text
stringlengths
2
1.1M
id
stringlengths
11
117
metadata
dict
__index_level_0__
int64
0
885
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package asn1 contains supporting types for parsing and building ASN.1 // messages with the cryptobyte package. package asn1 // Tag represents an ASN.1 identifier octet, consisting of a tag number // (indicating a type) and class (such as context-specific or constructed). // // Methods in the cryptobyte package only support the low-tag-number form, i.e. // a single identifier octet with bits 7-8 encoding the class and bits 1-6 // encoding the tag number. type Tag uint8 const ( classConstructed = 0x20 classContextSpecific = 0x80 ) // Constructed returns t with the constructed class bit set. func (t Tag) Constructed() Tag { return t | classConstructed } // ContextSpecific returns t with the context-specific class bit set. func (t Tag) ContextSpecific() Tag { return t | classContextSpecific } // The following is a list of standard tag and class combinations. const ( BOOLEAN = Tag(1) INTEGER = Tag(2) BIT_STRING = Tag(3) OCTET_STRING = Tag(4) NULL = Tag(5) OBJECT_IDENTIFIER = Tag(6) ENUM = Tag(10) UTF8String = Tag(12) SEQUENCE = Tag(16 | classConstructed) SET = Tag(17 | classConstructed) PrintableString = Tag(19) T61String = Tag(20) IA5String = Tag(22) UTCTime = Tag(23) GeneralizedTime = Tag(24) GeneralString = Tag(27) )
crypto/cryptobyte/asn1/asn1.go/0
{ "file_path": "crypto/cryptobyte/asn1/asn1.go", "repo_id": "crypto", "token_count": 570 }
4
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package wycheproof import ( "crypto/rsa" "testing" ) func TestRsa(t *testing.T) { // KeyJwk Public key in JWK format type KeyJwk struct { } // Notes a description of the labels used in the test vectors type Notes struct { } // SignatureTestVector type SignatureTestVector struct { // A brief description of the test case Comment string `json:"comment,omitempty"` // A list of flags Flags []string `json:"flags,omitempty"` // The message to sign Msg string `json:"msg,omitempty"` // Test result Result string `json:"result,omitempty"` // A signature for msg Sig string `json:"sig,omitempty"` // Identifier of the test case TcId int `json:"tcId,omitempty"` } // RsassaPkcs1TestGroup type RsassaPkcs1TestGroup struct { // The private exponent D string `json:"d,omitempty"` // The public exponent E string `json:"e,omitempty"` // ASN encoding of the sequence [n, e] KeyAsn string `json:"keyAsn,omitempty"` // ASN encoding of the public key KeyDer string `json:"keyDer,omitempty"` // Public key in JWK format KeyJwk *KeyJwk `json:"keyJwk,omitempty"` // Pem encoded public key KeyPem string `json:"keyPem,omitempty"` // the size of the modulus in bits KeySize int `json:"keySize,omitempty"` // The modulus of the key N string `json:"n,omitempty"` // the hash function used for the message Sha string `json:"sha,omitempty"` Tests []*SignatureTestVector `json:"tests,omitempty"` Type interface{} `json:"type,omitempty"` } // Root type Root struct { // the primitive tested in the test file Algorithm string `json:"algorithm,omitempty"` // the version of the test vectors. GeneratorVersion string `json:"generatorVersion,omitempty"` // additional documentation Header []string `json:"header,omitempty"` // a description of the labels used in the test vectors Notes *Notes `json:"notes,omitempty"` // the number of test vectors in this test NumberOfTests int `json:"numberOfTests,omitempty"` Schema interface{} `json:"schema,omitempty"` TestGroups []*RsassaPkcs1TestGroup `json:"testGroups,omitempty"` } flagsShouldPass := map[string]bool{ // Omitting the parameter field in an ASN encoded integer is a legacy behavior. "MissingNull": false, // Keys with a modulus less than 2048 bits are supported by crypto/rsa. "SmallModulus": true, // Small public keys are supported by crypto/rsa. "SmallPublicKey": true, } var root Root readTestVector(t, "rsa_signature_test.json", &root) for _, tg := range root.TestGroups { pub := decodePublicKey(tg.KeyDer).(*rsa.PublicKey) ch := parseHash(tg.Sha) h := ch.New() for _, sig := range tg.Tests { h.Reset() h.Write(decodeHex(sig.Msg)) hashed := h.Sum(nil) err := rsa.VerifyPKCS1v15(pub, ch, hashed, decodeHex(sig.Sig)) want := shouldPass(sig.Result, sig.Flags, flagsShouldPass) if (err == nil) != want { t.Errorf("tcid: %d, type: %s, comment: %q, wanted success: %t", sig.TcId, sig.Result, sig.Comment, want) } } } }
crypto/internal/wycheproof/rsa_signature_test.go/0
{ "file_path": "crypto/internal/wycheproof/rsa_signature_test.go", "repo_id": "crypto", "token_count": 1254 }
5
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sign import ( "bytes" "crypto/rand" "encoding/hex" "testing" ) var testSignedMessage, _ = hex.DecodeString("26a0a47f733d02ddb74589b6cbd6f64a7dab1947db79395a1a9e00e4c902c0f185b119897b89b248d16bab4ea781b5a3798d25c2984aec833dddab57e0891e0d68656c6c6f20776f726c64") var testMessage = testSignedMessage[Overhead:] var testPublicKey [32]byte var testPrivateKey = [64]byte{ 0x98, 0x3c, 0x6a, 0xa6, 0x21, 0xcc, 0xbb, 0xb2, 0xa7, 0xe8, 0x97, 0x94, 0xde, 0x5f, 0xf8, 0x11, 0x8a, 0xf3, 0x33, 0x1a, 0x03, 0x5c, 0x43, 0x99, 0x03, 0x13, 0x2d, 0xd7, 0xb4, 0xc4, 0x8b, 0xb0, 0xf6, 0x33, 0x20, 0xa3, 0x34, 0x8b, 0x7b, 0xe2, 0xfe, 0xb4, 0xe7, 0x3a, 0x54, 0x08, 0x2d, 0xd7, 0x0c, 0xb7, 0xc0, 0xe3, 0xbf, 0x62, 0x6c, 0x55, 0xf0, 0x33, 0x28, 0x52, 0xf8, 0x48, 0x7d, 0xfd, } func init() { copy(testPublicKey[:], testPrivateKey[32:]) } func TestSign(t *testing.T) { signedMessage := Sign(nil, testMessage, &testPrivateKey) if !bytes.Equal(signedMessage, testSignedMessage) { t.Fatalf("signed message did not match, got\n%x\n, expected\n%x", signedMessage, testSignedMessage) } } func TestOpen(t *testing.T) { message, ok := Open(nil, testSignedMessage, &testPublicKey) if !ok { t.Fatalf("valid signed message not successfully verified") } if !bytes.Equal(message, testMessage) { t.Fatalf("message did not match, got\n%x\n, expected\n%x", message, testMessage) } _, ok = Open(nil, testSignedMessage[1:], &testPublicKey) if ok { t.Fatalf("invalid signed message successfully verified") } badMessage := make([]byte, len(testSignedMessage)) copy(badMessage, testSignedMessage) badMessage[5] ^= 1 if _, ok := Open(nil, badMessage, &testPublicKey); ok { t.Fatalf("Open succeeded with a corrupt message") } var badPublicKey [32]byte copy(badPublicKey[:], testPublicKey[:]) badPublicKey[5] ^= 1 if _, ok := Open(nil, testSignedMessage, &badPublicKey); ok { t.Fatalf("Open succeeded with a corrupt public key") } } func TestGenerateSignOpen(t *testing.T) { publicKey, privateKey, _ := GenerateKey(rand.Reader) signedMessage := Sign(nil, testMessage, privateKey) message, ok := Open(nil, signedMessage, publicKey) if !ok { t.Fatalf("failed to verify signed message") } if !bytes.Equal(message, testMessage) { t.Fatalf("verified message does not match signed messge, got\n%x\n, expected\n%x", message, testMessage) } }
crypto/nacl/sign/sign_test.go/0
{ "file_path": "crypto/nacl/sign/sign_test.go", "repo_id": "crypto", "token_count": 1073 }
6
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "compress/bzip2" "compress/flate" "compress/zlib" "golang.org/x/crypto/openpgp/errors" "io" "strconv" ) // Compressed represents a compressed OpenPGP packet. The decompressed contents // will contain more OpenPGP packets. See RFC 4880, section 5.6. type Compressed struct { Body io.Reader } const ( NoCompression = flate.NoCompression BestSpeed = flate.BestSpeed BestCompression = flate.BestCompression DefaultCompression = flate.DefaultCompression ) // CompressionConfig contains compressor configuration settings. type CompressionConfig struct { // Level is the compression level to use. It must be set to // between -1 and 9, with -1 causing the compressor to use the // default compression level, 0 causing the compressor to use // no compression and 1 to 9 representing increasing (better, // slower) compression levels. If Level is less than -1 or // more then 9, a non-nil error will be returned during // encryption. See the constants above for convenient common // settings for Level. Level int } func (c *Compressed) parse(r io.Reader) error { var buf [1]byte _, err := readFull(r, buf[:]) if err != nil { return err } switch buf[0] { case 1: c.Body = flate.NewReader(r) case 2: c.Body, err = zlib.NewReader(r) case 3: c.Body = bzip2.NewReader(r) default: err = errors.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0]))) } return err } // compressedWriteCloser represents the serialized compression stream // header and the compressor. Its Close() method ensures that both the // compressor and serialized stream header are closed. Its Write() // method writes to the compressor. type compressedWriteCloser struct { sh io.Closer // Stream Header c io.WriteCloser // Compressor } func (cwc compressedWriteCloser) Write(p []byte) (int, error) { return cwc.c.Write(p) } func (cwc compressedWriteCloser) Close() (err error) { err = cwc.c.Close() if err != nil { return err } return cwc.sh.Close() } // SerializeCompressed serializes a compressed data packet to w and // returns a WriteCloser to which the literal data packets themselves // can be written and which MUST be closed on completion. If cc is // nil, sensible defaults will be used to configure the compression // algorithm. func SerializeCompressed(w io.WriteCloser, algo CompressionAlgo, cc *CompressionConfig) (literaldata io.WriteCloser, err error) { compressed, err := serializeStreamHeader(w, packetTypeCompressed) if err != nil { return } _, err = compressed.Write([]byte{uint8(algo)}) if err != nil { return } level := DefaultCompression if cc != nil { level = cc.Level } var compressor io.WriteCloser switch algo { case CompressionZIP: compressor, err = flate.NewWriter(compressed, level) case CompressionZLIB: compressor, err = zlib.NewWriterLevel(compressed, level) default: s := strconv.Itoa(int(algo)) err = errors.UnsupportedError("Unsupported compression algorithm: " + s) } if err != nil { return } literaldata = compressedWriteCloser{compressed, compressor} return }
crypto/openpgp/packet/compressed.go/0
{ "file_path": "crypto/openpgp/packet/compressed.go", "repo_id": "crypto", "token_count": 1064 }
7
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package openpgp implements high level operations on OpenPGP messages. // // Deprecated: this package is unmaintained except for security fixes. New // applications should consider a more focused, modern alternative to OpenPGP // for their specific task. If you are required to interoperate with OpenPGP // systems and need a maintained package, consider a community fork. // See https://golang.org/issue/44226. package openpgp import ( "crypto" _ "crypto/sha256" "hash" "io" "strconv" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/errors" "golang.org/x/crypto/openpgp/packet" ) // SignatureType is the armor type for a PGP signature. var SignatureType = "PGP SIGNATURE" // readArmored reads an armored block with the given type. func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) { block, err := armor.Decode(r) if err != nil { return } if block.Type != expectedType { return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) } return block.Body, nil } // MessageDetails contains the result of parsing an OpenPGP encrypted and/or // signed message. type MessageDetails struct { IsEncrypted bool // true if the message was encrypted. EncryptedToKeyIds []uint64 // the list of recipient key ids. IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message. DecryptedWith Key // the private key used to decrypt the message, if any. IsSigned bool // true if the message is signed. SignedByKeyId uint64 // the key id of the signer, if any. SignedBy *Key // the key of the signer, if available. LiteralData *packet.LiteralData // the metadata of the contents UnverifiedBody io.Reader // the contents of the message. // If IsSigned is true and SignedBy is non-zero then the signature will // be verified as UnverifiedBody is read. The signature cannot be // checked until the whole of UnverifiedBody is read so UnverifiedBody // must be consumed until EOF before the data can be trusted. Even if a // message isn't signed (or the signer is unknown) the data may contain // an authentication code that is only checked once UnverifiedBody has // been consumed. Once EOF has been seen, the following fields are // valid. (An authentication code failure is reported as a // SignatureError error when reading from UnverifiedBody.) SignatureError error // nil if the signature is good. Signature *packet.Signature // the signature packet itself, if v4 (default) SignatureV3 *packet.SignatureV3 // the signature packet if it is a v2 or v3 signature decrypted io.ReadCloser } // A PromptFunction is used as a callback by functions that may need to decrypt // a private key, or prompt for a passphrase. It is called with a list of // acceptable, encrypted private keys and a boolean that indicates whether a // passphrase is usable. It should either decrypt a private key or return a // passphrase to try. If the decrypted private key or given passphrase isn't // correct, the function will be called again, forever. Any error returned will // be passed up. type PromptFunction func(keys []Key, symmetric bool) ([]byte, error) // A keyEnvelopePair is used to store a private key with the envelope that // contains a symmetric key, encrypted with that key. type keyEnvelopePair struct { key Key encryptedKey *packet.EncryptedKey } // ReadMessage parses an OpenPGP message that may be signed and/or encrypted. // The given KeyRing should contain both public keys (for signature // verification) and, possibly encrypted, private keys for decrypting. // If config is nil, sensible defaults will be used. func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) { var p packet.Packet var symKeys []*packet.SymmetricKeyEncrypted var pubKeys []keyEnvelopePair var se *packet.SymmetricallyEncrypted packets := packet.NewReader(r) md = new(MessageDetails) md.IsEncrypted = true // The message, if encrypted, starts with a number of packets // containing an encrypted decryption key. The decryption key is either // encrypted to a public key, or with a passphrase. This loop // collects these packets. ParsePackets: for { p, err = packets.Next() if err != nil { return nil, err } switch p := p.(type) { case *packet.SymmetricKeyEncrypted: // This packet contains the decryption key encrypted with a passphrase. md.IsSymmetricallyEncrypted = true symKeys = append(symKeys, p) case *packet.EncryptedKey: // This packet contains the decryption key encrypted to a public key. md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId) switch p.Algo { case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal: break default: continue } var keys []Key if p.KeyId == 0 { keys = keyring.DecryptionKeys() } else { keys = keyring.KeysById(p.KeyId) } for _, k := range keys { pubKeys = append(pubKeys, keyEnvelopePair{k, p}) } case *packet.SymmetricallyEncrypted: se = p break ParsePackets case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature: // This message isn't encrypted. if len(symKeys) != 0 || len(pubKeys) != 0 { return nil, errors.StructuralError("key material not followed by encrypted message") } packets.Unread(p) return readSignedMessage(packets, nil, keyring) } } var candidates []Key var decrypted io.ReadCloser // Now that we have the list of encrypted keys we need to decrypt at // least one of them or, if we cannot, we need to call the prompt // function so that it can decrypt a key or give us a passphrase. FindKey: for { // See if any of the keys already have a private key available candidates = candidates[:0] candidateFingerprints := make(map[string]bool) for _, pk := range pubKeys { if pk.key.PrivateKey == nil { continue } if !pk.key.PrivateKey.Encrypted { if len(pk.encryptedKey.Key) == 0 { pk.encryptedKey.Decrypt(pk.key.PrivateKey, config) } if len(pk.encryptedKey.Key) == 0 { continue } decrypted, err = se.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key) if err != nil && err != errors.ErrKeyIncorrect { return nil, err } if decrypted != nil { md.DecryptedWith = pk.key break FindKey } } else { fpr := string(pk.key.PublicKey.Fingerprint[:]) if v := candidateFingerprints[fpr]; v { continue } candidates = append(candidates, pk.key) candidateFingerprints[fpr] = true } } if len(candidates) == 0 && len(symKeys) == 0 { return nil, errors.ErrKeyIncorrect } if prompt == nil { return nil, errors.ErrKeyIncorrect } passphrase, err := prompt(candidates, len(symKeys) != 0) if err != nil { return nil, err } // Try the symmetric passphrase first if len(symKeys) != 0 && passphrase != nil { for _, s := range symKeys { key, cipherFunc, err := s.Decrypt(passphrase) if err == nil { decrypted, err = se.Decrypt(cipherFunc, key) if err != nil && err != errors.ErrKeyIncorrect { return nil, err } if decrypted != nil { break FindKey } } } } } md.decrypted = decrypted if err := packets.Push(decrypted); err != nil { return nil, err } return readSignedMessage(packets, md, keyring) } // readSignedMessage reads a possibly signed message if mdin is non-zero then // that structure is updated and returned. Otherwise a fresh MessageDetails is // used. func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing) (md *MessageDetails, err error) { if mdin == nil { mdin = new(MessageDetails) } md = mdin var p packet.Packet var h hash.Hash var wrappedHash hash.Hash FindLiteralData: for { p, err = packets.Next() if err != nil { return nil, err } switch p := p.(type) { case *packet.Compressed: if err := packets.Push(p.Body); err != nil { return nil, err } case *packet.OnePassSignature: if !p.IsLast { return nil, errors.UnsupportedError("nested signatures") } h, wrappedHash, err = hashForSignature(p.Hash, p.SigType) if err != nil { md = nil return } md.IsSigned = true md.SignedByKeyId = p.KeyId keys := keyring.KeysByIdUsage(p.KeyId, packet.KeyFlagSign) if len(keys) > 0 { md.SignedBy = &keys[0] } case *packet.LiteralData: md.LiteralData = p break FindLiteralData } } if md.SignedBy != nil { md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md} } else if md.decrypted != nil { md.UnverifiedBody = checkReader{md} } else { md.UnverifiedBody = md.LiteralData.Body } return md, nil } // hashForSignature returns a pair of hashes that can be used to verify a // signature. The signature may specify that the contents of the signed message // should be preprocessed (i.e. to normalize line endings). Thus this function // returns two hashes. The second should be used to hash the message itself and // performs any needed preprocessing. func hashForSignature(hashId crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) { if !hashId.Available() { return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashId))) } h := hashId.New() switch sigType { case packet.SigTypeBinary: return h, h, nil case packet.SigTypeText: return h, NewCanonicalTextHash(h), nil } return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType))) } // checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF // it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger // MDC checks. type checkReader struct { md *MessageDetails } func (cr checkReader) Read(buf []byte) (n int, err error) { n, err = cr.md.LiteralData.Body.Read(buf) if err == io.EOF { mdcErr := cr.md.decrypted.Close() if mdcErr != nil { err = mdcErr } } return } // signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes // the data as it is read. When it sees an EOF from the underlying io.Reader // it parses and checks a trailing Signature packet and triggers any MDC checks. type signatureCheckReader struct { packets *packet.Reader h, wrappedHash hash.Hash md *MessageDetails } func (scr *signatureCheckReader) Read(buf []byte) (n int, err error) { n, err = scr.md.LiteralData.Body.Read(buf) scr.wrappedHash.Write(buf[:n]) if err == io.EOF { var p packet.Packet p, scr.md.SignatureError = scr.packets.Next() if scr.md.SignatureError != nil { return } var ok bool if scr.md.Signature, ok = p.(*packet.Signature); ok { scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignature(scr.h, scr.md.Signature) } else if scr.md.SignatureV3, ok = p.(*packet.SignatureV3); ok { scr.md.SignatureError = scr.md.SignedBy.PublicKey.VerifySignatureV3(scr.h, scr.md.SignatureV3) } else { scr.md.SignatureError = errors.StructuralError("LiteralData not followed by Signature") return } // The SymmetricallyEncrypted packet, if any, might have an // unsigned hash of its own. In order to check this we need to // close that Reader. if scr.md.decrypted != nil { mdcErr := scr.md.decrypted.Close() if mdcErr != nil { err = mdcErr } } } return } // CheckDetachedSignature takes a signed file and a detached signature and // returns the signer if the signature is valid. If the signer isn't known, // ErrUnknownIssuer is returned. func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { var issuerKeyId uint64 var hashFunc crypto.Hash var sigType packet.SignatureType var keys []Key var p packet.Packet packets := packet.NewReader(signature) for { p, err = packets.Next() if err == io.EOF { return nil, errors.ErrUnknownIssuer } if err != nil { return nil, err } switch sig := p.(type) { case *packet.Signature: if sig.IssuerKeyId == nil { return nil, errors.StructuralError("signature doesn't have an issuer") } issuerKeyId = *sig.IssuerKeyId hashFunc = sig.Hash sigType = sig.SigType case *packet.SignatureV3: issuerKeyId = sig.IssuerKeyId hashFunc = sig.Hash sigType = sig.SigType default: return nil, errors.StructuralError("non signature packet found") } keys = keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign) if len(keys) > 0 { break } } if len(keys) == 0 { panic("unreachable") } h, wrappedHash, err := hashForSignature(hashFunc, sigType) if err != nil { return nil, err } if _, err := io.Copy(wrappedHash, signed); err != nil && err != io.EOF { return nil, err } for _, key := range keys { switch sig := p.(type) { case *packet.Signature: err = key.PublicKey.VerifySignature(h, sig) case *packet.SignatureV3: err = key.PublicKey.VerifySignatureV3(h, sig) default: panic("unreachable") } if err == nil { return key.Entity, nil } } return nil, err } // CheckArmoredDetachedSignature performs the same actions as // CheckDetachedSignature but expects the signature to be armored. func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader) (signer *Entity, err error) { body, err := readArmored(signature, SignatureType) if err != nil { return } return CheckDetachedSignature(keyring, signed, body) }
crypto/openpgp/read.go/0
{ "file_path": "crypto/openpgp/read.go", "repo_id": "crypto", "token_count": 5066 }
8
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkcs12 import "errors" var ( // ErrDecryption represents a failure to decrypt the input. ErrDecryption = errors.New("pkcs12: decryption error, incorrect padding") // ErrIncorrectPassword is returned when an incorrect password is detected. // Usually, P12/PFX data is signed to be able to verify the password. ErrIncorrectPassword = errors.New("pkcs12: decryption password incorrect") ) // NotImplementedError indicates that the input is not currently supported. type NotImplementedError string func (e NotImplementedError) Error() string { return "pkcs12: " + string(e) }
crypto/pkcs12/errors.go/0
{ "file_path": "crypto/pkcs12/errors.go", "repo_id": "crypto", "token_count": 212 }
9
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package salsa import "math/bits" // Core208 applies the Salsa20/8 core function to the 64-byte array in and puts // the result into the 64-byte array out. The input and output may be the same array. func Core208(out *[64]byte, in *[64]byte) { j0 := uint32(in[0]) | uint32(in[1])<<8 | uint32(in[2])<<16 | uint32(in[3])<<24 j1 := uint32(in[4]) | uint32(in[5])<<8 | uint32(in[6])<<16 | uint32(in[7])<<24 j2 := uint32(in[8]) | uint32(in[9])<<8 | uint32(in[10])<<16 | uint32(in[11])<<24 j3 := uint32(in[12]) | uint32(in[13])<<8 | uint32(in[14])<<16 | uint32(in[15])<<24 j4 := uint32(in[16]) | uint32(in[17])<<8 | uint32(in[18])<<16 | uint32(in[19])<<24 j5 := uint32(in[20]) | uint32(in[21])<<8 | uint32(in[22])<<16 | uint32(in[23])<<24 j6 := uint32(in[24]) | uint32(in[25])<<8 | uint32(in[26])<<16 | uint32(in[27])<<24 j7 := uint32(in[28]) | uint32(in[29])<<8 | uint32(in[30])<<16 | uint32(in[31])<<24 j8 := uint32(in[32]) | uint32(in[33])<<8 | uint32(in[34])<<16 | uint32(in[35])<<24 j9 := uint32(in[36]) | uint32(in[37])<<8 | uint32(in[38])<<16 | uint32(in[39])<<24 j10 := uint32(in[40]) | uint32(in[41])<<8 | uint32(in[42])<<16 | uint32(in[43])<<24 j11 := uint32(in[44]) | uint32(in[45])<<8 | uint32(in[46])<<16 | uint32(in[47])<<24 j12 := uint32(in[48]) | uint32(in[49])<<8 | uint32(in[50])<<16 | uint32(in[51])<<24 j13 := uint32(in[52]) | uint32(in[53])<<8 | uint32(in[54])<<16 | uint32(in[55])<<24 j14 := uint32(in[56]) | uint32(in[57])<<8 | uint32(in[58])<<16 | uint32(in[59])<<24 j15 := uint32(in[60]) | uint32(in[61])<<8 | uint32(in[62])<<16 | uint32(in[63])<<24 x0, x1, x2, x3, x4, x5, x6, x7, x8 := j0, j1, j2, j3, j4, j5, j6, j7, j8 x9, x10, x11, x12, x13, x14, x15 := j9, j10, j11, j12, j13, j14, j15 for i := 0; i < 8; i += 2 { u := x0 + x12 x4 ^= bits.RotateLeft32(u, 7) u = x4 + x0 x8 ^= bits.RotateLeft32(u, 9) u = x8 + x4 x12 ^= bits.RotateLeft32(u, 13) u = x12 + x8 x0 ^= bits.RotateLeft32(u, 18) u = x5 + x1 x9 ^= bits.RotateLeft32(u, 7) u = x9 + x5 x13 ^= bits.RotateLeft32(u, 9) u = x13 + x9 x1 ^= bits.RotateLeft32(u, 13) u = x1 + x13 x5 ^= bits.RotateLeft32(u, 18) u = x10 + x6 x14 ^= bits.RotateLeft32(u, 7) u = x14 + x10 x2 ^= bits.RotateLeft32(u, 9) u = x2 + x14 x6 ^= bits.RotateLeft32(u, 13) u = x6 + x2 x10 ^= bits.RotateLeft32(u, 18) u = x15 + x11 x3 ^= bits.RotateLeft32(u, 7) u = x3 + x15 x7 ^= bits.RotateLeft32(u, 9) u = x7 + x3 x11 ^= bits.RotateLeft32(u, 13) u = x11 + x7 x15 ^= bits.RotateLeft32(u, 18) u = x0 + x3 x1 ^= bits.RotateLeft32(u, 7) u = x1 + x0 x2 ^= bits.RotateLeft32(u, 9) u = x2 + x1 x3 ^= bits.RotateLeft32(u, 13) u = x3 + x2 x0 ^= bits.RotateLeft32(u, 18) u = x5 + x4 x6 ^= bits.RotateLeft32(u, 7) u = x6 + x5 x7 ^= bits.RotateLeft32(u, 9) u = x7 + x6 x4 ^= bits.RotateLeft32(u, 13) u = x4 + x7 x5 ^= bits.RotateLeft32(u, 18) u = x10 + x9 x11 ^= bits.RotateLeft32(u, 7) u = x11 + x10 x8 ^= bits.RotateLeft32(u, 9) u = x8 + x11 x9 ^= bits.RotateLeft32(u, 13) u = x9 + x8 x10 ^= bits.RotateLeft32(u, 18) u = x15 + x14 x12 ^= bits.RotateLeft32(u, 7) u = x12 + x15 x13 ^= bits.RotateLeft32(u, 9) u = x13 + x12 x14 ^= bits.RotateLeft32(u, 13) u = x14 + x13 x15 ^= bits.RotateLeft32(u, 18) } x0 += j0 x1 += j1 x2 += j2 x3 += j3 x4 += j4 x5 += j5 x6 += j6 x7 += j7 x8 += j8 x9 += j9 x10 += j10 x11 += j11 x12 += j12 x13 += j13 x14 += j14 x15 += j15 out[0] = byte(x0) out[1] = byte(x0 >> 8) out[2] = byte(x0 >> 16) out[3] = byte(x0 >> 24) out[4] = byte(x1) out[5] = byte(x1 >> 8) out[6] = byte(x1 >> 16) out[7] = byte(x1 >> 24) out[8] = byte(x2) out[9] = byte(x2 >> 8) out[10] = byte(x2 >> 16) out[11] = byte(x2 >> 24) out[12] = byte(x3) out[13] = byte(x3 >> 8) out[14] = byte(x3 >> 16) out[15] = byte(x3 >> 24) out[16] = byte(x4) out[17] = byte(x4 >> 8) out[18] = byte(x4 >> 16) out[19] = byte(x4 >> 24) out[20] = byte(x5) out[21] = byte(x5 >> 8) out[22] = byte(x5 >> 16) out[23] = byte(x5 >> 24) out[24] = byte(x6) out[25] = byte(x6 >> 8) out[26] = byte(x6 >> 16) out[27] = byte(x6 >> 24) out[28] = byte(x7) out[29] = byte(x7 >> 8) out[30] = byte(x7 >> 16) out[31] = byte(x7 >> 24) out[32] = byte(x8) out[33] = byte(x8 >> 8) out[34] = byte(x8 >> 16) out[35] = byte(x8 >> 24) out[36] = byte(x9) out[37] = byte(x9 >> 8) out[38] = byte(x9 >> 16) out[39] = byte(x9 >> 24) out[40] = byte(x10) out[41] = byte(x10 >> 8) out[42] = byte(x10 >> 16) out[43] = byte(x10 >> 24) out[44] = byte(x11) out[45] = byte(x11 >> 8) out[46] = byte(x11 >> 16) out[47] = byte(x11 >> 24) out[48] = byte(x12) out[49] = byte(x12 >> 8) out[50] = byte(x12 >> 16) out[51] = byte(x12 >> 24) out[52] = byte(x13) out[53] = byte(x13 >> 8) out[54] = byte(x13 >> 16) out[55] = byte(x13 >> 24) out[56] = byte(x14) out[57] = byte(x14 >> 8) out[58] = byte(x14 >> 16) out[59] = byte(x14 >> 24) out[60] = byte(x15) out[61] = byte(x15 >> 8) out[62] = byte(x15 >> 16) out[63] = byte(x15 >> 24) }
crypto/salsa20/salsa/salsa208.go/0
{ "file_path": "crypto/salsa20/salsa/salsa208.go", "repo_id": "crypto", "token_count": 2779 }
10
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package agent_test import ( "log" "net" "os" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" ) func ExampleNewClient() { // ssh-agent(1) provides a UNIX socket at $SSH_AUTH_SOCK. socket := os.Getenv("SSH_AUTH_SOCK") conn, err := net.Dial("unix", socket) if err != nil { log.Fatalf("Failed to open SSH_AUTH_SOCK: %v", err) } agentClient := agent.NewClient(conn) config := &ssh.ClientConfig{ User: "gopher", Auth: []ssh.AuthMethod{ // Use a callback rather than PublicKeys so we only consult the // agent once the remote server wants it. ssh.PublicKeysCallback(agentClient.Signers), }, HostKeyCallback: ssh.InsecureIgnoreHostKey(), } sshc, err := ssh.Dial("tcp", "localhost:22", config) if err != nil { log.Fatal(err) } // Use sshc... sshc.Close() }
crypto/ssh/agent/example_test.go/0
{ "file_path": "crypto/ssh/agent/example_test.go", "repo_id": "crypto", "token_count": 370 }
11
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "bytes" "errors" "fmt" "io" "strings" ) type authResult int const ( authFailure authResult = iota authPartialSuccess authSuccess ) // clientAuthenticate authenticates with the remote server. See RFC 4252. func (c *connection) clientAuthenticate(config *ClientConfig) error { // initiate user auth session if err := c.transport.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})); err != nil { return err } packet, err := c.transport.readPacket() if err != nil { return err } // The server may choose to send a SSH_MSG_EXT_INFO at this point (if we // advertised willingness to receive one, which we always do) or not. See // RFC 8308, Section 2.4. extensions := make(map[string][]byte) if len(packet) > 0 && packet[0] == msgExtInfo { var extInfo extInfoMsg if err := Unmarshal(packet, &extInfo); err != nil { return err } payload := extInfo.Payload for i := uint32(0); i < extInfo.NumExtensions; i++ { name, rest, ok := parseString(payload) if !ok { return parseError(msgExtInfo) } value, rest, ok := parseString(rest) if !ok { return parseError(msgExtInfo) } extensions[string(name)] = value payload = rest } packet, err = c.transport.readPacket() if err != nil { return err } } var serviceAccept serviceAcceptMsg if err := Unmarshal(packet, &serviceAccept); err != nil { return err } // during the authentication phase the client first attempts the "none" method // then any untried methods suggested by the server. var tried []string var lastMethods []string sessionID := c.transport.getSessionID() for auth := AuthMethod(new(noneAuth)); auth != nil; { ok, methods, err := auth.auth(sessionID, config.User, c.transport, config.Rand, extensions) if err != nil { // On disconnect, return error immediately if _, ok := err.(*disconnectMsg); ok { return err } // We return the error later if there is no other method left to // try. ok = authFailure } if ok == authSuccess { // success return nil } else if ok == authFailure { if m := auth.method(); !contains(tried, m) { tried = append(tried, m) } } if methods == nil { methods = lastMethods } lastMethods = methods auth = nil findNext: for _, a := range config.Auth { candidateMethod := a.method() if contains(tried, candidateMethod) { continue } for _, meth := range methods { if meth == candidateMethod { auth = a break findNext } } } if auth == nil && err != nil { // We have an error and there are no other authentication methods to // try, so we return it. return err } } return fmt.Errorf("ssh: unable to authenticate, attempted methods %v, no supported methods remain", tried) } func contains(list []string, e string) bool { for _, s := range list { if s == e { return true } } return false } // An AuthMethod represents an instance of an RFC 4252 authentication method. type AuthMethod interface { // auth authenticates user over transport t. // Returns true if authentication is successful. // If authentication is not successful, a []string of alternative // method names is returned. If the slice is nil, it will be ignored // and the previous set of possible methods will be reused. auth(session []byte, user string, p packetConn, rand io.Reader, extensions map[string][]byte) (authResult, []string, error) // method returns the RFC 4252 method name. method() string } // "none" authentication, RFC 4252 section 5.2. type noneAuth int func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) { if err := c.writePacket(Marshal(&userAuthRequestMsg{ User: user, Service: serviceSSH, Method: "none", })); err != nil { return authFailure, nil, err } return handleAuthResponse(c) } func (n *noneAuth) method() string { return "none" } // passwordCallback is an AuthMethod that fetches the password through // a function call, e.g. by prompting the user. type passwordCallback func() (password string, err error) func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) { type passwordAuthMsg struct { User string `sshtype:"50"` Service string Method string Reply bool Password string } pw, err := cb() // REVIEW NOTE: is there a need to support skipping a password attempt? // The program may only find out that the user doesn't have a password // when prompting. if err != nil { return authFailure, nil, err } if err := c.writePacket(Marshal(&passwordAuthMsg{ User: user, Service: serviceSSH, Method: cb.method(), Reply: false, Password: pw, })); err != nil { return authFailure, nil, err } return handleAuthResponse(c) } func (cb passwordCallback) method() string { return "password" } // Password returns an AuthMethod using the given password. func Password(secret string) AuthMethod { return passwordCallback(func() (string, error) { return secret, nil }) } // PasswordCallback returns an AuthMethod that uses a callback for // fetching a password. func PasswordCallback(prompt func() (secret string, err error)) AuthMethod { return passwordCallback(prompt) } type publickeyAuthMsg struct { User string `sshtype:"50"` Service string Method string // HasSig indicates to the receiver packet that the auth request is signed and // should be used for authentication of the request. HasSig bool Algoname string PubKey []byte // Sig is tagged with "rest" so Marshal will exclude it during // validateKey Sig []byte `ssh:"rest"` } // publicKeyCallback is an AuthMethod that uses a set of key // pairs for authentication. type publicKeyCallback func() ([]Signer, error) func (cb publicKeyCallback) method() string { return "publickey" } func pickSignatureAlgorithm(signer Signer, extensions map[string][]byte) (MultiAlgorithmSigner, string, error) { var as MultiAlgorithmSigner keyFormat := signer.PublicKey().Type() // If the signer implements MultiAlgorithmSigner we use the algorithms it // support, if it implements AlgorithmSigner we assume it supports all // algorithms, otherwise only the key format one. switch s := signer.(type) { case MultiAlgorithmSigner: as = s case AlgorithmSigner: as = &multiAlgorithmSigner{ AlgorithmSigner: s, supportedAlgorithms: algorithmsForKeyFormat(underlyingAlgo(keyFormat)), } default: as = &multiAlgorithmSigner{ AlgorithmSigner: algorithmSignerWrapper{signer}, supportedAlgorithms: []string{underlyingAlgo(keyFormat)}, } } getFallbackAlgo := func() (string, error) { // Fallback to use if there is no "server-sig-algs" extension or a // common algorithm cannot be found. We use the public key format if the // MultiAlgorithmSigner supports it, otherwise we return an error. if !contains(as.Algorithms(), underlyingAlgo(keyFormat)) { return "", fmt.Errorf("ssh: no common public key signature algorithm, server only supports %q for key type %q, signer only supports %v", underlyingAlgo(keyFormat), keyFormat, as.Algorithms()) } return keyFormat, nil } extPayload, ok := extensions["server-sig-algs"] if !ok { // If there is no "server-sig-algs" extension use the fallback // algorithm. algo, err := getFallbackAlgo() return as, algo, err } // The server-sig-algs extension only carries underlying signature // algorithm, but we are trying to select a protocol-level public key // algorithm, which might be a certificate type. Extend the list of server // supported algorithms to include the corresponding certificate algorithms. serverAlgos := strings.Split(string(extPayload), ",") for _, algo := range serverAlgos { if certAlgo, ok := certificateAlgo(algo); ok { serverAlgos = append(serverAlgos, certAlgo) } } // Filter algorithms based on those supported by MultiAlgorithmSigner. var keyAlgos []string for _, algo := range algorithmsForKeyFormat(keyFormat) { if contains(as.Algorithms(), underlyingAlgo(algo)) { keyAlgos = append(keyAlgos, algo) } } algo, err := findCommon("public key signature algorithm", keyAlgos, serverAlgos) if err != nil { // If there is no overlap, return the fallback algorithm to support // servers that fail to list all supported algorithms. algo, err := getFallbackAlgo() return as, algo, err } return as, algo, nil } func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader, extensions map[string][]byte) (authResult, []string, error) { // Authentication is performed by sending an enquiry to test if a key is // acceptable to the remote. If the key is acceptable, the client will // attempt to authenticate with the valid key. If not the client will repeat // the process with the remaining keys. signers, err := cb() if err != nil { return authFailure, nil, err } var methods []string var errSigAlgo error origSignersLen := len(signers) for idx := 0; idx < len(signers); idx++ { signer := signers[idx] pub := signer.PublicKey() as, algo, err := pickSignatureAlgorithm(signer, extensions) if err != nil && errSigAlgo == nil { // If we cannot negotiate a signature algorithm store the first // error so we can return it to provide a more meaningful message if // no other signers work. errSigAlgo = err continue } ok, err := validateKey(pub, algo, user, c) if err != nil { return authFailure, nil, err } // OpenSSH 7.2-7.7 advertises support for rsa-sha2-256 and rsa-sha2-512 // in the "server-sig-algs" extension but doesn't support these // algorithms for certificate authentication, so if the server rejects // the key try to use the obtained algorithm as if "server-sig-algs" had // not been implemented if supported from the algorithm signer. if !ok && idx < origSignersLen && isRSACert(algo) && algo != CertAlgoRSAv01 { if contains(as.Algorithms(), KeyAlgoRSA) { // We retry using the compat algorithm after all signers have // been tried normally. signers = append(signers, &multiAlgorithmSigner{ AlgorithmSigner: as, supportedAlgorithms: []string{KeyAlgoRSA}, }) } } if !ok { continue } pubKey := pub.Marshal() data := buildDataSignedForAuth(session, userAuthRequestMsg{ User: user, Service: serviceSSH, Method: cb.method(), }, algo, pubKey) sign, err := as.SignWithAlgorithm(rand, data, underlyingAlgo(algo)) if err != nil { return authFailure, nil, err } // manually wrap the serialized signature in a string s := Marshal(sign) sig := make([]byte, stringLength(len(s))) marshalString(sig, s) msg := publickeyAuthMsg{ User: user, Service: serviceSSH, Method: cb.method(), HasSig: true, Algoname: algo, PubKey: pubKey, Sig: sig, } p := Marshal(&msg) if err := c.writePacket(p); err != nil { return authFailure, nil, err } var success authResult success, methods, err = handleAuthResponse(c) if err != nil { return authFailure, nil, err } // If authentication succeeds or the list of available methods does not // contain the "publickey" method, do not attempt to authenticate with any // other keys. According to RFC 4252 Section 7, the latter can occur when // additional authentication methods are required. if success == authSuccess || !contains(methods, cb.method()) { return success, methods, err } } return authFailure, methods, errSigAlgo } // validateKey validates the key provided is acceptable to the server. func validateKey(key PublicKey, algo string, user string, c packetConn) (bool, error) { pubKey := key.Marshal() msg := publickeyAuthMsg{ User: user, Service: serviceSSH, Method: "publickey", HasSig: false, Algoname: algo, PubKey: pubKey, } if err := c.writePacket(Marshal(&msg)); err != nil { return false, err } return confirmKeyAck(key, c) } func confirmKeyAck(key PublicKey, c packetConn) (bool, error) { pubKey := key.Marshal() for { packet, err := c.readPacket() if err != nil { return false, err } switch packet[0] { case msgUserAuthBanner: if err := handleBannerResponse(c, packet); err != nil { return false, err } case msgUserAuthPubKeyOk: var msg userAuthPubKeyOkMsg if err := Unmarshal(packet, &msg); err != nil { return false, err } // According to RFC 4252 Section 7 the algorithm in // SSH_MSG_USERAUTH_PK_OK should match that of the request but some // servers send the key type instead. OpenSSH allows any algorithm // that matches the public key, so we do the same. // https://github.com/openssh/openssh-portable/blob/86bdd385/sshconnect2.c#L709 if !contains(algorithmsForKeyFormat(key.Type()), msg.Algo) { return false, nil } if !bytes.Equal(msg.PubKey, pubKey) { return false, nil } return true, nil case msgUserAuthFailure: return false, nil default: return false, unexpectedMessageError(msgUserAuthPubKeyOk, packet[0]) } } } // PublicKeys returns an AuthMethod that uses the given key // pairs. func PublicKeys(signers ...Signer) AuthMethod { return publicKeyCallback(func() ([]Signer, error) { return signers, nil }) } // PublicKeysCallback returns an AuthMethod that runs the given // function to obtain a list of key pairs. func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMethod { return publicKeyCallback(getSigners) } // handleAuthResponse returns whether the preceding authentication request succeeded // along with a list of remaining authentication methods to try next and // an error if an unexpected response was received. func handleAuthResponse(c packetConn) (authResult, []string, error) { gotMsgExtInfo := false for { packet, err := c.readPacket() if err != nil { return authFailure, nil, err } switch packet[0] { case msgUserAuthBanner: if err := handleBannerResponse(c, packet); err != nil { return authFailure, nil, err } case msgExtInfo: // Ignore post-authentication RFC 8308 extensions, once. if gotMsgExtInfo { return authFailure, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) } gotMsgExtInfo = true case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { return authFailure, nil, err } if msg.PartialSuccess { return authPartialSuccess, msg.Methods, nil } return authFailure, msg.Methods, nil case msgUserAuthSuccess: return authSuccess, nil, nil default: return authFailure, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) } } } func handleBannerResponse(c packetConn, packet []byte) error { var msg userAuthBannerMsg if err := Unmarshal(packet, &msg); err != nil { return err } transport, ok := c.(*handshakeTransport) if !ok { return nil } if transport.bannerCallback != nil { return transport.bannerCallback(msg.Message) } return nil } // KeyboardInteractiveChallenge should print questions, optionally // disabling echoing (e.g. for passwords), and return all the answers. // Challenge may be called multiple times in a single session. After // successful authentication, the server may send a challenge with no // questions, for which the name and instruction messages should be // printed. RFC 4256 section 3.3 details how the UI should behave for // both CLI and GUI environments. type KeyboardInteractiveChallenge func(name, instruction string, questions []string, echos []bool) (answers []string, err error) // KeyboardInteractive returns an AuthMethod using a prompt/response // sequence controlled by the server. func KeyboardInteractive(challenge KeyboardInteractiveChallenge) AuthMethod { return challenge } func (cb KeyboardInteractiveChallenge) method() string { return "keyboard-interactive" } func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) { type initiateMsg struct { User string `sshtype:"50"` Service string Method string Language string Submethods string } if err := c.writePacket(Marshal(&initiateMsg{ User: user, Service: serviceSSH, Method: "keyboard-interactive", })); err != nil { return authFailure, nil, err } gotMsgExtInfo := false for { packet, err := c.readPacket() if err != nil { return authFailure, nil, err } // like handleAuthResponse, but with less options. switch packet[0] { case msgUserAuthBanner: if err := handleBannerResponse(c, packet); err != nil { return authFailure, nil, err } continue case msgExtInfo: // Ignore post-authentication RFC 8308 extensions, once. if gotMsgExtInfo { return authFailure, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) } gotMsgExtInfo = true continue case msgUserAuthInfoRequest: // OK case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { return authFailure, nil, err } if msg.PartialSuccess { return authPartialSuccess, msg.Methods, nil } return authFailure, msg.Methods, nil case msgUserAuthSuccess: return authSuccess, nil, nil default: return authFailure, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) } var msg userAuthInfoRequestMsg if err := Unmarshal(packet, &msg); err != nil { return authFailure, nil, err } // Manually unpack the prompt/echo pairs. rest := msg.Prompts var prompts []string var echos []bool for i := 0; i < int(msg.NumPrompts); i++ { prompt, r, ok := parseString(rest) if !ok || len(r) == 0 { return authFailure, nil, errors.New("ssh: prompt format error") } prompts = append(prompts, string(prompt)) echos = append(echos, r[0] != 0) rest = r[1:] } if len(rest) != 0 { return authFailure, nil, errors.New("ssh: extra data following keyboard-interactive pairs") } answers, err := cb(msg.Name, msg.Instruction, prompts, echos) if err != nil { return authFailure, nil, err } if len(answers) != len(prompts) { return authFailure, nil, fmt.Errorf("ssh: incorrect number of answers from keyboard-interactive callback %d (expected %d)", len(answers), len(prompts)) } responseLength := 1 + 4 for _, a := range answers { responseLength += stringLength(len(a)) } serialized := make([]byte, responseLength) p := serialized p[0] = msgUserAuthInfoResponse p = p[1:] p = marshalUint32(p, uint32(len(answers))) for _, a := range answers { p = marshalString(p, []byte(a)) } if err := c.writePacket(serialized); err != nil { return authFailure, nil, err } } } type retryableAuthMethod struct { authMethod AuthMethod maxTries int } func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader, extensions map[string][]byte) (ok authResult, methods []string, err error) { for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ { ok, methods, err = r.authMethod.auth(session, user, c, rand, extensions) if ok != authFailure || err != nil { // either success, partial success or error terminate return ok, methods, err } } return ok, methods, err } func (r *retryableAuthMethod) method() string { return r.authMethod.method() } // RetryableAuthMethod is a decorator for other auth methods enabling them to // be retried up to maxTries before considering that AuthMethod itself failed. // If maxTries is <= 0, will retry indefinitely // // This is useful for interactive clients using challenge/response type // authentication (e.g. Keyboard-Interactive, Password, etc) where the user // could mistype their response resulting in the server issuing a // SSH_MSG_USERAUTH_FAILURE (rfc4252 #8 [password] and rfc4256 #3.4 // [keyboard-interactive]); Without this decorator, the non-retryable // AuthMethod would be removed from future consideration, and never tried again // (and so the user would never be able to retry their entry). func RetryableAuthMethod(auth AuthMethod, maxTries int) AuthMethod { return &retryableAuthMethod{authMethod: auth, maxTries: maxTries} } // GSSAPIWithMICAuthMethod is an AuthMethod with "gssapi-with-mic" authentication. // See RFC 4462 section 3 // gssAPIClient is implementation of the GSSAPIClient interface, see the definition of the interface for details. // target is the server host you want to log in to. func GSSAPIWithMICAuthMethod(gssAPIClient GSSAPIClient, target string) AuthMethod { if gssAPIClient == nil { panic("gss-api client must be not nil with enable gssapi-with-mic") } return &gssAPIWithMICCallback{gssAPIClient: gssAPIClient, target: target} } type gssAPIWithMICCallback struct { gssAPIClient GSSAPIClient target string } func (g *gssAPIWithMICCallback) auth(session []byte, user string, c packetConn, rand io.Reader, _ map[string][]byte) (authResult, []string, error) { m := &userAuthRequestMsg{ User: user, Service: serviceSSH, Method: g.method(), } // The GSS-API authentication method is initiated when the client sends an SSH_MSG_USERAUTH_REQUEST. // See RFC 4462 section 3.2. m.Payload = appendU32(m.Payload, 1) m.Payload = appendString(m.Payload, string(krb5OID)) if err := c.writePacket(Marshal(m)); err != nil { return authFailure, nil, err } // The server responds to the SSH_MSG_USERAUTH_REQUEST with either an // SSH_MSG_USERAUTH_FAILURE if none of the mechanisms are supported or // with an SSH_MSG_USERAUTH_GSSAPI_RESPONSE. // See RFC 4462 section 3.3. // OpenSSH supports Kerberos V5 mechanism only for GSS-API authentication,so I don't want to check // selected mech if it is valid. packet, err := c.readPacket() if err != nil { return authFailure, nil, err } userAuthGSSAPIResp := &userAuthGSSAPIResponse{} if err := Unmarshal(packet, userAuthGSSAPIResp); err != nil { return authFailure, nil, err } // Start the loop into the exchange token. // See RFC 4462 section 3.4. var token []byte defer g.gssAPIClient.DeleteSecContext() for { // Initiates the establishment of a security context between the application and a remote peer. nextToken, needContinue, err := g.gssAPIClient.InitSecContext("host@"+g.target, token, false) if err != nil { return authFailure, nil, err } if len(nextToken) > 0 { if err := c.writePacket(Marshal(&userAuthGSSAPIToken{ Token: nextToken, })); err != nil { return authFailure, nil, err } } if !needContinue { break } packet, err = c.readPacket() if err != nil { return authFailure, nil, err } switch packet[0] { case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { return authFailure, nil, err } if msg.PartialSuccess { return authPartialSuccess, msg.Methods, nil } return authFailure, msg.Methods, nil case msgUserAuthGSSAPIError: userAuthGSSAPIErrorResp := &userAuthGSSAPIError{} if err := Unmarshal(packet, userAuthGSSAPIErrorResp); err != nil { return authFailure, nil, err } return authFailure, nil, fmt.Errorf("GSS-API Error:\n"+ "Major Status: %d\n"+ "Minor Status: %d\n"+ "Error Message: %s\n", userAuthGSSAPIErrorResp.MajorStatus, userAuthGSSAPIErrorResp.MinorStatus, userAuthGSSAPIErrorResp.Message) case msgUserAuthGSSAPIToken: userAuthGSSAPITokenReq := &userAuthGSSAPIToken{} if err := Unmarshal(packet, userAuthGSSAPITokenReq); err != nil { return authFailure, nil, err } token = userAuthGSSAPITokenReq.Token } } // Binding Encryption Keys. // See RFC 4462 section 3.5. micField := buildMIC(string(session), user, "ssh-connection", "gssapi-with-mic") micToken, err := g.gssAPIClient.GetMIC(micField) if err != nil { return authFailure, nil, err } if err := c.writePacket(Marshal(&userAuthGSSAPIMIC{ MIC: micToken, })); err != nil { return authFailure, nil, err } return handleAuthResponse(c) } func (g *gssAPIWithMICCallback) method() string { return "gssapi-with-mic" }
crypto/ssh/client_auth.go/0
{ "file_path": "crypto/ssh/client_auth.go", "repo_id": "crypto", "token_count": 8430 }
12
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package knownhosts implements a parser for the OpenSSH known_hosts // host key database, and provides utility functions for writing // OpenSSH compliant known_hosts files. package knownhosts import ( "bufio" "bytes" "crypto/hmac" "crypto/rand" "crypto/sha1" "encoding/base64" "errors" "fmt" "io" "net" "os" "strings" "golang.org/x/crypto/ssh" ) // See the sshd manpage // (http://man.openbsd.org/sshd#SSH_KNOWN_HOSTS_FILE_FORMAT) for // background. type addr struct{ host, port string } func (a *addr) String() string { h := a.host if strings.Contains(h, ":") { h = "[" + h + "]" } return h + ":" + a.port } type matcher interface { match(addr) bool } type hostPattern struct { negate bool addr addr } func (p *hostPattern) String() string { n := "" if p.negate { n = "!" } return n + p.addr.String() } type hostPatterns []hostPattern func (ps hostPatterns) match(a addr) bool { matched := false for _, p := range ps { if !p.match(a) { continue } if p.negate { return false } matched = true } return matched } // See // https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/addrmatch.c // The matching of * has no regard for separators, unlike filesystem globs func wildcardMatch(pat []byte, str []byte) bool { for { if len(pat) == 0 { return len(str) == 0 } if len(str) == 0 { return false } if pat[0] == '*' { if len(pat) == 1 { return true } for j := range str { if wildcardMatch(pat[1:], str[j:]) { return true } } return false } if pat[0] == '?' || pat[0] == str[0] { pat = pat[1:] str = str[1:] } else { return false } } } func (p *hostPattern) match(a addr) bool { return wildcardMatch([]byte(p.addr.host), []byte(a.host)) && p.addr.port == a.port } type keyDBLine struct { cert bool matcher matcher knownKey KnownKey } func serialize(k ssh.PublicKey) string { return k.Type() + " " + base64.StdEncoding.EncodeToString(k.Marshal()) } func (l *keyDBLine) match(a addr) bool { return l.matcher.match(a) } type hostKeyDB struct { // Serialized version of revoked keys revoked map[string]*KnownKey lines []keyDBLine } func newHostKeyDB() *hostKeyDB { db := &hostKeyDB{ revoked: make(map[string]*KnownKey), } return db } func keyEq(a, b ssh.PublicKey) bool { return bytes.Equal(a.Marshal(), b.Marshal()) } // IsHostAuthority can be used as a callback in ssh.CertChecker func (db *hostKeyDB) IsHostAuthority(remote ssh.PublicKey, address string) bool { h, p, err := net.SplitHostPort(address) if err != nil { return false } a := addr{host: h, port: p} for _, l := range db.lines { if l.cert && keyEq(l.knownKey.Key, remote) && l.match(a) { return true } } return false } // IsRevoked can be used as a callback in ssh.CertChecker func (db *hostKeyDB) IsRevoked(key *ssh.Certificate) bool { _, ok := db.revoked[string(key.Marshal())] return ok } const markerCert = "@cert-authority" const markerRevoked = "@revoked" func nextWord(line []byte) (string, []byte) { i := bytes.IndexAny(line, "\t ") if i == -1 { return string(line), nil } return string(line[:i]), bytes.TrimSpace(line[i:]) } func parseLine(line []byte) (marker, host string, key ssh.PublicKey, err error) { if w, next := nextWord(line); w == markerCert || w == markerRevoked { marker = w line = next } host, line = nextWord(line) if len(line) == 0 { return "", "", nil, errors.New("knownhosts: missing host pattern") } // ignore the keytype as it's in the key blob anyway. _, line = nextWord(line) if len(line) == 0 { return "", "", nil, errors.New("knownhosts: missing key type pattern") } keyBlob, _ := nextWord(line) keyBytes, err := base64.StdEncoding.DecodeString(keyBlob) if err != nil { return "", "", nil, err } key, err = ssh.ParsePublicKey(keyBytes) if err != nil { return "", "", nil, err } return marker, host, key, nil } func (db *hostKeyDB) parseLine(line []byte, filename string, linenum int) error { marker, pattern, key, err := parseLine(line) if err != nil { return err } if marker == markerRevoked { db.revoked[string(key.Marshal())] = &KnownKey{ Key: key, Filename: filename, Line: linenum, } return nil } entry := keyDBLine{ cert: marker == markerCert, knownKey: KnownKey{ Filename: filename, Line: linenum, Key: key, }, } if pattern[0] == '|' { entry.matcher, err = newHashedHost(pattern) } else { entry.matcher, err = newHostnameMatcher(pattern) } if err != nil { return err } db.lines = append(db.lines, entry) return nil } func newHostnameMatcher(pattern string) (matcher, error) { var hps hostPatterns for _, p := range strings.Split(pattern, ",") { if len(p) == 0 { continue } var a addr var negate bool if p[0] == '!' { negate = true p = p[1:] } if len(p) == 0 { return nil, errors.New("knownhosts: negation without following hostname") } var err error if p[0] == '[' { a.host, a.port, err = net.SplitHostPort(p) if err != nil { return nil, err } } else { a.host, a.port, err = net.SplitHostPort(p) if err != nil { a.host = p a.port = "22" } } hps = append(hps, hostPattern{ negate: negate, addr: a, }) } return hps, nil } // KnownKey represents a key declared in a known_hosts file. type KnownKey struct { Key ssh.PublicKey Filename string Line int } func (k *KnownKey) String() string { return fmt.Sprintf("%s:%d: %s", k.Filename, k.Line, serialize(k.Key)) } // KeyError is returned if we did not find the key in the host key // database, or there was a mismatch. Typically, in batch // applications, this should be interpreted as failure. Interactive // applications can offer an interactive prompt to the user. type KeyError struct { // Want holds the accepted host keys. For each key algorithm, // there can be one hostkey. If Want is empty, the host is // unknown. If Want is non-empty, there was a mismatch, which // can signify a MITM attack. Want []KnownKey } func (u *KeyError) Error() string { if len(u.Want) == 0 { return "knownhosts: key is unknown" } return "knownhosts: key mismatch" } // RevokedError is returned if we found a key that was revoked. type RevokedError struct { Revoked KnownKey } func (r *RevokedError) Error() string { return "knownhosts: key is revoked" } // check checks a key against the host database. This should not be // used for verifying certificates. func (db *hostKeyDB) check(address string, remote net.Addr, remoteKey ssh.PublicKey) error { if revoked := db.revoked[string(remoteKey.Marshal())]; revoked != nil { return &RevokedError{Revoked: *revoked} } host, port, err := net.SplitHostPort(remote.String()) if err != nil { return fmt.Errorf("knownhosts: SplitHostPort(%s): %v", remote, err) } hostToCheck := addr{host, port} if address != "" { // Give preference to the hostname if available. host, port, err := net.SplitHostPort(address) if err != nil { return fmt.Errorf("knownhosts: SplitHostPort(%s): %v", address, err) } hostToCheck = addr{host, port} } return db.checkAddr(hostToCheck, remoteKey) } // checkAddr checks if we can find the given public key for the // given address. If we only find an entry for the IP address, // or only the hostname, then this still succeeds. func (db *hostKeyDB) checkAddr(a addr, remoteKey ssh.PublicKey) error { // TODO(hanwen): are these the right semantics? What if there // is just a key for the IP address, but not for the // hostname? // Algorithm => key. knownKeys := map[string]KnownKey{} for _, l := range db.lines { if l.match(a) { typ := l.knownKey.Key.Type() if _, ok := knownKeys[typ]; !ok { knownKeys[typ] = l.knownKey } } } keyErr := &KeyError{} for _, v := range knownKeys { keyErr.Want = append(keyErr.Want, v) } // Unknown remote host. if len(knownKeys) == 0 { return keyErr } // If the remote host starts using a different, unknown key type, we // also interpret that as a mismatch. if known, ok := knownKeys[remoteKey.Type()]; !ok || !keyEq(known.Key, remoteKey) { return keyErr } return nil } // The Read function parses file contents. func (db *hostKeyDB) Read(r io.Reader, filename string) error { scanner := bufio.NewScanner(r) lineNum := 0 for scanner.Scan() { lineNum++ line := scanner.Bytes() line = bytes.TrimSpace(line) if len(line) == 0 || line[0] == '#' { continue } if err := db.parseLine(line, filename, lineNum); err != nil { return fmt.Errorf("knownhosts: %s:%d: %v", filename, lineNum, err) } } return scanner.Err() } // New creates a host key callback from the given OpenSSH host key // files. The returned callback is for use in // ssh.ClientConfig.HostKeyCallback. By preference, the key check // operates on the hostname if available, i.e. if a server changes its // IP address, the host key check will still succeed, even though a // record of the new IP address is not available. func New(files ...string) (ssh.HostKeyCallback, error) { db := newHostKeyDB() for _, fn := range files { f, err := os.Open(fn) if err != nil { return nil, err } defer f.Close() if err := db.Read(f, fn); err != nil { return nil, err } } var certChecker ssh.CertChecker certChecker.IsHostAuthority = db.IsHostAuthority certChecker.IsRevoked = db.IsRevoked certChecker.HostKeyFallback = db.check return certChecker.CheckHostKey, nil } // Normalize normalizes an address into the form used in known_hosts func Normalize(address string) string { host, port, err := net.SplitHostPort(address) if err != nil { host = address port = "22" } entry := host if port != "22" { entry = "[" + entry + "]:" + port } else if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") { entry = "[" + entry + "]" } return entry } // Line returns a line to add append to the known_hosts files. func Line(addresses []string, key ssh.PublicKey) string { var trimmed []string for _, a := range addresses { trimmed = append(trimmed, Normalize(a)) } return strings.Join(trimmed, ",") + " " + serialize(key) } // HashHostname hashes the given hostname. The hostname is not // normalized before hashing. func HashHostname(hostname string) string { // TODO(hanwen): check if we can safely normalize this always. salt := make([]byte, sha1.Size) _, err := rand.Read(salt) if err != nil { panic(fmt.Sprintf("crypto/rand failure %v", err)) } hash := hashHost(hostname, salt) return encodeHash(sha1HashType, salt, hash) } func decodeHash(encoded string) (hashType string, salt, hash []byte, err error) { if len(encoded) == 0 || encoded[0] != '|' { err = errors.New("knownhosts: hashed host must start with '|'") return } components := strings.Split(encoded, "|") if len(components) != 4 { err = fmt.Errorf("knownhosts: got %d components, want 3", len(components)) return } hashType = components[1] if salt, err = base64.StdEncoding.DecodeString(components[2]); err != nil { return } if hash, err = base64.StdEncoding.DecodeString(components[3]); err != nil { return } return } func encodeHash(typ string, salt []byte, hash []byte) string { return strings.Join([]string{"", typ, base64.StdEncoding.EncodeToString(salt), base64.StdEncoding.EncodeToString(hash), }, "|") } // See https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/hostfile.c#120 func hashHost(hostname string, salt []byte) []byte { mac := hmac.New(sha1.New, salt) mac.Write([]byte(hostname)) return mac.Sum(nil) } type hashedHost struct { salt []byte hash []byte } const sha1HashType = "1" func newHashedHost(encoded string) (*hashedHost, error) { typ, salt, hash, err := decodeHash(encoded) if err != nil { return nil, err } // The type field seems for future algorithm agility, but it's // actually hardcoded in openssh currently, see // https://android.googlesource.com/platform/external/openssh/+/ab28f5495c85297e7a597c1ba62e996416da7c7e/hostfile.c#120 if typ != sha1HashType { return nil, fmt.Errorf("knownhosts: got hash type %s, must be '1'", typ) } return &hashedHost{salt: salt, hash: hash}, nil } func (h *hashedHost) match(a addr) bool { return bytes.Equal(hashHost(Normalize(a.String()), h.salt), h.hash) }
crypto/ssh/knownhosts/knownhosts.go/0
{ "file_path": "crypto/ssh/knownhosts/knownhosts.go", "repo_id": "crypto", "token_count": 4787 }
13
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssh import ( "context" "errors" "fmt" "io" "math/rand" "net" "strconv" "strings" "sync" "time" ) // Listen requests the remote peer open a listening socket on // addr. Incoming connections will be available by calling Accept on // the returned net.Listener. The listener must be serviced, or the // SSH connection may hang. // N must be "tcp", "tcp4", "tcp6", or "unix". func (c *Client) Listen(n, addr string) (net.Listener, error) { switch n { case "tcp", "tcp4", "tcp6": laddr, err := net.ResolveTCPAddr(n, addr) if err != nil { return nil, err } return c.ListenTCP(laddr) case "unix": return c.ListenUnix(addr) default: return nil, fmt.Errorf("ssh: unsupported protocol: %s", n) } } // Automatic port allocation is broken with OpenSSH before 6.0. See // also https://bugzilla.mindrot.org/show_bug.cgi?id=2017. In // particular, OpenSSH 5.9 sends a channelOpenMsg with port number 0, // rather than the actual port number. This means you can never open // two different listeners with auto allocated ports. We work around // this by trying explicit ports until we succeed. const openSSHPrefix = "OpenSSH_" var portRandomizer = rand.New(rand.NewSource(time.Now().UnixNano())) // isBrokenOpenSSHVersion returns true if the given version string // specifies a version of OpenSSH that is known to have a bug in port // forwarding. func isBrokenOpenSSHVersion(versionStr string) bool { i := strings.Index(versionStr, openSSHPrefix) if i < 0 { return false } i += len(openSSHPrefix) j := i for ; j < len(versionStr); j++ { if versionStr[j] < '0' || versionStr[j] > '9' { break } } version, _ := strconv.Atoi(versionStr[i:j]) return version < 6 } // autoPortListenWorkaround simulates automatic port allocation by // trying random ports repeatedly. func (c *Client) autoPortListenWorkaround(laddr *net.TCPAddr) (net.Listener, error) { var sshListener net.Listener var err error const tries = 10 for i := 0; i < tries; i++ { addr := *laddr addr.Port = 1024 + portRandomizer.Intn(60000) sshListener, err = c.ListenTCP(&addr) if err == nil { laddr.Port = addr.Port return sshListener, err } } return nil, fmt.Errorf("ssh: listen on random port failed after %d tries: %v", tries, err) } // RFC 4254 7.1 type channelForwardMsg struct { addr string rport uint32 } // handleForwards starts goroutines handling forwarded connections. // It's called on first use by (*Client).ListenTCP to not launch // goroutines until needed. func (c *Client) handleForwards() { go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-tcpip")) go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-streamlocal@openssh.com")) } // ListenTCP requests the remote peer open a listening socket // on laddr. Incoming connections will be available by calling // Accept on the returned net.Listener. func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) { c.handleForwardsOnce.Do(c.handleForwards) if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) { return c.autoPortListenWorkaround(laddr) } m := channelForwardMsg{ laddr.IP.String(), uint32(laddr.Port), } // send message ok, resp, err := c.SendRequest("tcpip-forward", true, Marshal(&m)) if err != nil { return nil, err } if !ok { return nil, errors.New("ssh: tcpip-forward request denied by peer") } // If the original port was 0, then the remote side will // supply a real port number in the response. if laddr.Port == 0 { var p struct { Port uint32 } if err := Unmarshal(resp, &p); err != nil { return nil, err } laddr.Port = int(p.Port) } // Register this forward, using the port number we obtained. ch := c.forwards.add(laddr) return &tcpListener{laddr, c, ch}, nil } // forwardList stores a mapping between remote // forward requests and the tcpListeners. type forwardList struct { sync.Mutex entries []forwardEntry } // forwardEntry represents an established mapping of a laddr on a // remote ssh server to a channel connected to a tcpListener. type forwardEntry struct { laddr net.Addr c chan forward } // forward represents an incoming forwarded tcpip connection. The // arguments to add/remove/lookup should be address as specified in // the original forward-request. type forward struct { newCh NewChannel // the ssh client channel underlying this forward raddr net.Addr // the raddr of the incoming connection } func (l *forwardList) add(addr net.Addr) chan forward { l.Lock() defer l.Unlock() f := forwardEntry{ laddr: addr, c: make(chan forward, 1), } l.entries = append(l.entries, f) return f.c } // See RFC 4254, section 7.2 type forwardedTCPPayload struct { Addr string Port uint32 OriginAddr string OriginPort uint32 } // parseTCPAddr parses the originating address from the remote into a *net.TCPAddr. func parseTCPAddr(addr string, port uint32) (*net.TCPAddr, error) { if port == 0 || port > 65535 { return nil, fmt.Errorf("ssh: port number out of range: %d", port) } ip := net.ParseIP(string(addr)) if ip == nil { return nil, fmt.Errorf("ssh: cannot parse IP address %q", addr) } return &net.TCPAddr{IP: ip, Port: int(port)}, nil } func (l *forwardList) handleChannels(in <-chan NewChannel) { for ch := range in { var ( laddr net.Addr raddr net.Addr err error ) switch channelType := ch.ChannelType(); channelType { case "forwarded-tcpip": var payload forwardedTCPPayload if err = Unmarshal(ch.ExtraData(), &payload); err != nil { ch.Reject(ConnectionFailed, "could not parse forwarded-tcpip payload: "+err.Error()) continue } // RFC 4254 section 7.2 specifies that incoming // addresses should list the address, in string // format. It is implied that this should be an IP // address, as it would be impossible to connect to it // otherwise. laddr, err = parseTCPAddr(payload.Addr, payload.Port) if err != nil { ch.Reject(ConnectionFailed, err.Error()) continue } raddr, err = parseTCPAddr(payload.OriginAddr, payload.OriginPort) if err != nil { ch.Reject(ConnectionFailed, err.Error()) continue } case "forwarded-streamlocal@openssh.com": var payload forwardedStreamLocalPayload if err = Unmarshal(ch.ExtraData(), &payload); err != nil { ch.Reject(ConnectionFailed, "could not parse forwarded-streamlocal@openssh.com payload: "+err.Error()) continue } laddr = &net.UnixAddr{ Name: payload.SocketPath, Net: "unix", } raddr = &net.UnixAddr{ Name: "@", Net: "unix", } default: panic(fmt.Errorf("ssh: unknown channel type %s", channelType)) } if ok := l.forward(laddr, raddr, ch); !ok { // Section 7.2, implementations MUST reject spurious incoming // connections. ch.Reject(Prohibited, "no forward for address") continue } } } // remove removes the forward entry, and the channel feeding its // listener. func (l *forwardList) remove(addr net.Addr) { l.Lock() defer l.Unlock() for i, f := range l.entries { if addr.Network() == f.laddr.Network() && addr.String() == f.laddr.String() { l.entries = append(l.entries[:i], l.entries[i+1:]...) close(f.c) return } } } // closeAll closes and clears all forwards. func (l *forwardList) closeAll() { l.Lock() defer l.Unlock() for _, f := range l.entries { close(f.c) } l.entries = nil } func (l *forwardList) forward(laddr, raddr net.Addr, ch NewChannel) bool { l.Lock() defer l.Unlock() for _, f := range l.entries { if laddr.Network() == f.laddr.Network() && laddr.String() == f.laddr.String() { f.c <- forward{newCh: ch, raddr: raddr} return true } } return false } type tcpListener struct { laddr *net.TCPAddr conn *Client in <-chan forward } // Accept waits for and returns the next connection to the listener. func (l *tcpListener) Accept() (net.Conn, error) { s, ok := <-l.in if !ok { return nil, io.EOF } ch, incoming, err := s.newCh.Accept() if err != nil { return nil, err } go DiscardRequests(incoming) return &chanConn{ Channel: ch, laddr: l.laddr, raddr: s.raddr, }, nil } // Close closes the listener. func (l *tcpListener) Close() error { m := channelForwardMsg{ l.laddr.IP.String(), uint32(l.laddr.Port), } // this also closes the listener. l.conn.forwards.remove(l.laddr) ok, _, err := l.conn.SendRequest("cancel-tcpip-forward", true, Marshal(&m)) if err == nil && !ok { err = errors.New("ssh: cancel-tcpip-forward failed") } return err } // Addr returns the listener's network address. func (l *tcpListener) Addr() net.Addr { return l.laddr } // DialContext initiates a connection to the addr from the remote host. // // The provided Context must be non-nil. If the context expires before the // connection is complete, an error is returned. Once successfully connected, // any expiration of the context will not affect the connection. // // See func Dial for additional information. func (c *Client) DialContext(ctx context.Context, n, addr string) (net.Conn, error) { if err := ctx.Err(); err != nil { return nil, err } type connErr struct { conn net.Conn err error } ch := make(chan connErr) go func() { conn, err := c.Dial(n, addr) select { case ch <- connErr{conn, err}: case <-ctx.Done(): if conn != nil { conn.Close() } } }() select { case res := <-ch: return res.conn, res.err case <-ctx.Done(): return nil, ctx.Err() } } // Dial initiates a connection to the addr from the remote host. // The resulting connection has a zero LocalAddr() and RemoteAddr(). func (c *Client) Dial(n, addr string) (net.Conn, error) { var ch Channel switch n { case "tcp", "tcp4", "tcp6": // Parse the address into host and numeric port. host, portString, err := net.SplitHostPort(addr) if err != nil { return nil, err } port, err := strconv.ParseUint(portString, 10, 16) if err != nil { return nil, err } ch, err = c.dial(net.IPv4zero.String(), 0, host, int(port)) if err != nil { return nil, err } // Use a zero address for local and remote address. zeroAddr := &net.TCPAddr{ IP: net.IPv4zero, Port: 0, } return &chanConn{ Channel: ch, laddr: zeroAddr, raddr: zeroAddr, }, nil case "unix": var err error ch, err = c.dialStreamLocal(addr) if err != nil { return nil, err } return &chanConn{ Channel: ch, laddr: &net.UnixAddr{ Name: "@", Net: "unix", }, raddr: &net.UnixAddr{ Name: addr, Net: "unix", }, }, nil default: return nil, fmt.Errorf("ssh: unsupported protocol: %s", n) } } // DialTCP connects to the remote address raddr on the network net, // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used // as the local address for the connection. func (c *Client) DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error) { if laddr == nil { laddr = &net.TCPAddr{ IP: net.IPv4zero, Port: 0, } } ch, err := c.dial(laddr.IP.String(), laddr.Port, raddr.IP.String(), raddr.Port) if err != nil { return nil, err } return &chanConn{ Channel: ch, laddr: laddr, raddr: raddr, }, nil } // RFC 4254 7.2 type channelOpenDirectMsg struct { raddr string rport uint32 laddr string lport uint32 } func (c *Client) dial(laddr string, lport int, raddr string, rport int) (Channel, error) { msg := channelOpenDirectMsg{ raddr: raddr, rport: uint32(rport), laddr: laddr, lport: uint32(lport), } ch, in, err := c.OpenChannel("direct-tcpip", Marshal(&msg)) if err != nil { return nil, err } go DiscardRequests(in) return ch, err } type tcpChan struct { Channel // the backing channel } // chanConn fulfills the net.Conn interface without // the tcpChan having to hold laddr or raddr directly. type chanConn struct { Channel laddr, raddr net.Addr } // LocalAddr returns the local network address. func (t *chanConn) LocalAddr() net.Addr { return t.laddr } // RemoteAddr returns the remote network address. func (t *chanConn) RemoteAddr() net.Addr { return t.raddr } // SetDeadline sets the read and write deadlines associated // with the connection. func (t *chanConn) SetDeadline(deadline time.Time) error { if err := t.SetReadDeadline(deadline); err != nil { return err } return t.SetWriteDeadline(deadline) } // SetReadDeadline sets the read deadline. // A zero value for t means Read will not time out. // After the deadline, the error from Read will implement net.Error // with Timeout() == true. func (t *chanConn) SetReadDeadline(deadline time.Time) error { // for compatibility with previous version, // the error message contains "tcpChan" return errors.New("ssh: tcpChan: deadline not supported") } // SetWriteDeadline exists to satisfy the net.Conn interface // but is not implemented by this type. It always returns an error. func (t *chanConn) SetWriteDeadline(deadline time.Time) error { return errors.New("ssh: tcpChan: deadline not supported") }
crypto/ssh/tcpip.go/0
{ "file_path": "crypto/ssh/tcpip.go", "repo_id": "crypto", "token_count": 4852 }
14
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This package contains test data shared between the various subpackages of // the golang.org/x/crypto/ssh package. Under no circumstance should // this data be used for production code. package testdata
crypto/ssh/testdata/doc.go/0
{ "file_path": "crypto/ssh/testdata/doc.go", "repo_id": "crypto", "token_count": 89 }
15
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package xtea implements XTEA encryption, as defined in Needham and Wheeler's // 1997 technical report, "Tea extensions." // // XTEA is a legacy cipher and its short block size makes it vulnerable to // birthday bound attacks (see https://sweet32.info). It should only be used // where compatibility with legacy systems, not security, is the goal. // // Deprecated: any new system should use AES (from crypto/aes, if necessary in // an AEAD mode like crypto/cipher.NewGCM) or XChaCha20-Poly1305 (from // golang.org/x/crypto/chacha20poly1305). package xtea // For details, see http://www.cix.co.uk/~klockstone/xtea.pdf import "strconv" // The XTEA block size in bytes. const BlockSize = 8 // A Cipher is an instance of an XTEA cipher using a particular key. type Cipher struct { // table contains a series of precalculated values that are used each round. table [64]uint32 } type KeySizeError int func (k KeySizeError) Error() string { return "crypto/xtea: invalid key size " + strconv.Itoa(int(k)) } // NewCipher creates and returns a new Cipher. // The key argument should be the XTEA key. // XTEA only supports 128 bit (16 byte) keys. func NewCipher(key []byte) (*Cipher, error) { k := len(key) switch k { default: return nil, KeySizeError(k) case 16: break } c := new(Cipher) initCipher(c, key) return c, nil } // BlockSize returns the XTEA block size, 8 bytes. // It is necessary to satisfy the Block interface in the // package "crypto/cipher". func (c *Cipher) BlockSize() int { return BlockSize } // Encrypt encrypts the 8 byte buffer src using the key and stores the result in dst. // Note that for amounts of data larger than a block, // it is not safe to just call Encrypt on successive blocks; // instead, use an encryption mode like CBC (see crypto/cipher/cbc.go). func (c *Cipher) Encrypt(dst, src []byte) { encryptBlock(c, dst, src) } // Decrypt decrypts the 8 byte buffer src using the key and stores the result in dst. func (c *Cipher) Decrypt(dst, src []byte) { decryptBlock(c, dst, src) } // initCipher initializes the cipher context by creating a look up table // of precalculated values that are based on the key. func initCipher(c *Cipher, key []byte) { // Load the key into four uint32s var k [4]uint32 for i := 0; i < len(k); i++ { j := i << 2 // Multiply by 4 k[i] = uint32(key[j+0])<<24 | uint32(key[j+1])<<16 | uint32(key[j+2])<<8 | uint32(key[j+3]) } // Precalculate the table const delta = 0x9E3779B9 var sum uint32 // Two rounds of XTEA applied per loop for i := 0; i < numRounds; { c.table[i] = sum + k[sum&3] i++ sum += delta c.table[i] = sum + k[(sum>>11)&3] i++ } }
crypto/xtea/cipher.go/0
{ "file_path": "crypto/xtea/cipher.go", "repo_id": "crypto", "token_count": 955 }
16
General maintainers: sam boyer (@sdboyer) * dep * `init` command: Carolyn Van Slyck (@carolynvs) * `ensure` command: Ibrahim AshShohail (@ibrasho) * `status` command: Sunny (@darkowlzz) * testing harness: (vacant) * gps * solver: (vacant) * source manager: (@jmank88) * root deduction: (vacant) * source/vcs interaction: (@jmank88) * caching: Jordan Krage (@jmank88) * pkgtree: (vacant) * versions and constraints: (@jmank88)
dep/MAINTAINERS.md/0
{ "file_path": "dep/MAINTAINERS.md", "repo_id": "dep", "token_count": 175 }
17
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "fmt" "os" "path/filepath" "strings" "sync" "github.com/golang/dep" "github.com/golang/dep/gps" "github.com/golang/dep/gps/paths" "github.com/golang/dep/gps/pkgtree" fb "github.com/golang/dep/internal/feedback" "github.com/golang/dep/internal/fs" "github.com/pkg/errors" ) // gopathScanner supplies manifest/lock data by scanning the contents of GOPATH // It uses its results to fill-in any missing details left by the rootAnalyzer. type gopathScanner struct { ctx *dep.Ctx directDeps map[gps.ProjectRoot]bool sm gps.SourceManager pd projectData origM *dep.Manifest origL *dep.Lock } func newGopathScanner(ctx *dep.Ctx, directDeps map[gps.ProjectRoot]bool, sm gps.SourceManager) *gopathScanner { return &gopathScanner{ ctx: ctx, directDeps: directDeps, sm: sm, } } // InitializeRootManifestAndLock performs analysis of the filesystem tree rooted // at path, with the root import path importRoot, to determine the project's // constraints. Respect any initial constraints defined in the root manifest and // lock. func (g *gopathScanner) InitializeRootManifestAndLock(rootM *dep.Manifest, rootL *dep.Lock) error { var err error g.ctx.Err.Println("Searching GOPATH for projects...") g.pd, err = g.scanGopathForDependencies() if err != nil { return err } g.origM = dep.NewManifest() g.origM.Constraints = g.pd.constraints g.origL = &dep.Lock{ P: make([]gps.LockedProject, 0, len(g.pd.ondisk)), } for pr, v := range g.pd.ondisk { // That we have to chop off these path prefixes is a symptom of // a problem in gps itself pkgs := make([]string, 0, len(g.pd.dependencies[pr])) prslash := string(pr) + "/" for _, pkg := range g.pd.dependencies[pr] { if pkg == string(pr) { pkgs = append(pkgs, ".") } else { pkgs = append(pkgs, trimPathPrefix(pkg, prslash)) } } g.origL.P = append(g.origL.P, gps.NewLockedProject( gps.ProjectIdentifier{ProjectRoot: pr}, v, pkgs), ) } g.overlay(rootM, rootL) return nil } // Fill in gaps in the root manifest/lock with data found from the GOPATH. func (g *gopathScanner) overlay(rootM *dep.Manifest, rootL *dep.Lock) { for pkg, prj := range g.origM.Constraints { if _, has := rootM.Constraints[pkg]; has { continue } rootM.Constraints[pkg] = prj v := g.pd.ondisk[pkg] pi := gps.ProjectIdentifier{ProjectRoot: pkg, Source: prj.Source} f := fb.NewConstraintFeedback(gps.ProjectConstraint{Ident: pi, Constraint: v}, fb.DepTypeDirect) f.LogFeedback(g.ctx.Err) f = fb.NewLockedProjectFeedback(gps.NewLockedProject(pi, v, nil), fb.DepTypeDirect) f.LogFeedback(g.ctx.Err) } // Keep track of which projects have been locked lockedProjects := map[gps.ProjectRoot]bool{} for _, lp := range rootL.P { lockedProjects[lp.Ident().ProjectRoot] = true } for _, lp := range g.origL.P { pkg := lp.Ident().ProjectRoot if _, isLocked := lockedProjects[pkg]; isLocked { continue } rootL.P = append(rootL.P, lp) lockedProjects[pkg] = true if _, isDirect := g.directDeps[pkg]; !isDirect { f := fb.NewLockedProjectFeedback(lp, fb.DepTypeTransitive) f.LogFeedback(g.ctx.Err) } } // Identify projects whose version is unknown and will have to be solved for var missing []string // all project roots missing from GOPATH var missingVCS []string // all project roots missing VCS information for pr := range g.pd.notondisk { if _, isLocked := lockedProjects[pr]; isLocked { continue } if g.pd.invalidSVC[pr] { missingVCS = append(missingVCS, string(pr)) } else { missing = append(missing, string(pr)) } } missingStr := "" missingVCSStr := "" if len(missing) > 0 { missingStr = fmt.Sprintf("The following dependencies were not found in GOPATH:\n %s\n\n", strings.Join(missing, "\n ")) } if len(missingVCS) > 0 { missingVCSStr = fmt.Sprintf("The following dependencies found in GOPATH were missing VCS information (a remote source is required):\n %s\n\n", strings.Join(missingVCS, "\n ")) } if len(missingVCS)+len(missing) > 0 { g.ctx.Err.Printf("\n%s%sThe most recent version of these projects will be used.\n\n", missingStr, missingVCSStr) } } func trimPathPrefix(p1, p2 string) string { if isPrefix, _ := fs.HasFilepathPrefix(p1, p2); isPrefix { return p1[len(p2):] } return p1 } // contains checks if a array of strings contains a value func contains(a []string, b string) bool { for _, v := range a { if b == v { return true } } return false } // getProjectPropertiesFromVersion takes a Version and returns a proper // ProjectProperties with Constraint value based on the provided version. func getProjectPropertiesFromVersion(v gps.Version) gps.ProjectProperties { pp := gps.ProjectProperties{} // extract version and ignore if it's revision only switch tv := v.(type) { case gps.PairedVersion: v = tv.Unpair() case gps.Revision: return pp } switch v.Type() { case gps.IsBranch, gps.IsVersion: pp.Constraint = v case gps.IsSemver: c, err := gps.NewSemverConstraintIC(v.String()) if err != nil { panic(err) } pp.Constraint = c } return pp } type projectData struct { constraints gps.ProjectConstraints // constraints that could be found dependencies map[gps.ProjectRoot][]string // all dependencies (imports) found by project root notondisk map[gps.ProjectRoot]bool // projects that were not found on disk invalidSVC map[gps.ProjectRoot]bool // projects that were found on disk but SVC data could not be read ondisk map[gps.ProjectRoot]gps.Version // projects that were found on disk } func (g *gopathScanner) scanGopathForDependencies() (projectData, error) { constraints := make(gps.ProjectConstraints) dependencies := make(map[gps.ProjectRoot][]string) packages := make(map[string]bool) notondisk := make(map[gps.ProjectRoot]bool) invalidSVC := make(map[gps.ProjectRoot]bool) ondisk := make(map[gps.ProjectRoot]gps.Version) var syncDepGroup sync.WaitGroup syncDep := func(pr gps.ProjectRoot, sm gps.SourceManager) { if err := sm.SyncSourceFor(gps.ProjectIdentifier{ProjectRoot: pr}); err != nil { g.ctx.Err.Printf("%+v", errors.Wrapf(err, "Unable to cache %s", pr)) } syncDepGroup.Done() } if len(g.directDeps) == 0 { return projectData{}, nil } for ippr := range g.directDeps { // TODO(sdboyer) these are not import paths by this point, they've // already been worked down to project roots. ip := string(ippr) pr, err := g.sm.DeduceProjectRoot(ip) if err != nil { return projectData{}, errors.Wrap(err, "sm.DeduceProjectRoot") } packages[ip] = true if _, has := dependencies[pr]; has { dependencies[pr] = append(dependencies[pr], ip) continue } syncDepGroup.Add(1) go syncDep(pr, g.sm) dependencies[pr] = []string{ip} abs, err := g.ctx.AbsForImport(string(pr)) if err != nil { notondisk[pr] = true continue } v, err := gps.VCSVersion(abs) if err != nil { invalidSVC[pr] = true notondisk[pr] = true continue } ondisk[pr] = v pp := getProjectPropertiesFromVersion(v) if pp.Constraint != nil || pp.Source != "" { constraints[pr] = pp } } // Explore the packages we've found for transitive deps, either // completing the lock or identifying (more) missing projects that we'll // need to ask gps to solve for us. colors := make(map[string]uint8) const ( white uint8 = iota grey black ) // cache of PackageTrees, so we don't parse projects more than once ptrees := make(map[gps.ProjectRoot]pkgtree.PackageTree) // depth-first traverser var dft func(string) error dft = func(pkg string) error { switch colors[pkg] { case white: colors[pkg] = grey pr, err := g.sm.DeduceProjectRoot(pkg) if err != nil { return errors.Wrap(err, "could not deduce project root for "+pkg) } // We already visited this project root earlier via some other // pkg within it, and made the decision that it's not on disk. // Respect that decision, and pop the stack. if notondisk[pr] { colors[pkg] = black return nil } ptree, has := ptrees[pr] if !has { // It's fine if the root does not exist - it indicates that this // project is not present in the workspace, and so we need to // solve to deal with this dep. r := filepath.Join(g.ctx.GOPATH, "src", string(pr)) fi, err := os.Stat(r) if os.IsNotExist(err) || !fi.IsDir() { colors[pkg] = black notondisk[pr] = true return nil } // We know the project is on disk; the question is whether we're // first seeing it here, in the transitive exploration, or if it // was found in the initial pass on direct imports. We know it's // the former if there's no entry for it in the ondisk map. if _, in := ondisk[pr]; !in { abs, err := g.ctx.AbsForImport(string(pr)) if err != nil { colors[pkg] = black notondisk[pr] = true return nil } v, err := gps.VCSVersion(abs) if err != nil { // Even if we know it's on disk, errors are still // possible when trying to deduce version. If we // encounter such an error, just treat the project as // not being on disk; the solver will work it out. colors[pkg] = black notondisk[pr] = true return nil } ondisk[pr] = v } ptree, err = pkgtree.ListPackages(r, string(pr)) if err != nil { // Any error here other than an a nonexistent dir (which // can't happen because we covered that case above) is // probably critical, so bail out. return errors.Wrap(err, "gps.ListPackages") } ptrees[pr] = ptree } // Get a reachmap that includes main pkgs (even though importing // them is an error, what we're checking right now is simply whether // there's a package with go code present on disk), and does not // backpropagate errors (again, because our only concern right now // is package existence). rm, errmap := ptree.ToReachMap(true, false, false, nil) reached, ok := rm[pkg] if !ok { colors[pkg] = black // not on disk... notondisk[pr] = true return nil } if _, ok := errmap[pkg]; ok { // The package is on disk, but contains some errors. colors[pkg] = black return nil } if deps, has := dependencies[pr]; has { if !contains(deps, pkg) { dependencies[pr] = append(deps, pkg) } } else { dependencies[pr] = []string{pkg} syncDepGroup.Add(1) go syncDep(pr, g.sm) } // recurse for _, rpkg := range reached.External { if paths.IsStandardImportPath(rpkg) { continue } err := dft(rpkg) if err != nil { // Bubble up any errors we encounter return err } } colors[pkg] = black case grey: return errors.Errorf("Import cycle detected on %s", pkg) } return nil } // run the depth-first traversal from the set of immediate external // package imports we found in the current project for pkg := range packages { err := dft(pkg) if err != nil { return projectData{}, err // already errors.Wrap()'d internally } } syncDepGroup.Wait() pd := projectData{ constraints: constraints, dependencies: dependencies, invalidSVC: invalidSVC, notondisk: notondisk, ondisk: ondisk, } return pd, nil }
dep/cmd/dep/gopath_scanner.go/0
{ "file_path": "dep/cmd/dep/gopath_scanner.go", "repo_id": "dep", "token_count": 4529 }
18
digraph { node [shape=box]; 4106060478 [label="project"]; }
dep/cmd/dep/testdata/graphviz/case2.dot/0
{ "file_path": "dep/cmd/dep/testdata/graphviz/case2.dot", "repo_id": "dep", "token_count": 26 }
19
[[constraint]] name = "github.com/sdboyer/deptest" version = "1.0.0" [prune] go-tests = true unused-packages = true [[constraint]] branch = "master" name = "github.com/sdboyer/deptesttres"
dep/cmd/dep/testdata/harness_tests/ensure/add/all-new-double/final/Gopkg.toml/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/add/all-new-double/final/Gopkg.toml", "repo_id": "dep", "token_count": 88 }
20
{ "commands": [ ["init", "-skip-tools", "-no-examples"], ["ensure", "-update"] ], "vendor-final": [ "github.com/sdboyer/deptest" ] }
dep/cmd/dep/testdata/harness_tests/ensure/empty/case1/testcase.json/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/empty/case1/testcase.json", "repo_id": "dep", "token_count": 72 }
21
noverify = ["github.com/sdboyer/deptest"]
dep/cmd/dep/testdata/harness_tests/ensure/noverify/hash_mismatch/final/Gopkg.toml/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/noverify/hash_mismatch/final/Gopkg.toml", "repo_id": "dep", "token_count": 18 }
22
{ "commands": [ ["ensure"], ["check"] ], "vendor-final": [ "github.com/sdboyer/deptest" ] }
dep/cmd/dep/testdata/harness_tests/ensure/noverify/vendororphans/testcase.json/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/ensure/noverify/vendororphans/testcase.json", "repo_id": "dep", "token_count": 58 }
23
Test if a transitive glide manifest is read.
dep/cmd/dep/testdata/harness_tests/init/glide/trans-trans-trans/README.md/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/init/glide/trans-trans-trans/README.md", "repo_id": "dep", "token_count": 10 }
24
[[constraint]] name = "github.com/ChinmayR/deptestglideA" version = "0.5.0" [[constraint]] name = "github.com/ChinmayR/deptestglideB" version = "0.3.0" [prune] go-tests = true unused-packages = true
dep/cmd/dep/testdata/harness_tests/init/glide/trans-trans/final/Gopkg.toml/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/init/glide/trans-trans/final/Gopkg.toml", "repo_id": "dep", "token_count": 98 }
25
{ "commands": [ ["init", "-not-defined-flag"] ], "error-expected": "flag provided but not defined: -not-defined-flag\nUsage: dep init [root]" }
dep/cmd/dep/testdata/harness_tests/init/usage/with_not_defined_flag/testcase.json/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/init/usage/with_not_defined_flag/testcase.json", "repo_id": "dep", "token_count": 57 }
26
[[override]] name = "github.com/sdboyer/deptest" version = "=0.8.1"
dep/cmd/dep/testdata/harness_tests/status/override_constraint/final/Gopkg.toml/0
{ "file_path": "dep/cmd/dep/testdata/harness_tests/status/override_constraint/final/Gopkg.toml", "repo_id": "dep", "token_count": 34 }
27
--- id: env-vars title: Environment Variables --- dep's behavior can be modified by some environment variables: * [`DEPCACHEAGE`](#depcacheage) * [`DEPCACHEDIR`](#depcachedir) * [`DEPPROJECTROOT`](#depprojectroot) * [`DEPNOLOCK`](#depnolock) Environment variables are passed through to subcommands, and therefore can be used to affect vcs (e.g. `git`) behavior. --- ### `DEPCACHEAGE` If set to a [duration](https://golang.org/pkg/time/#ParseDuration) (e.g. `24h`), it will enable caching of metadata from source repositories: * Lists of published versions * The contents of a project's `Gopkg.toml` file, at a particular version * A project's tree of packages and imports, at a particular version A duration must be set to enable caching. (In future versions of dep, it will be on by default). The duration is used as a TTL, but only for mutable information, like version lists. Information associated with an immutable VCS revision (packages and imports; `Gopkg.toml` declarations) is cached indefinitely. The cache lives in `$DEPCACHEDIR/bolt-v1.db`, where the version number is an internal number associated with a particular data schema dep uses. The file can be removed safely; the database will be automatically rebuilt as needed. ### `DEPCACHEDIR` Allows the user to specify a custom directory for dep's [local cache](glossary.md#local-cache) of pristine VCS source repositories. Defaults to `$GOPATH/pkg/dep`. ### `DEPPROJECTROOT` If set, the value of this variable will be treated as the [project root](glossary.md#project-root) of the [current project](glossary.md#current-project), superseding GOPATH-based inference. This is primarily useful if you're not using the standard `go` toolchain as a compiler (for example, with Bazel), as there otherwise isn't much use to operating outside of GOPATH. ### `DEPNOLOCK` By default, dep creates an `sm.lock` file at `$DEPCACHEDIR/sm.lock` in order to prevent multiple dep processes from interacting with the [local cache](glossary.md#local-cache) simultaneously. Setting this variable will bypass that protection; no file will be created. This can be useful on certain filesystems; VirtualBox shares in particular are known to misbehave.
dep/docs/env-vars.md/0
{ "file_path": "dep/docs/env-vars.md", "repo_id": "dep", "token_count": 623 }
28
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gps import ( "os" "path/filepath" "strings" "github.com/pkg/errors" ) // fsLink represents a symbolic link. type fsLink struct { path string to string // circular denotes if evaluating the symlink fails with "too many links" error. // This error means that it's very likely that the symlink has a circular reference. circular bool // broken denotes that attempting to resolve the link fails, most likely because // the destaination doesn't exist. broken bool } // filesystemState represents the state of a file system. type filesystemState struct { root string dirs []string files []string links []fsLink } func (s filesystemState) setup() error { for _, dir := range s.dirs { p := filepath.Join(s.root, dir) if err := os.MkdirAll(p, 0777); err != nil { return errors.Errorf("os.MkdirAll(%q, 0777) err=%q", p, err) } } for _, file := range s.files { p := filepath.Join(s.root, file) f, err := os.Create(p) if err != nil { return errors.Errorf("os.Create(%q) err=%q", p, err) } if err := f.Close(); err != nil { return errors.Errorf("file %q Close() err=%q", p, err) } } for _, link := range s.links { p := filepath.Join(s.root, link.path) // On Windows, relative symlinks confuse filepath.Walk. So, we'll just sigh // and do absolute links, assuming they are relative to the directory of // link.path. // // Reference: https://github.com/golang/go/issues/17540 // // TODO(ibrasho): This was fixed in Go 1.9. Remove this when support for // 1.8 is dropped. dir := filepath.Dir(p) to := "" if link.to != "" { to = filepath.Join(dir, link.to) } if err := os.Symlink(to, p); err != nil { return errors.Errorf("os.Symlink(%q, %q) err=%q", to, p, err) } } return nil } // deriveFilesystemState returns a filesystemState based on the state of // the filesystem on root. func deriveFilesystemState(root string) (filesystemState, error) { fs := filesystemState{root: root} err := filepath.Walk(fs.root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if path == fs.root { return nil } relPath, err := filepath.Rel(fs.root, path) if err != nil { return err } if (info.Mode() & os.ModeSymlink) != 0 { l := fsLink{path: relPath} l.to, err = filepath.EvalSymlinks(path) if err != nil && strings.HasSuffix(err.Error(), "too many links") { l.circular = true } else if err != nil && os.IsNotExist(err) { l.broken = true } else if err != nil { return err } fs.links = append(fs.links, l) return nil } if info.IsDir() { fs.dirs = append(fs.dirs, relPath) return nil } fs.files = append(fs.files, relPath) return nil }) if err != nil { return filesystemState{}, err } return fs, nil }
dep/gps/filesystem.go/0
{ "file_path": "dep/gps/filesystem.go", "repo_id": "dep", "token_count": 1129 }
29
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pkgtree import ( "sort" "strings" "github.com/armon/go-radix" ) // IgnoredRuleset comprises a set of rules for ignoring import paths. It can // manage both literal and prefix-wildcard matches. type IgnoredRuleset struct { t *radix.Tree } // NewIgnoredRuleset processes a set of strings into an IgnoredRuleset. Strings // that end in "*" are treated as wildcards, where any import path with a // matching prefix will be ignored. IgnoredRulesets are immutable once created. // // Duplicate and redundant (i.e. a literal path that has a prefix of a wildcard // path) declarations are discarded. Consequently, it is possible that the // returned IgnoredRuleset may have a smaller Len() than the input slice. func NewIgnoredRuleset(ig []string) *IgnoredRuleset { if len(ig) == 0 { return &IgnoredRuleset{} } ir := &IgnoredRuleset{ t: radix.New(), } // Sort the list of all the ignores in order to ensure that wildcard // precedence is recorded correctly in the trie. sort.Strings(ig) for _, i := range ig { // Skip global ignore and empty string. if i == "*" || i == "" { continue } _, wildi, has := ir.t.LongestPrefix(i) // We may not always have a value here, but if we do, then it's a bool. wild, _ := wildi.(bool) // Check if it's a wildcard ignore. if strings.HasSuffix(i, "*") { // Check if it is ineffectual. if has && wild { // Skip ineffectual wildcard ignore. continue } // Create the ignore prefix and insert in the radix tree. ir.t.Insert(i[:len(i)-1], true) } else if !has || !wild { ir.t.Insert(i, false) } } if ir.t.Len() == 0 { ir.t = nil } return ir } // IsIgnored indicates whether the provided path should be ignored, according to // the ruleset. func (ir *IgnoredRuleset) IsIgnored(path string) bool { if path == "" || ir == nil || ir.t == nil { return false } prefix, wildi, has := ir.t.LongestPrefix(path) return has && (wildi.(bool) || path == prefix) } // Len indicates the number of rules in the ruleset. func (ir *IgnoredRuleset) Len() int { if ir == nil || ir.t == nil { return 0 } return ir.t.Len() } // ToSlice converts the contents of the IgnoredRuleset to a string slice. // // This operation is symmetrically dual to NewIgnoredRuleset. func (ir *IgnoredRuleset) ToSlice() []string { irlen := ir.Len() if irlen == 0 { return nil } items := make([]string, 0, irlen) ir.t.Walk(func(s string, v interface{}) bool { if s != "" { if v.(bool) { items = append(items, s+"*") } else { items = append(items, s) } } return false }) return items }
dep/gps/pkgtree/ignored_ruleset.go/0
{ "file_path": "dep/gps/pkgtree/ignored_ruleset.go", "repo_id": "dep", "token_count": 980 }
30
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gps import ( "bytes" "fmt" "sort" "strings" ) func a2vs(a atom) string { if a.v == rootRev || a.v == nil { return "(root)" } return fmt.Sprintf("%s@%s", a.id, a.v) } type traceError interface { traceString() string } type noVersionError struct { pn ProjectIdentifier fails []failedVersion } func (e *noVersionError) Error() string { if len(e.fails) == 0 { return fmt.Sprintf("No versions found for project %q.", e.pn.ProjectRoot) } var buf bytes.Buffer fmt.Fprintf(&buf, "No versions of %s met constraints:", e.pn.ProjectRoot) for _, f := range e.fails { fmt.Fprintf(&buf, "\n\t%s: %s", f.v, f.f.Error()) } return buf.String() } func (e *noVersionError) traceString() string { if len(e.fails) == 0 { return fmt.Sprintf("No versions found") } var buf bytes.Buffer fmt.Fprintf(&buf, "No versions of %s met constraints:", e.pn.ProjectRoot) for _, f := range e.fails { if te, ok := f.f.(traceError); ok { fmt.Fprintf(&buf, "\n %s: %s", f.v, te.traceString()) } else { fmt.Fprintf(&buf, "\n %s: %s", f.v, f.f.Error()) } } return buf.String() } // caseMismatchFailure occurs when there are import paths that differ only by // case. The compiler disallows this case. type caseMismatchFailure struct { // goal is the depender atom that tried to introduce the case-varying name, // along with the case-varying name. goal dependency // current is the specific casing of a ProjectRoot that is presently // selected for all possible case variations of its contained unicode code // points. current ProjectRoot // failsib is the list of active dependencies that have determined the // specific casing for the target project. failsib []dependency } func (e *caseMismatchFailure) Error() string { if len(e.failsib) == 1 { str := "Could not introduce %s due to a case-only variation: it depends on %q, but %q was already established as the case variant for that project root by depender %s" return fmt.Sprintf(str, a2vs(e.goal.depender), e.goal.dep.Ident.ProjectRoot, e.current, a2vs(e.failsib[0].depender)) } var buf bytes.Buffer str := "Could not introduce %s due to a case-only variation: it depends on %q, but %q was already established as the case variant for that project root by the following other dependers:\n" fmt.Fprintf(&buf, str, a2vs(e.goal.depender), e.goal.dep.Ident.ProjectRoot, e.current) for _, c := range e.failsib { fmt.Fprintf(&buf, "\t%s\n", a2vs(c.depender)) } return buf.String() } func (e *caseMismatchFailure) traceString() string { var buf bytes.Buffer fmt.Fprintf(&buf, "case-only variation in dependency on %q; %q already established by:\n", e.goal.dep.Ident.ProjectRoot, e.current) for _, f := range e.failsib { fmt.Fprintf(&buf, "%s\n", a2vs(f.depender)) } return buf.String() } // wrongCaseFailure occurs when one or more projects - A, B, ... - depend on // another project - Z - with an incorrect case variant, as indicated by the // case variant used internally by Z to reference its own packages. // // For example, github.com/sirupsen/logrus/hooks/syslog references itself via // github.com/sirupsen/logrus, establishing that as the canonical case variant. type wrongCaseFailure struct { // correct is the canonical representation of the ProjectRoot correct ProjectRoot // goal is the incorrectly-referenced target project goal dependency // badcase is the list of active dependencies that have specified an // incorrect ProjectRoot casing for the project in question. badcase []dependency } func (e *wrongCaseFailure) Error() string { if len(e.badcase) == 1 { str := "Could not introduce %s; imports amongst its packages establish %q as the canonical casing for root, but %s tried to import it as %q" return fmt.Sprintf(str, a2vs(e.goal.depender), e.correct, a2vs(e.badcase[0].depender), e.badcase[0].dep.Ident.ProjectRoot) } var buf bytes.Buffer str := "Could not introduce %s; imports amongst its packages establish %q as the canonical casing for root, but the following projects tried to import it as %q" fmt.Fprintf(&buf, str, a2vs(e.goal.depender), e.correct, e.badcase[0].dep.Ident.ProjectRoot) for _, c := range e.badcase { fmt.Fprintf(&buf, "\t%s\n", a2vs(c.depender)) } return buf.String() } func (e *wrongCaseFailure) traceString() string { var buf bytes.Buffer fmt.Fprintf(&buf, "internal imports establish %q as correct casing; %q was used by:\n", e.correct, e.goal.dep.Ident.ProjectRoot) for _, f := range e.badcase { fmt.Fprintf(&buf, "%s\n", a2vs(f.depender)) } return buf.String() } // disjointConstraintFailure occurs when attempting to introduce an atom that // itself has an acceptable version, but one of its dependency constraints is // disjoint with one or more dependency constraints already active for that // identifier. type disjointConstraintFailure struct { // goal is the dependency with the problematic constraint, forcing us to // reject the atom that introduces it. goal dependency // failsib is the list of active dependencies that are disjoint with the // goal dependency. This will be at least one, but may not be all of the // active dependencies. failsib []dependency // nofailsib is the list of active dependencies that are NOT disjoint with // the goal dependency. The total of nofailsib and failsib will always be // the total number of active dependencies on target identifier. nofailsib []dependency // c is the current constraint on the target identifier. It is intersection // of all the active dependencies' constraints. c Constraint } func (e *disjointConstraintFailure) Error() string { if len(e.failsib) == 1 { str := "Could not introduce %s, as it has a dependency on %s with constraint %s, which has no overlap with existing constraint %s from %s" return fmt.Sprintf(str, a2vs(e.goal.depender), e.goal.dep.Ident, e.goal.dep.Constraint.String(), e.failsib[0].dep.Constraint.String(), a2vs(e.failsib[0].depender)) } var buf bytes.Buffer var sibs []dependency if len(e.failsib) > 1 { sibs = e.failsib str := "Could not introduce %s, as it has a dependency on %s with constraint %s, which has no overlap with the following existing constraints:\n" fmt.Fprintf(&buf, str, a2vs(e.goal.depender), e.goal.dep.Ident, e.goal.dep.Constraint.String()) } else { sibs = e.nofailsib str := "Could not introduce %s, as it has a dependency on %s with constraint %s, which does not overlap with the intersection of existing constraints from other currently selected packages:\n" fmt.Fprintf(&buf, str, a2vs(e.goal.depender), e.goal.dep.Ident, e.goal.dep.Constraint.String()) } for _, c := range sibs { fmt.Fprintf(&buf, "\t%s from %s\n", c.dep.Constraint.String(), a2vs(c.depender)) } return buf.String() } func (e *disjointConstraintFailure) traceString() string { var buf bytes.Buffer fmt.Fprintf(&buf, "constraint %s on %s disjoint with other dependers:\n", e.goal.dep.Constraint.String(), e.goal.dep.Ident) for _, f := range e.failsib { fmt.Fprintf( &buf, "%s from %s (no overlap)\n", f.dep.Constraint.String(), a2vs(f.depender), ) } for _, f := range e.nofailsib { fmt.Fprintf( &buf, "%s from %s (some overlap)\n", f.dep.Constraint.String(), a2vs(f.depender), ) } return buf.String() } // Indicates that an atom could not be introduced because one of its dep // constraints does not admit the currently-selected version of the target // project. type constraintNotAllowedFailure struct { // The dependency with the problematic constraint that could not be // introduced. goal dependency // The (currently selected) version of the target project that was not // admissible by the goal dependency. v Version } func (e *constraintNotAllowedFailure) Error() string { return fmt.Sprintf( "Could not introduce %s, as it has a dependency on %s with constraint %s, which does not allow the currently selected version of %s", a2vs(e.goal.depender), e.goal.dep.Ident, e.goal.dep.Constraint, e.v, ) } func (e *constraintNotAllowedFailure) traceString() string { return fmt.Sprintf( "%s depends on %s with %s, but that's already selected at %s", a2vs(e.goal.depender), e.goal.dep.Ident.ProjectRoot, e.goal.dep.Constraint, e.v, ) } // versionNotAllowedFailure describes a failure where an atom is rejected // because its version is not allowed by current constraints. // // (This is one of the more straightforward types of failures) type versionNotAllowedFailure struct { // goal is the atom that was rejected by current constraints. goal atom // failparent is the list of active dependencies that caused the atom to be // rejected. Note that this only includes dependencies that actually // rejected the atom, which will be at least one, but may not be all the // active dependencies on the atom's identifier. failparent []dependency // c is the current constraint on the atom's identifier. This is the intersection // of all active dependencies' constraints. c Constraint } func (e *versionNotAllowedFailure) Error() string { if len(e.failparent) == 1 { return fmt.Sprintf( "Could not introduce %s, as it is not allowed by constraint %s from project %s.", a2vs(e.goal), e.failparent[0].dep.Constraint.String(), e.failparent[0].depender.id, ) } var buf bytes.Buffer fmt.Fprintf(&buf, "Could not introduce %s, as it is not allowed by constraints from the following projects:\n", a2vs(e.goal)) for _, f := range e.failparent { fmt.Fprintf(&buf, "\t%s from %s\n", f.dep.Constraint.String(), a2vs(f.depender)) } return buf.String() } func (e *versionNotAllowedFailure) traceString() string { var buf bytes.Buffer fmt.Fprintf(&buf, "%s not allowed by constraint %s:\n", a2vs(e.goal), e.c.String()) for _, f := range e.failparent { fmt.Fprintf(&buf, " %s from %s\n", f.dep.Constraint.String(), a2vs(f.depender)) } return buf.String() } type missingSourceFailure struct { goal ProjectIdentifier prob string } func (e *missingSourceFailure) Error() string { return fmt.Sprintf(e.prob, e.goal) } type badOptsFailure string func (e badOptsFailure) Error() string { return string(e) } type sourceMismatchFailure struct { // The ProjectRoot over which there is disagreement about where it should be // sourced from shared ProjectRoot // The current value for the network source current string // The mismatched value for the network source mismatch string // The currently selected dependencies which have agreed upon/established // the given network source sel []dependency // The atom with the constraint that has the new, incompatible network source prob atom } func (e *sourceMismatchFailure) Error() string { var cur []string for _, c := range e.sel { cur = append(cur, string(c.depender.id.ProjectRoot)) } str := "Could not introduce %s, as it depends on %s from %s, but %s is already marked as coming from %s by %s" return fmt.Sprintf(str, a2vs(e.prob), e.shared, e.mismatch, e.shared, e.current, strings.Join(cur, ", ")) } func (e *sourceMismatchFailure) traceString() string { var buf bytes.Buffer fmt.Fprintf(&buf, "disagreement on network addr for %s:\n", e.shared) fmt.Fprintf(&buf, " %s from %s\n", e.mismatch, e.prob.id) for _, dep := range e.sel { fmt.Fprintf(&buf, " %s from %s\n", e.current, dep.depender.id) } return buf.String() } type errDeppers struct { err error deppers []atom } // checkeeHasProblemPackagesFailure indicates that the goal atom was rejected // because one or more of the packages required by its deppers had errors. // // "errors" includes package nonexistence, which is indicated by a nil err in // the corresponding errDeppers failpkg map value. // // checkeeHasProblemPackagesFailure complements depHasProblemPackagesFailure; // one or the other could appear to describe the same fundamental issue, // depending on the order in which dependencies were visited. type checkeeHasProblemPackagesFailure struct { // goal is the atom that was rejected due to problematic packages. goal atom // failpkg is a map of package names to the error describing the problem // with them, plus a list of the selected atoms that require that package. failpkg map[string]errDeppers } func (e *checkeeHasProblemPackagesFailure) Error() string { var buf bytes.Buffer indent := "" if len(e.failpkg) > 1 { indent = "\t" fmt.Fprintf( &buf, "Could not introduce %s due to multiple problematic subpackages:\n", a2vs(e.goal), ) } for pkg, errdep := range e.failpkg { var cause string if errdep.err == nil { cause = "is missing" } else { cause = fmt.Sprintf("does not contain usable Go code (%T).", errdep.err) } if len(e.failpkg) == 1 { fmt.Fprintf( &buf, "Could not introduce %s, as its subpackage %s %s.", a2vs(e.goal), pkg, cause, ) } else { fmt.Fprintf(&buf, "\tSubpackage %s %s.", pkg, cause) } if len(errdep.deppers) == 1 { fmt.Fprintf( &buf, " (Package is required by %s.)", a2vs(errdep.deppers[0]), ) } else { fmt.Fprintf(&buf, " Package is required by:") for _, pa := range errdep.deppers { fmt.Fprintf(&buf, "\n%s\t%s", indent, a2vs(pa)) } } } return buf.String() } func (e *checkeeHasProblemPackagesFailure) traceString() string { var buf bytes.Buffer fmt.Fprintf(&buf, "%s at %s has problem subpkg(s):\n", e.goal.id.ProjectRoot, e.goal.v) for pkg, errdep := range e.failpkg { if errdep.err == nil { fmt.Fprintf(&buf, "\t%s is missing; ", pkg) } else { fmt.Fprintf(&buf, "\t%s has err (%T); ", pkg, errdep.err) } if len(errdep.deppers) == 1 { fmt.Fprintf(&buf, "required by %s.", a2vs(errdep.deppers[0])) } else { fmt.Fprintf(&buf, " required by:") for _, pa := range errdep.deppers { fmt.Fprintf(&buf, "\n\t\t%s at %s", pa.id, pa.v) } } } return buf.String() } // depHasProblemPackagesFailure indicates that the goal dependency was rejected // because there were problems with one or more of the packages the dependency // requires in the atom currently selected for that dependency. (This failure // can only occur if the target dependency is already selected.) // // "errors" includes package nonexistence, which is indicated by a nil err as // the corresponding prob map value. // // depHasProblemPackagesFailure complements checkeeHasProblemPackagesFailure; // one or the other could appear to describe the same fundamental issue, // depending on the order in which dependencies were visited. type depHasProblemPackagesFailure struct { // goal is the dependency that was rejected due to the atom currently // selected for the dependency's target id having errors (including, and // probably most commonly, // nonexistence) in one or more packages named by the dependency. goal dependency // v is the version of the currently selected atom targeted by the goal // dependency. v Version // prob is a map of problem packages to their specific error. It does not // include missing packages. prob map[string]error } func (e *depHasProblemPackagesFailure) Error() string { fcause := func(pkg string) string { if err := e.prob[pkg]; err != nil { return fmt.Sprintf("does not contain usable Go code (%T).", err) } return "is missing." } if len(e.prob) == 1 { var pkg string for pkg = range e.prob { } return fmt.Sprintf( "Could not introduce %s, as it requires package %s from %s, but in version %s that package %s", a2vs(e.goal.depender), pkg, e.goal.dep.Ident, e.v, fcause(pkg), ) } var buf bytes.Buffer fmt.Fprintf( &buf, "Could not introduce %s, as it requires problematic packages from %s (current version %s):", a2vs(e.goal.depender), e.goal.dep.Ident, e.v, ) pkgs := make([]string, len(e.prob)) k := 0 for pkg := range e.prob { pkgs[k] = pkg k++ } sort.Strings(pkgs) for _, pkg := range pkgs { fmt.Fprintf(&buf, "\t%s %s", pkg, fcause(pkg)) } return buf.String() } func (e *depHasProblemPackagesFailure) traceString() string { var buf bytes.Buffer fcause := func(pkg string) string { if err := e.prob[pkg]; err != nil { return fmt.Sprintf("has parsing err (%T).", err) } return "is missing" } fmt.Fprintf( &buf, "%s depping on %s at %s has problem subpkg(s):", a2vs(e.goal.depender), e.goal.dep.Ident, e.v, ) pkgs := make([]string, len(e.prob)) k := 0 for pkg := range e.prob { pkgs[k] = pkg k++ } sort.Strings(pkgs) for _, pkg := range pkgs { fmt.Fprintf(&buf, "\t%s %s", pkg, fcause(pkg)) } return buf.String() } // nonexistentRevisionFailure indicates that a revision constraint was specified // for a given project, but that that revision does not exist in the source // repository. type nonexistentRevisionFailure struct { goal dependency r Revision } func (e *nonexistentRevisionFailure) Error() string { return fmt.Sprintf( "Could not introduce %s, as it requires %s at revision %s, but that revision does not exist", a2vs(e.goal.depender), e.goal.dep.Ident, e.r, ) } func (e *nonexistentRevisionFailure) traceString() string { return fmt.Sprintf( "%s wants missing rev %s of %s", a2vs(e.goal.depender), e.r, e.goal.dep.Ident, ) }
dep/gps/solve_failures.go/0
{ "file_path": "dep/gps/solve_failures.go", "repo_id": "dep", "token_count": 6001 }
31
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gps import ( "context" "fmt" "io/ioutil" "log" "os" "path/filepath" "testing" "github.com/golang/dep/gps/pkgtree" "github.com/golang/dep/internal/test" ) // Executed in parallel by TestSlowVcs func testSourceGateway(t *testing.T) { t.Parallel() if testing.Short() { t.Skip("Skipping gateway testing in short mode") } requiresBins(t, "git") cachedir, err := ioutil.TempDir("", "smcache") if err != nil { t.Fatalf("failed to create temp dir: %s", err) } bgc := context.Background() ctx, cancelFunc := context.WithCancel(bgc) defer func() { os.RemoveAll(cachedir) cancelFunc() }() os.Mkdir(filepath.Join(cachedir, "sources"), 0777) do := func(wantstate sourceState) func(t *testing.T) { return func(t *testing.T) { superv := newSupervisor(ctx) deducer := newDeductionCoordinator(superv) logger := log.New(test.Writer{TB: t}, "", 0) sc := newSourceCoordinator(superv, deducer, cachedir, nil, logger) defer sc.close() id := mkPI("github.com/sdboyer/deptest") sg, err := sc.getSourceGatewayFor(ctx, id) if err != nil { t.Fatal(err) } if sg.srcState != wantstate { t.Fatalf("expected state to be %q, got %q", wantstate, sg.srcState) } if err := sg.existsUpstream(ctx); err != nil { t.Fatalf("failed to verify upstream source: %s", err) } wantstate |= sourceExistsUpstream if sg.src.existsCallsListVersions() { wantstate |= sourceHasLatestVersionList } if sg.srcState != wantstate { t.Fatalf("expected state to be %q, got %q", wantstate, sg.srcState) } if err := sg.syncLocal(ctx); err != nil { t.Fatalf("error on cloning git repo: %s", err) } wantstate |= sourceExistsLocally | sourceHasLatestLocally if sg.srcState != wantstate { t.Fatalf("expected state to be %q, got %q", wantstate, sg.srcState) } if _, ok := sg.src.(*gitSource); !ok { t.Fatalf("Expected a gitSource, got a %T", sg.src) } vlist, err := sg.listVersions(ctx) if err != nil { t.Fatalf("Unexpected error getting version pairs from git repo: %s", err) } wantstate |= sourceHasLatestVersionList if sg.srcState != wantstate { t.Fatalf("expected state to be %q, got %q", wantstate, sg.srcState) } if len(vlist) != 4 { t.Fatalf("git test repo should've produced four versions, got %v: vlist was %s", len(vlist), vlist) } else { SortPairedForUpgrade(vlist) evl := []PairedVersion{ NewVersion("v1.0.0").Pair(Revision("ff2948a2ac8f538c4ecd55962e919d1e13e74baf")), NewVersion("v0.8.1").Pair(Revision("3f4c3bea144e112a69bbe5d8d01c1b09a544253f")), NewVersion("v0.8.0").Pair(Revision("ff2948a2ac8f538c4ecd55962e919d1e13e74baf")), newDefaultBranch("master").Pair(Revision("3f4c3bea144e112a69bbe5d8d01c1b09a544253f")), } if len(evl) != len(vlist) { t.Errorf("expected %d versions but got %d", len(evl), len(vlist)) } else { for i := range evl { if !evl[i].identical(vlist[i]) { t.Errorf("index %d: expected version identical to %#v but got %#v", i, evl[i], vlist[i]) } } } } rev := Revision("c575196502940c07bf89fd6d95e83b999162e051") // check that an expected rev is not in cache _, has := sg.cache.getVersionsFor(rev) if has { t.Fatal("shouldn't have bare revs in cache without specifically requesting them") } is, err := sg.revisionPresentIn(ctx, rev) if err != nil { t.Fatalf("unexpected error while checking revision presence: %s", err) } else if !is { t.Fatalf("revision that should exist was not present") } // check that an expected rev is not in cache _, has = sg.cache.getVersionsFor(rev) if !has { t.Fatal("bare rev should be in cache after specific request for it") } // Ensure that a bad rev doesn't work on any method that takes // versions badver := NewVersion("notexist") wanterr := fmt.Errorf("version %q does not exist in source", badver) _, _, err = sg.getManifestAndLock(ctx, ProjectRoot("github.com/sdboyer/deptest"), badver, naiveAnalyzer{}) if err == nil { t.Fatal("wanted err on nonexistent version") } else if err.Error() != wanterr.Error() { t.Fatalf("wanted nonexistent err when passing bad version, got: %s", err) } _, err = sg.listPackages(ctx, ProjectRoot("github.com/sdboyer/deptest"), badver) if err == nil { t.Fatal("wanted err on nonexistent version") } else if err.Error() != wanterr.Error() { t.Fatalf("wanted nonexistent err when passing bad version, got: %s", err) } err = sg.exportVersionTo(ctx, badver, cachedir) if err == nil { t.Fatal("wanted err on nonexistent version") } else if err.Error() != wanterr.Error() { t.Fatalf("wanted nonexistent err when passing bad version, got: %s", err) } wantptree := pkgtree.PackageTree{ ImportRoot: "github.com/sdboyer/deptest", Packages: map[string]pkgtree.PackageOrErr{ "github.com/sdboyer/deptest": { P: pkgtree.Package{ ImportPath: "github.com/sdboyer/deptest", Name: "deptest", Imports: []string{}, }, }, }, } ptree, err := sg.listPackages(ctx, ProjectRoot("github.com/sdboyer/deptest"), Revision("ff2948a2ac8f538c4ecd55962e919d1e13e74baf")) if err != nil { t.Fatalf("unexpected err when getting package tree with known rev: %s", err) } comparePackageTree(t, wantptree, ptree) ptree, err = sg.listPackages(ctx, ProjectRoot("github.com/sdboyer/deptest"), NewVersion("v1.0.0")) if err != nil { t.Fatalf("unexpected err when getting package tree with unpaired good version: %s", err) } comparePackageTree(t, wantptree, ptree) } } // Run test twice so that we cover both the existing and non-existing case. t.Run("empty", do(sourceExistsUpstream|sourceHasLatestVersionList)) t.Run("exists", do(sourceExistsLocally)) }
dep/gps/source_test.go/0
{ "file_path": "dep/gps/source_test.go", "repo_id": "dep", "token_count": 2564 }
32
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package verify import ( "fmt" "math/bits" "strings" "testing" "github.com/golang/dep/gps" ) func contains(haystack []string, needle string) bool { for _, str := range haystack { if str == needle { return true } } return false } func (dd DeltaDimension) String() string { var parts []string for dd != 0 { index := bits.TrailingZeros32(uint32(dd)) dd &= ^(1 << uint(index)) switch DeltaDimension(1 << uint(index)) { case InputImportsChanged: parts = append(parts, "input imports") case ProjectAdded: parts = append(parts, "project added") case ProjectRemoved: parts = append(parts, "project removed") case SourceChanged: parts = append(parts, "source changed") case VersionChanged: parts = append(parts, "version changed") case RevisionChanged: parts = append(parts, "revision changed") case PackagesChanged: parts = append(parts, "packages changed") case PruneOptsChanged: parts = append(parts, "pruneopts changed") case HashVersionChanged: parts = append(parts, "hash version changed") case HashChanged: parts = append(parts, "hash digest changed") } } return strings.Join(parts, ", ") } func TestLockDelta(t *testing.T) { fooversion := gps.NewVersion("v1.0.0").Pair("foorev1") bazversion := gps.NewVersion("v2.0.0").Pair("bazrev1") transver := gps.NewVersion("v0.5.0").Pair("transrev1") l := safeLock{ i: []string{"foo.com/bar", "baz.com/qux"}, p: []gps.LockedProject{ newVerifiableProject(mkPI("foo.com/bar"), fooversion, []string{".", "subpkg"}), newVerifiableProject(mkPI("baz.com/qux"), bazversion, []string{".", "other"}), newVerifiableProject(mkPI("transitive.com/dependency"), transver, []string{"."}), }, } var dup lockTransformer = func(l safeLock) safeLock { return l.dup() } tt := map[string]struct { lt lockTransformer delta DeltaDimension checkfn func(*testing.T, LockDelta) }{ "ident": { lt: dup, }, "added import": { lt: dup.addII("other.org"), delta: InputImportsChanged, }, "added import 2x": { lt: dup.addII("other.org").addII("andsomethingelse.com/wowie"), delta: InputImportsChanged, checkfn: func(t *testing.T, ld LockDelta) { if !contains(ld.AddedImportInputs, "other.org") { t.Error("first added input import missing") } if !contains(ld.AddedImportInputs, "andsomethingelse.com/wowie") { t.Error("first added input import missing") } }, }, "removed import": { lt: dup.rmII("baz.com/qux"), delta: InputImportsChanged, checkfn: func(t *testing.T, ld LockDelta) { if !contains(ld.RemovedImportInputs, "baz.com/qux") { t.Error("removed input import missing") } }, }, "add project": { lt: dup.addDumbProject("madeup.org"), delta: ProjectAdded, }, "remove project": { lt: dup.rmProject("foo.com/bar"), delta: ProjectRemoved, }, "remove last project": { lt: dup.rmProject("transitive.com/dependency"), delta: ProjectRemoved, }, "all": { lt: dup.addII("other.org").rmII("baz.com/qux").addDumbProject("zebrafun.org").rmProject("foo.com/bar"), delta: InputImportsChanged | ProjectRemoved | ProjectAdded, }, "remove all projects and imports": { lt: dup.rmII("baz.com/qux").rmII("foo.com/bar").rmProject("baz.com/qux").rmProject("foo.com/bar").rmProject("transitive.com/dependency"), delta: InputImportsChanged | ProjectRemoved, }, } for name, fix := range tt { fix := fix t.Run(name, func(t *testing.T) { fixl := fix.lt(l) ld := DiffLocks(l, fixl) if !ld.Changed(AnyChanged) && fix.delta != 0 { t.Errorf("Changed() reported false when expecting some dimensions to be changed: %s", fix.delta) } else if ld.Changed(AnyChanged) && fix.delta == 0 { t.Error("Changed() reported true when expecting no changes") } if ld.Changed(AnyChanged & ^fix.delta) { t.Errorf("Changed() reported true when checking along not-expected dimensions: %s", ld.Changes() & ^fix.delta) } gotdelta := ld.Changes() if fix.delta & ^gotdelta != 0 { t.Errorf("wanted change in some dimensions that were unchanged: %s", fix.delta & ^gotdelta) } if gotdelta & ^fix.delta != 0 { t.Errorf("did not want change in some dimensions that were changed: %s", gotdelta & ^fix.delta) } if fix.checkfn != nil { fix.checkfn(t, ld) } }) } } func TestLockedProjectPropertiesDelta(t *testing.T) { fooversion, foorev := gps.NewVersion("v1.0.0"), gps.Revision("foorev1") foopair := fooversion.Pair(foorev) foovp := VerifiableProject{ LockedProject: gps.NewLockedProject(mkPI("foo.com/project"), foopair, []string{".", "subpkg"}), PruneOpts: gps.PruneNestedVendorDirs, Digest: VersionedDigest{ HashVersion: HashVersion, Digest: []byte("foobytes"), }, } var dup lockedProjectTransformer = func(lp gps.LockedProject) gps.LockedProject { return lp.(VerifiableProject).dup() } tt := map[string]struct { lt1, lt2 lockedProjectTransformer delta DeltaDimension checkfn func(*testing.T, LockedProjectPropertiesDelta) }{ "ident": { lt1: dup, }, "add pkg": { lt1: dup.addPkg("whatev"), delta: PackagesChanged, }, "rm pkg": { lt1: dup.rmPkg("subpkg"), delta: PackagesChanged, }, "add and rm pkg": { lt1: dup.rmPkg("subpkg").addPkg("whatev"), delta: PackagesChanged, checkfn: func(t *testing.T, ld LockedProjectPropertiesDelta) { if !contains(ld.PackagesAdded, "whatev") { t.Error("added pkg missing from list") } if !contains(ld.PackagesRemoved, "subpkg") { t.Error("removed pkg missing from list") } }, }, "add source": { lt1: dup.setSource("somethingelse"), delta: SourceChanged, }, "remove source": { lt1: dup.setSource("somethingelse"), lt2: dup, delta: SourceChanged, }, "to rev only": { lt1: dup.setVersion(foorev), delta: VersionChanged, }, "from rev only": { lt1: dup.setVersion(foorev), lt2: dup, delta: VersionChanged, }, "to new rev only": { lt1: dup.setVersion(gps.Revision("newrev")), delta: VersionChanged | RevisionChanged, }, "from new rev only": { lt1: dup.setVersion(gps.Revision("newrev")), lt2: dup, delta: VersionChanged | RevisionChanged, }, "version change": { lt1: dup.setVersion(gps.NewVersion("v0.5.0").Pair(foorev)), delta: VersionChanged, }, "version change to norev": { lt1: dup.setVersion(gps.NewVersion("v0.5.0")), delta: VersionChanged | RevisionChanged, }, "version change from norev": { lt1: dup.setVersion(gps.NewVersion("v0.5.0")), lt2: dup.setVersion(gps.NewVersion("v0.5.0").Pair(foorev)), delta: RevisionChanged, }, "to branch": { lt1: dup.setVersion(gps.NewBranch("master").Pair(foorev)), delta: VersionChanged, }, "to branch new rev": { lt1: dup.setVersion(gps.NewBranch("master").Pair(gps.Revision("newrev"))), delta: VersionChanged | RevisionChanged, }, "to empty prune opts": { lt1: dup.setPruneOpts(0), delta: PruneOptsChanged, }, "from empty prune opts": { lt1: dup.setPruneOpts(0), lt2: dup, delta: PruneOptsChanged, }, "prune opts change": { lt1: dup.setPruneOpts(gps.PruneNestedVendorDirs | gps.PruneNonGoFiles), delta: PruneOptsChanged, }, "empty digest": { lt1: dup.setDigest(VersionedDigest{}), delta: HashVersionChanged | HashChanged, }, "to empty digest": { lt1: dup.setDigest(VersionedDigest{}), lt2: dup, delta: HashVersionChanged | HashChanged, }, "hash version changed": { lt1: dup.setDigest(VersionedDigest{HashVersion: HashVersion + 1, Digest: []byte("foobytes")}), delta: HashVersionChanged, }, "hash contents changed": { lt1: dup.setDigest(VersionedDigest{HashVersion: HashVersion, Digest: []byte("barbytes")}), delta: HashChanged, }, "to plain locked project": { lt1: dup.toPlainLP(), delta: PruneOptsChanged | HashChanged | HashVersionChanged, }, "from plain locked project": { lt1: dup.toPlainLP(), lt2: dup, delta: PruneOptsChanged | HashChanged | HashVersionChanged, }, "all": { lt1: dup.setDigest(VersionedDigest{}).setVersion(gps.NewBranch("master").Pair(gps.Revision("newrev"))).setPruneOpts(gps.PruneNestedVendorDirs | gps.PruneNonGoFiles).setSource("whatever"), delta: SourceChanged | VersionChanged | RevisionChanged | PruneOptsChanged | HashChanged | HashVersionChanged, }, } for name, fix := range tt { fix := fix t.Run(name, func(t *testing.T) { // Use two patterns for constructing locks to compare: if only lt1 // is set, use foovp as the first lp and compare with the lt1 // transforms applied. If lt2 is set, transform foovp with lt1 for // the first lp, then transform foovp with lt2 for the second lp. var lp1, lp2 gps.LockedProject if fix.lt2 == nil { lp1 = foovp lp2 = fix.lt1(foovp) } else { lp1 = fix.lt1(foovp) lp2 = fix.lt2(foovp) } lppd := DiffLockedProjectProperties(lp1, lp2) if !lppd.Changed(AnyChanged) && fix.delta != 0 { t.Errorf("Changed() reporting false when expecting some dimensions to be changed: %s", fix.delta) } else if lppd.Changed(AnyChanged) && fix.delta == 0 { t.Error("Changed() reporting true when expecting no changes") } if lppd.Changed(AnyChanged & ^fix.delta) { t.Errorf("Changed() reported true when checking along not-expected dimensions: %s", lppd.Changes() & ^fix.delta) } gotdelta := lppd.Changes() if fix.delta & ^gotdelta != 0 { t.Errorf("wanted change in some dimensions that were unchanged: %s", fix.delta & ^gotdelta) } if gotdelta & ^fix.delta != 0 { t.Errorf("did not want change in some dimensions that were changed: %s", gotdelta & ^fix.delta) } if fix.checkfn != nil { fix.checkfn(t, lppd) } }) } } type lockTransformer func(safeLock) safeLock func (lt lockTransformer) compose(lt2 lockTransformer) lockTransformer { if lt == nil { return lt2 } return func(l safeLock) safeLock { return lt2(lt(l)) } } func (lt lockTransformer) addDumbProject(root string) lockTransformer { vp := newVerifiableProject(mkPI(root), gps.NewVersion("whatever").Pair("addedrev"), []string{"."}) return lt.compose(func(l safeLock) safeLock { for _, lp := range l.p { if lp.Ident().ProjectRoot == vp.Ident().ProjectRoot { panic(fmt.Sprintf("%q already in lock", vp.Ident().ProjectRoot)) } } l.p = append(l.p, vp) return l }) } func (lt lockTransformer) rmProject(pr string) lockTransformer { return lt.compose(func(l safeLock) safeLock { for k, lp := range l.p { if lp.Ident().ProjectRoot == gps.ProjectRoot(pr) { l.p = l.p[:k+copy(l.p[k:], l.p[k+1:])] return l } } panic(fmt.Sprintf("%q not in lock", pr)) }) } func (lt lockTransformer) addII(path string) lockTransformer { return lt.compose(func(l safeLock) safeLock { for _, impath := range l.i { if path == impath { panic(fmt.Sprintf("%q already in input imports", impath)) } } l.i = append(l.i, path) return l }) } func (lt lockTransformer) rmII(path string) lockTransformer { return lt.compose(func(l safeLock) safeLock { for k, impath := range l.i { if path == impath { l.i = l.i[:k+copy(l.i[k:], l.i[k+1:])] return l } } panic(fmt.Sprintf("%q not in input imports", path)) }) } type lockedProjectTransformer func(gps.LockedProject) gps.LockedProject func (lpt lockedProjectTransformer) compose(lpt2 lockedProjectTransformer) lockedProjectTransformer { if lpt == nil { return lpt2 } return func(lp gps.LockedProject) gps.LockedProject { return lpt2(lpt(lp)) } } func (lpt lockedProjectTransformer) addPkg(path string) lockedProjectTransformer { return lpt.compose(func(lp gps.LockedProject) gps.LockedProject { for _, pkg := range lp.Packages() { if path == pkg { panic(fmt.Sprintf("%q already in pkg list", path)) } } nlp := gps.NewLockedProject(lp.Ident(), lp.Version(), append(lp.Packages(), path)) if vp, ok := lp.(VerifiableProject); ok { vp.LockedProject = nlp return vp } return nlp }) } func (lpt lockedProjectTransformer) rmPkg(path string) lockedProjectTransformer { return lpt.compose(func(lp gps.LockedProject) gps.LockedProject { pkglist := lp.Packages() for k, pkg := range pkglist { if path == pkg { pkglist = pkglist[:k+copy(pkglist[k:], pkglist[k+1:])] nlp := gps.NewLockedProject(lp.Ident(), lp.Version(), pkglist) if vp, ok := lp.(VerifiableProject); ok { vp.LockedProject = nlp return vp } return nlp } } panic(fmt.Sprintf("%q not in pkg list", path)) }) } func (lpt lockedProjectTransformer) setSource(source string) lockedProjectTransformer { return lpt.compose(func(lp gps.LockedProject) gps.LockedProject { ident := lp.Ident() ident.Source = source nlp := gps.NewLockedProject(ident, lp.Version(), lp.Packages()) if vp, ok := lp.(VerifiableProject); ok { vp.LockedProject = nlp return vp } return nlp }) } func (lpt lockedProjectTransformer) setVersion(v gps.Version) lockedProjectTransformer { return lpt.compose(func(lp gps.LockedProject) gps.LockedProject { nlp := gps.NewLockedProject(lp.Ident(), v, lp.Packages()) if vp, ok := lp.(VerifiableProject); ok { vp.LockedProject = nlp return vp } return nlp }) } func (lpt lockedProjectTransformer) setPruneOpts(po gps.PruneOptions) lockedProjectTransformer { return lpt.compose(func(lp gps.LockedProject) gps.LockedProject { vp := lp.(VerifiableProject) vp.PruneOpts = po return vp }) } func (lpt lockedProjectTransformer) setDigest(vd VersionedDigest) lockedProjectTransformer { return lpt.compose(func(lp gps.LockedProject) gps.LockedProject { vp := lp.(VerifiableProject) vp.Digest = vd return vp }) } func (lpt lockedProjectTransformer) toPlainLP() lockedProjectTransformer { return lpt.compose(func(lp gps.LockedProject) gps.LockedProject { if vp, ok := lp.(VerifiableProject); ok { return vp.LockedProject } return lp }) }
dep/gps/verify/lockdiff_test.go/0
{ "file_path": "dep/gps/verify/lockdiff_test.go", "repo_id": "dep", "token_count": 5949 }
33
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package feedback import ( "bytes" log2 "log" "strings" "testing" "github.com/golang/dep/gps" _ "github.com/golang/dep/internal/test" // DO NOT REMOVE, allows go test ./... -update to work ) func TestFeedback_Constraint(t *testing.T) { ver, _ := gps.NewSemverConstraint("^1.0.0") rev := gps.Revision("1b8edb3") pi := gps.ProjectIdentifier{ProjectRoot: gps.ProjectRoot("github.com/foo/bar")} cases := []struct { feedback *ConstraintFeedback want string }{ { feedback: NewConstraintFeedback(gps.ProjectConstraint{Constraint: ver, Ident: pi}, DepTypeDirect), want: "Using ^1.0.0 as constraint for direct dep github.com/foo/bar", }, { feedback: NewConstraintFeedback(gps.ProjectConstraint{Constraint: ver, Ident: pi}, DepTypeImported), want: "Using ^1.0.0 as initial constraint for imported dep github.com/foo/bar", }, { feedback: NewConstraintFeedback(gps.ProjectConstraint{Constraint: gps.Any(), Ident: pi}, DepTypeImported), want: "Using * as initial constraint for imported dep github.com/foo/bar", }, { feedback: NewConstraintFeedback(gps.ProjectConstraint{Constraint: rev, Ident: pi}, DepTypeDirect), want: "Using 1b8edb3 as hint for direct dep github.com/foo/bar", }, { feedback: NewConstraintFeedback(gps.ProjectConstraint{Constraint: rev, Ident: pi}, DepTypeImported), want: "Using 1b8edb3 as initial hint for imported dep github.com/foo/bar", }, } for _, c := range cases { buf := &bytes.Buffer{} log := log2.New(buf, "", 0) c.feedback.LogFeedback(log) got := strings.TrimSpace(buf.String()) if c.want != got { t.Errorf("Feedbacks are not expected: \n\t(GOT) '%s'\n\t(WNT) '%s'", got, c.want) } } } func TestFeedback_LockedProject(t *testing.T) { v := gps.NewVersion("v1.1.4").Pair("bc29b4f") b := gps.NewBranch("master").Pair("436f39d") pi := gps.ProjectIdentifier{ProjectRoot: gps.ProjectRoot("github.com/foo/bar")} cases := []struct { feedback *ConstraintFeedback want string }{ { feedback: NewLockedProjectFeedback(gps.NewLockedProject(pi, v, nil), DepTypeDirect), want: "Locking in v1.1.4 (bc29b4f) for direct dep github.com/foo/bar", }, { feedback: NewLockedProjectFeedback(gps.NewLockedProject(pi, v, nil), DepTypeImported), want: "Trying v1.1.4 (bc29b4f) as initial lock for imported dep github.com/foo/bar", }, { feedback: NewLockedProjectFeedback(gps.NewLockedProject(pi, gps.NewVersion("").Pair("bc29b4f"), nil), DepTypeImported), want: "Trying * (bc29b4f) as initial lock for imported dep github.com/foo/bar", }, { feedback: NewLockedProjectFeedback(gps.NewLockedProject(pi, b, nil), DepTypeTransitive), want: "Locking in master (436f39d) for transitive dep github.com/foo/bar", }, } for _, c := range cases { buf := &bytes.Buffer{} log := log2.New(buf, "", 0) c.feedback.LogFeedback(log) got := strings.TrimSpace(buf.String()) if c.want != got { t.Errorf("Feedbacks are not expected: \n\t(GOT) '%s'\n\t(WNT) '%s'", got, c.want) } } } func TestFeedback_BrokenImport(t *testing.T) { pi := gps.ProjectIdentifier{ProjectRoot: gps.ProjectRoot("github.com/foo/bar")} cases := []struct { oldVersion gps.Version currentVersion gps.Version pID gps.ProjectIdentifier altPID gps.ProjectIdentifier want string name string }{ { oldVersion: gps.NewVersion("v1.1.4").Pair("bc29b4f"), currentVersion: gps.NewVersion("v1.2.0").Pair("ia3da28"), pID: pi, altPID: pi, want: "Warning: Unable to preserve imported lock v1.1.4 (bc29b4f) for github.com/foo/bar. Locking in v1.2.0 (ia3da28)", name: "Basic broken import", }, { oldVersion: gps.NewBranch("master").Pair("bc29b4f"), currentVersion: gps.NewBranch("dev").Pair("ia3da28"), pID: pi, altPID: pi, want: "Warning: Unable to preserve imported lock master (bc29b4f) for github.com/foo/bar. Locking in dev (ia3da28)", name: "Branches", }, { oldVersion: gps.NewBranch("master").Pair("bc29b4f"), currentVersion: gps.NewBranch("dev").Pair("ia3da28"), pID: pi, altPID: gps.ProjectIdentifier{ProjectRoot: gps.ProjectRoot("github.com/foo/boo")}, want: "Warning: Unable to preserve imported lock master (bc29b4f) for github.com/foo/bar. The project was removed from the lock because it is not used.", name: "Branches", }, { oldVersion: gps.NewBranch("master").Pair("bc29b4f"), currentVersion: gps.NewBranch("dev").Pair("ia3da28"), pID: gps.ProjectIdentifier{ProjectRoot: gps.ProjectRoot("github.com/foo/boo"), Source: "github.com/das/foo"}, altPID: gps.ProjectIdentifier{ProjectRoot: gps.ProjectRoot("github.com/foo/boo"), Source: "github.com/das/bar"}, want: "Warning: Unable to preserve imported lock master (bc29b4f) for github.com/foo/boo(github.com/das/foo). Locking in dev (ia3da28) for github.com/foo/boo(github.com/das/bar)", name: "With a source", }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { buf := &bytes.Buffer{} ol := gps.SimpleLock{ gps.NewLockedProject(c.pID, c.oldVersion, nil), } l := gps.SimpleLock{ gps.NewLockedProject(c.altPID, c.currentVersion, nil), } log := log2.New(buf, "", 0) feedback := NewBrokenImportFeedback(DiffLocks(&ol, &l)) feedback.LogFeedback(log) got := strings.TrimSpace(buf.String()) if c.want != got { t.Errorf("Feedbacks are not expected: \n\t(GOT) '%s'\n\t(WNT) '%s'", got, c.want) } }) } }
dep/internal/feedback/feedback_test.go/0
{ "file_path": "dep/internal/feedback/feedback_test.go", "repo_id": "dep", "token_count": 2581 }
34
package: github.com/golang/notexist homepage: http://example.com license: MIT owners: - name: Sam Boyer email: sdboyer@example.com homepage: http://sdboyer.io ignore: - github.com/sdboyer/dep-test excludeDirs: - samples import: - package: github.com/sdboyer/deptest repo: https://github.com/sdboyer/deptest.git vcs: git version: master - package: github.com/sdboyer/deptestdos version: v2.0.0 testImport: - package: github.com/golang/lint
dep/internal/importers/glide/testdata/glide.yaml/0
{ "file_path": "dep/internal/importers/glide/testdata/glide.yaml", "repo_id": "dep", "token_count": 175 }
35
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package test import ( "strings" "testing" "unicode" ) // Writer adapts a testing.TB to the io.Writer interface type Writer struct { testing.TB } func (t Writer) Write(b []byte) (n int, err error) { str := string(b) if len(str) == 0 { return 0, nil } for _, part := range strings.Split(str, "\n") { str := strings.TrimRightFunc(part, unicode.IsSpace) if len(str) != 0 { t.Log(str) } } return len(b), err }
dep/internal/test/writer.go/0
{ "file_path": "dep/internal/test/writer.go", "repo_id": "dep", "token_count": 220 }
36
ignored = ["github.com/foo/bar"] [[override]] name = "github.com/golang/dep" branch = "master" [[override]] name = "github.com/golang/dep" branch = "master"
dep/testdata/manifest/error3.toml/0
{ "file_path": "dep/testdata/manifest/error3.toml", "repo_id": "dep", "token_count": 69 }
37
package semver import ( "errors" "fmt" "strings" ) func rewriteRange(i string) string { m := constraintRangeRegex.FindAllStringSubmatch(i, -1) if m == nil { return i } o := i for _, v := range m { t := fmt.Sprintf(">= %s, <= %s", v[1], v[11]) o = strings.Replace(o, v[0], t, 1) } return o } func parseConstraint(c string, cbd bool) (Constraint, error) { m := constraintRegex.FindStringSubmatch(c) if m == nil { return nil, fmt.Errorf("Malformed constraint: %s", c) } // Handle the full wildcard case first - easy! if isX(m[3]) { return any{}, nil } ver := m[2] var wildPatch, wildMinor bool if isX(strings.TrimPrefix(m[4], ".")) { wildPatch = true wildMinor = true ver = fmt.Sprintf("%s.0.0%s", m[3], m[6]) } else if isX(strings.TrimPrefix(m[5], ".")) { wildPatch = true ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6]) } v, err := NewVersion(ver) if err != nil { // The constraintRegex should catch any regex parsing errors. So, // we should never get here. return nil, errors.New("constraint Parser Error") } // We never want to keep the "original" data in a constraint, and keeping it // around can disrupt simple equality comparisons. So, strip it out. v.original = "" // If caret-by-default flag is on and there's no operator, convert the // operator to a caret. if cbd && m[1] == "" { m[1] = "^" } switch m[1] { case "^": // Caret always expands to a range return expandCaret(v), nil case "~": // Tilde always expands to a range return expandTilde(v, wildMinor), nil case "!=": // Not equals expands to a range if no element isX(); otherwise expands // to a union of ranges return expandNeq(v, wildMinor, wildPatch), nil case "", "=": if wildPatch || wildMinor { // Equalling a wildcard has the same behavior as expanding tilde return expandTilde(v, wildMinor), nil } return v, nil case ">": return expandGreater(v, wildMinor, wildPatch, false), nil case ">=", "=>": return expandGreater(v, wildMinor, wildPatch, true), nil case "<": return expandLess(v, wildMinor, wildPatch, false), nil case "<=", "=<": return expandLess(v, wildMinor, wildPatch, true), nil default: // Shouldn't be possible to get here, unless the regex is allowing // predicate we don't know about... return nil, fmt.Errorf("Unrecognized predicate %q", m[1]) } } func expandCaret(v Version) Constraint { var maxv Version // Caret behaves like tilde below 1.0.0 if v.major == 0 { maxv.minor = v.minor + 1 } else { maxv.major = v.major + 1 } return rangeConstraint{ min: v, max: maxv, includeMin: true, includeMax: false, } } func expandTilde(v Version, wildMinor bool) Constraint { if wildMinor { // When minor is wild on a tilde, behavior is same as caret return expandCaret(v) } maxv := Version{ major: v.major, minor: v.minor + 1, patch: 0, } return rangeConstraint{ min: v, max: maxv, includeMin: true, includeMax: false, } } // expandNeq expands a "not-equals" constraint. // // If the constraint has any wildcards, it will expand into a unionConstraint // (which is how we represent a disjoint set). If there are no wildcards, it // will expand to a rangeConstraint with no min or max, but having the one // exception. func expandNeq(v Version, wildMinor, wildPatch bool) Constraint { if !(wildMinor || wildPatch) { return rangeConstraint{ min: Version{special: zeroVersion}, max: Version{special: infiniteVersion}, excl: []Version{v}, } } // Create the low range with no min, and the max as the floor admitted by // the wildcard lr := rangeConstraint{ min: Version{special: zeroVersion}, max: v, includeMax: false, } // The high range uses the derived version (bumped depending on where the // wildcards were) as the min, and is inclusive minv := Version{ major: v.major, minor: v.minor, patch: v.patch, } if wildMinor { minv.major++ } else { minv.minor++ } hr := rangeConstraint{ min: minv, max: Version{special: infiniteVersion}, includeMin: true, } return Union(lr, hr) } func expandGreater(v Version, wildMinor, wildPatch, eq bool) Constraint { if (wildMinor || wildPatch) && !eq { // wildcards negate the meaning of prerelease and other info v = Version{ major: v.major, minor: v.minor, patch: v.patch, } // Not equal but with wildcards is the weird case - we have to bump up // the next version AND make it equal if wildMinor { v.major++ } else { v.minor++ } return rangeConstraint{ min: v, max: Version{special: infiniteVersion}, includeMin: true, } } return rangeConstraint{ min: v, max: Version{special: infiniteVersion}, includeMin: eq, } } func expandLess(v Version, wildMinor, wildPatch, eq bool) Constraint { if eq && (wildMinor || wildPatch) { // wildcards negate the meaning of prerelease and other info v = Version{ major: v.major, minor: v.minor, patch: v.patch, } if wildMinor { v.major++ } else if wildPatch { v.minor++ } return rangeConstraint{ min: Version{special: zeroVersion}, max: v, includeMax: false, } } return rangeConstraint{ min: Version{special: zeroVersion}, max: v, includeMax: eq, } } func isX(x string) bool { l := strings.ToLower(x) return l == "x" || l == "*" }
dep/vendor/github.com/Masterminds/semver/parse.go/0
{ "file_path": "dep/vendor/github.com/Masterminds/semver/parse.go", "repo_id": "dep", "token_count": 2161 }
38
package bolt // maxMapSize represents the largest mmap size supported by Bolt. const maxMapSize = 0x7FFFFFFF // 2GB // maxAllocSize is the size used when creating array pointers. const maxAllocSize = 0xFFFFFFF // Are unaligned load/stores broken on this arch? var brokenUnaligned = false
dep/vendor/github.com/boltdb/bolt/bolt_386.go/0
{ "file_path": "dep/vendor/github.com/boltdb/bolt/bolt_386.go", "repo_id": "dep", "token_count": 83 }
39
package bolt import ( "errors" "fmt" "hash/fnv" "log" "os" "runtime" "runtime/debug" "strings" "sync" "time" "unsafe" ) // The largest step that can be taken when remapping the mmap. const maxMmapStep = 1 << 30 // 1GB // The data file format version. const version = 2 // Represents a marker value to indicate that a file is a Bolt DB. const magic uint32 = 0xED0CDAED // IgnoreNoSync specifies whether the NoSync field of a DB is ignored when // syncing changes to a file. This is required as some operating systems, // such as OpenBSD, do not have a unified buffer cache (UBC) and writes // must be synchronized using the msync(2) syscall. const IgnoreNoSync = runtime.GOOS == "openbsd" // Default values if not set in a DB instance. const ( DefaultMaxBatchSize int = 1000 DefaultMaxBatchDelay = 10 * time.Millisecond DefaultAllocSize = 16 * 1024 * 1024 ) // default page size for db is set to the OS page size. var defaultPageSize = os.Getpagesize() // DB represents a collection of buckets persisted to a file on disk. // All data access is performed through transactions which can be obtained through the DB. // All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called. type DB struct { // When enabled, the database will perform a Check() after every commit. // A panic is issued if the database is in an inconsistent state. This // flag has a large performance impact so it should only be used for // debugging purposes. StrictMode bool // Setting the NoSync flag will cause the database to skip fsync() // calls after each commit. This can be useful when bulk loading data // into a database and you can restart the bulk load in the event of // a system failure or database corruption. Do not set this flag for // normal use. // // If the package global IgnoreNoSync constant is true, this value is // ignored. See the comment on that constant for more details. // // THIS IS UNSAFE. PLEASE USE WITH CAUTION. NoSync bool // When true, skips the truncate call when growing the database. // Setting this to true is only safe on non-ext3/ext4 systems. // Skipping truncation avoids preallocation of hard drive space and // bypasses a truncate() and fsync() syscall on remapping. // // https://github.com/boltdb/bolt/issues/284 NoGrowSync bool // If you want to read the entire database fast, you can set MmapFlag to // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead. MmapFlags int // MaxBatchSize is the maximum size of a batch. Default value is // copied from DefaultMaxBatchSize in Open. // // If <=0, disables batching. // // Do not change concurrently with calls to Batch. MaxBatchSize int // MaxBatchDelay is the maximum delay before a batch starts. // Default value is copied from DefaultMaxBatchDelay in Open. // // If <=0, effectively disables batching. // // Do not change concurrently with calls to Batch. MaxBatchDelay time.Duration // AllocSize is the amount of space allocated when the database // needs to create new pages. This is done to amortize the cost // of truncate() and fsync() when growing the data file. AllocSize int path string file *os.File lockfile *os.File // windows only dataref []byte // mmap'ed readonly, write throws SEGV data *[maxMapSize]byte datasz int filesz int // current on disk file size meta0 *meta meta1 *meta pageSize int opened bool rwtx *Tx txs []*Tx freelist *freelist stats Stats pagePool sync.Pool batchMu sync.Mutex batch *batch rwlock sync.Mutex // Allows only one writer at a time. metalock sync.Mutex // Protects meta page access. mmaplock sync.RWMutex // Protects mmap access during remapping. statlock sync.RWMutex // Protects stats access. ops struct { writeAt func(b []byte, off int64) (n int, err error) } // Read only mode. // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately. readOnly bool } // Path returns the path to currently open database file. func (db *DB) Path() string { return db.path } // GoString returns the Go string representation of the database. func (db *DB) GoString() string { return fmt.Sprintf("bolt.DB{path:%q}", db.path) } // String returns the string representation of the database. func (db *DB) String() string { return fmt.Sprintf("DB<%q>", db.path) } // Open creates and opens a database at the given path. // If the file does not exist then it will be created automatically. // Passing in nil options will cause Bolt to open the database with the default options. func Open(path string, mode os.FileMode, options *Options) (*DB, error) { var db = &DB{opened: true} // Set default options if no options are provided. if options == nil { options = DefaultOptions } db.NoGrowSync = options.NoGrowSync db.MmapFlags = options.MmapFlags // Set default values for later DB operations. db.MaxBatchSize = DefaultMaxBatchSize db.MaxBatchDelay = DefaultMaxBatchDelay db.AllocSize = DefaultAllocSize flag := os.O_RDWR if options.ReadOnly { flag = os.O_RDONLY db.readOnly = true } // Open data file and separate sync handler for metadata writes. db.path = path var err error if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil { _ = db.close() return nil, err } // Lock file so that other processes using Bolt in read-write mode cannot // use the database at the same time. This would cause corruption since // the two processes would write meta pages and free pages separately. // The database file is locked exclusively (only one process can grab the lock) // if !options.ReadOnly. // The database file is locked using the shared lock (more than one process may // hold a lock at the same time) otherwise (options.ReadOnly is set). if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil { _ = db.close() return nil, err } // Default values for test hooks db.ops.writeAt = db.file.WriteAt // Initialize the database if it doesn't exist. if info, err := db.file.Stat(); err != nil { return nil, err } else if info.Size() == 0 { // Initialize new files with meta pages. if err := db.init(); err != nil { return nil, err } } else { // Read the first meta page to determine the page size. var buf [0x1000]byte if _, err := db.file.ReadAt(buf[:], 0); err == nil { m := db.pageInBuffer(buf[:], 0).meta() if err := m.validate(); err != nil { // If we can't read the page size, we can assume it's the same // as the OS -- since that's how the page size was chosen in the // first place. // // If the first page is invalid and this OS uses a different // page size than what the database was created with then we // are out of luck and cannot access the database. db.pageSize = os.Getpagesize() } else { db.pageSize = int(m.pageSize) } } } // Initialize page pool. db.pagePool = sync.Pool{ New: func() interface{} { return make([]byte, db.pageSize) }, } // Memory map the data file. if err := db.mmap(options.InitialMmapSize); err != nil { _ = db.close() return nil, err } // Read in the freelist. db.freelist = newFreelist() db.freelist.read(db.page(db.meta().freelist)) // Mark the database as opened and return. return db, nil } // mmap opens the underlying memory-mapped file and initializes the meta references. // minsz is the minimum size that the new mmap can be. func (db *DB) mmap(minsz int) error { db.mmaplock.Lock() defer db.mmaplock.Unlock() info, err := db.file.Stat() if err != nil { return fmt.Errorf("mmap stat error: %s", err) } else if int(info.Size()) < db.pageSize*2 { return fmt.Errorf("file size too small") } // Ensure the size is at least the minimum size. var size = int(info.Size()) if size < minsz { size = minsz } size, err = db.mmapSize(size) if err != nil { return err } // Dereference all mmap references before unmapping. if db.rwtx != nil { db.rwtx.root.dereference() } // Unmap existing data before continuing. if err := db.munmap(); err != nil { return err } // Memory-map the data file as a byte slice. if err := mmap(db, size); err != nil { return err } // Save references to the meta pages. db.meta0 = db.page(0).meta() db.meta1 = db.page(1).meta() // Validate the meta pages. We only return an error if both meta pages fail // validation, since meta0 failing validation means that it wasn't saved // properly -- but we can recover using meta1. And vice-versa. err0 := db.meta0.validate() err1 := db.meta1.validate() if err0 != nil && err1 != nil { return err0 } return nil } // munmap unmaps the data file from memory. func (db *DB) munmap() error { if err := munmap(db); err != nil { return fmt.Errorf("unmap error: " + err.Error()) } return nil } // mmapSize determines the appropriate size for the mmap given the current size // of the database. The minimum size is 32KB and doubles until it reaches 1GB. // Returns an error if the new mmap size is greater than the max allowed. func (db *DB) mmapSize(size int) (int, error) { // Double the size from 32KB until 1GB. for i := uint(15); i <= 30; i++ { if size <= 1<<i { return 1 << i, nil } } // Verify the requested size is not above the maximum allowed. if size > maxMapSize { return 0, fmt.Errorf("mmap too large") } // If larger than 1GB then grow by 1GB at a time. sz := int64(size) if remainder := sz % int64(maxMmapStep); remainder > 0 { sz += int64(maxMmapStep) - remainder } // Ensure that the mmap size is a multiple of the page size. // This should always be true since we're incrementing in MBs. pageSize := int64(db.pageSize) if (sz % pageSize) != 0 { sz = ((sz / pageSize) + 1) * pageSize } // If we've exceeded the max size then only grow up to the max size. if sz > maxMapSize { sz = maxMapSize } return int(sz), nil } // init creates a new database file and initializes its meta pages. func (db *DB) init() error { // Set the page size to the OS page size. db.pageSize = os.Getpagesize() // Create two meta pages on a buffer. buf := make([]byte, db.pageSize*4) for i := 0; i < 2; i++ { p := db.pageInBuffer(buf[:], pgid(i)) p.id = pgid(i) p.flags = metaPageFlag // Initialize the meta page. m := p.meta() m.magic = magic m.version = version m.pageSize = uint32(db.pageSize) m.freelist = 2 m.root = bucket{root: 3} m.pgid = 4 m.txid = txid(i) m.checksum = m.sum64() } // Write an empty freelist at page 3. p := db.pageInBuffer(buf[:], pgid(2)) p.id = pgid(2) p.flags = freelistPageFlag p.count = 0 // Write an empty leaf page at page 4. p = db.pageInBuffer(buf[:], pgid(3)) p.id = pgid(3) p.flags = leafPageFlag p.count = 0 // Write the buffer to our data file. if _, err := db.ops.writeAt(buf, 0); err != nil { return err } if err := fdatasync(db); err != nil { return err } return nil } // Close releases all database resources. // All transactions must be closed before closing the database. func (db *DB) Close() error { db.rwlock.Lock() defer db.rwlock.Unlock() db.metalock.Lock() defer db.metalock.Unlock() db.mmaplock.RLock() defer db.mmaplock.RUnlock() return db.close() } func (db *DB) close() error { if !db.opened { return nil } db.opened = false db.freelist = nil // Clear ops. db.ops.writeAt = nil // Close the mmap. if err := db.munmap(); err != nil { return err } // Close file handles. if db.file != nil { // No need to unlock read-only file. if !db.readOnly { // Unlock the file. if err := funlock(db); err != nil { log.Printf("bolt.Close(): funlock error: %s", err) } } // Close the file descriptor. if err := db.file.Close(); err != nil { return fmt.Errorf("db file close: %s", err) } db.file = nil } db.path = "" return nil } // Begin starts a new transaction. // Multiple read-only transactions can be used concurrently but only one // write transaction can be used at a time. Starting multiple write transactions // will cause the calls to block and be serialized until the current write // transaction finishes. // // Transactions should not be dependent on one another. Opening a read // transaction and a write transaction in the same goroutine can cause the // writer to deadlock because the database periodically needs to re-mmap itself // as it grows and it cannot do that while a read transaction is open. // // If a long running read transaction (for example, a snapshot transaction) is // needed, you might want to set DB.InitialMmapSize to a large enough value // to avoid potential blocking of write transaction. // // IMPORTANT: You must close read-only transactions after you are finished or // else the database will not reclaim old pages. func (db *DB) Begin(writable bool) (*Tx, error) { if writable { return db.beginRWTx() } return db.beginTx() } func (db *DB) beginTx() (*Tx, error) { // Lock the meta pages while we initialize the transaction. We obtain // the meta lock before the mmap lock because that's the order that the // write transaction will obtain them. db.metalock.Lock() // Obtain a read-only lock on the mmap. When the mmap is remapped it will // obtain a write lock so all transactions must finish before it can be // remapped. db.mmaplock.RLock() // Exit if the database is not open yet. if !db.opened { db.mmaplock.RUnlock() db.metalock.Unlock() return nil, ErrDatabaseNotOpen } // Create a transaction associated with the database. t := &Tx{} t.init(db) // Keep track of transaction until it closes. db.txs = append(db.txs, t) n := len(db.txs) // Unlock the meta pages. db.metalock.Unlock() // Update the transaction stats. db.statlock.Lock() db.stats.TxN++ db.stats.OpenTxN = n db.statlock.Unlock() return t, nil } func (db *DB) beginRWTx() (*Tx, error) { // If the database was opened with Options.ReadOnly, return an error. if db.readOnly { return nil, ErrDatabaseReadOnly } // Obtain writer lock. This is released by the transaction when it closes. // This enforces only one writer transaction at a time. db.rwlock.Lock() // Once we have the writer lock then we can lock the meta pages so that // we can set up the transaction. db.metalock.Lock() defer db.metalock.Unlock() // Exit if the database is not open yet. if !db.opened { db.rwlock.Unlock() return nil, ErrDatabaseNotOpen } // Create a transaction associated with the database. t := &Tx{writable: true} t.init(db) db.rwtx = t // Free any pages associated with closed read-only transactions. var minid txid = 0xFFFFFFFFFFFFFFFF for _, t := range db.txs { if t.meta.txid < minid { minid = t.meta.txid } } if minid > 0 { db.freelist.release(minid - 1) } return t, nil } // removeTx removes a transaction from the database. func (db *DB) removeTx(tx *Tx) { // Release the read lock on the mmap. db.mmaplock.RUnlock() // Use the meta lock to restrict access to the DB object. db.metalock.Lock() // Remove the transaction. for i, t := range db.txs { if t == tx { last := len(db.txs) - 1 db.txs[i] = db.txs[last] db.txs[last] = nil db.txs = db.txs[:last] break } } n := len(db.txs) // Unlock the meta pages. db.metalock.Unlock() // Merge statistics. db.statlock.Lock() db.stats.OpenTxN = n db.stats.TxStats.add(&tx.stats) db.statlock.Unlock() } // Update executes a function within the context of a read-write managed transaction. // If no error is returned from the function then the transaction is committed. // If an error is returned then the entire transaction is rolled back. // Any error that is returned from the function or returned from the commit is // returned from the Update() method. // // Attempting to manually commit or rollback within the function will cause a panic. func (db *DB) Update(fn func(*Tx) error) error { t, err := db.Begin(true) if err != nil { return err } // Make sure the transaction rolls back in the event of a panic. defer func() { if t.db != nil { t.rollback() } }() // Mark as a managed tx so that the inner function cannot manually commit. t.managed = true // If an error is returned from the function then rollback and return error. err = fn(t) t.managed = false if err != nil { _ = t.Rollback() return err } return t.Commit() } // View executes a function within the context of a managed read-only transaction. // Any error that is returned from the function is returned from the View() method. // // Attempting to manually rollback within the function will cause a panic. func (db *DB) View(fn func(*Tx) error) error { t, err := db.Begin(false) if err != nil { return err } // Make sure the transaction rolls back in the event of a panic. defer func() { if t.db != nil { t.rollback() } }() // Mark as a managed tx so that the inner function cannot manually rollback. t.managed = true // If an error is returned from the function then pass it through. err = fn(t) t.managed = false if err != nil { _ = t.Rollback() return err } if err := t.Rollback(); err != nil { return err } return nil } // Batch calls fn as part of a batch. It behaves similar to Update, // except: // // 1. concurrent Batch calls can be combined into a single Bolt // transaction. // // 2. the function passed to Batch may be called multiple times, // regardless of whether it returns error or not. // // This means that Batch function side effects must be idempotent and // take permanent effect only after a successful return is seen in // caller. // // The maximum batch size and delay can be adjusted with DB.MaxBatchSize // and DB.MaxBatchDelay, respectively. // // Batch is only useful when there are multiple goroutines calling it. func (db *DB) Batch(fn func(*Tx) error) error { errCh := make(chan error, 1) db.batchMu.Lock() if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) { // There is no existing batch, or the existing batch is full; start a new one. db.batch = &batch{ db: db, } db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger) } db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh}) if len(db.batch.calls) >= db.MaxBatchSize { // wake up batch, it's ready to run go db.batch.trigger() } db.batchMu.Unlock() err := <-errCh if err == trySolo { err = db.Update(fn) } return err } type call struct { fn func(*Tx) error err chan<- error } type batch struct { db *DB timer *time.Timer start sync.Once calls []call } // trigger runs the batch if it hasn't already been run. func (b *batch) trigger() { b.start.Do(b.run) } // run performs the transactions in the batch and communicates results // back to DB.Batch. func (b *batch) run() { b.db.batchMu.Lock() b.timer.Stop() // Make sure no new work is added to this batch, but don't break // other batches. if b.db.batch == b { b.db.batch = nil } b.db.batchMu.Unlock() retry: for len(b.calls) > 0 { var failIdx = -1 err := b.db.Update(func(tx *Tx) error { for i, c := range b.calls { if err := safelyCall(c.fn, tx); err != nil { failIdx = i return err } } return nil }) if failIdx >= 0 { // take the failing transaction out of the batch. it's // safe to shorten b.calls here because db.batch no longer // points to us, and we hold the mutex anyway. c := b.calls[failIdx] b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1] // tell the submitter re-run it solo, continue with the rest of the batch c.err <- trySolo continue retry } // pass success, or bolt internal errors, to all callers for _, c := range b.calls { if c.err != nil { c.err <- err } } break retry } } // trySolo is a special sentinel error value used for signaling that a // transaction function should be re-run. It should never be seen by // callers. var trySolo = errors.New("batch function returned an error and should be re-run solo") type panicked struct { reason interface{} } func (p panicked) Error() string { if err, ok := p.reason.(error); ok { return err.Error() } return fmt.Sprintf("panic: %v", p.reason) } func safelyCall(fn func(*Tx) error, tx *Tx) (err error) { defer func() { if p := recover(); p != nil { err = panicked{p} } }() return fn(tx) } // Sync executes fdatasync() against the database file handle. // // This is not necessary under normal operation, however, if you use NoSync // then it allows you to force the database file to sync against the disk. func (db *DB) Sync() error { return fdatasync(db) } // Stats retrieves ongoing performance stats for the database. // This is only updated when a transaction closes. func (db *DB) Stats() Stats { db.statlock.RLock() defer db.statlock.RUnlock() return db.stats } // This is for internal access to the raw data bytes from the C cursor, use // carefully, or not at all. func (db *DB) Info() *Info { return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize} } // page retrieves a page reference from the mmap based on the current page size. func (db *DB) page(id pgid) *page { pos := id * pgid(db.pageSize) return (*page)(unsafe.Pointer(&db.data[pos])) } // pageInBuffer retrieves a page reference from a given byte array based on the current page size. func (db *DB) pageInBuffer(b []byte, id pgid) *page { return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)])) } // meta retrieves the current meta page reference. func (db *DB) meta() *meta { // We have to return the meta with the highest txid which doesn't fail // validation. Otherwise, we can cause errors when in fact the database is // in a consistent state. metaA is the one with the higher txid. metaA := db.meta0 metaB := db.meta1 if db.meta1.txid > db.meta0.txid { metaA = db.meta1 metaB = db.meta0 } // Use higher meta page if valid. Otherwise fallback to previous, if valid. if err := metaA.validate(); err == nil { return metaA } else if err := metaB.validate(); err == nil { return metaB } // This should never be reached, because both meta1 and meta0 were validated // on mmap() and we do fsync() on every write. panic("bolt.DB.meta(): invalid meta pages") } // allocate returns a contiguous block of memory starting at a given page. func (db *DB) allocate(count int) (*page, error) { // Allocate a temporary buffer for the page. var buf []byte if count == 1 { buf = db.pagePool.Get().([]byte) } else { buf = make([]byte, count*db.pageSize) } p := (*page)(unsafe.Pointer(&buf[0])) p.overflow = uint32(count - 1) // Use pages from the freelist if they are available. if p.id = db.freelist.allocate(count); p.id != 0 { return p, nil } // Resize mmap() if we're at the end. p.id = db.rwtx.meta.pgid var minsz = int((p.id+pgid(count))+1) * db.pageSize if minsz >= db.datasz { if err := db.mmap(minsz); err != nil { return nil, fmt.Errorf("mmap allocate error: %s", err) } } // Move the page id high water mark. db.rwtx.meta.pgid += pgid(count) return p, nil } // grow grows the size of the database to the given sz. func (db *DB) grow(sz int) error { // Ignore if the new size is less than available file size. if sz <= db.filesz { return nil } // If the data is smaller than the alloc size then only allocate what's needed. // Once it goes over the allocation size then allocate in chunks. if db.datasz < db.AllocSize { sz = db.datasz } else { sz += db.AllocSize } // Truncate and fsync to ensure file size metadata is flushed. // https://github.com/boltdb/bolt/issues/284 if !db.NoGrowSync && !db.readOnly { if runtime.GOOS != "windows" { if err := db.file.Truncate(int64(sz)); err != nil { return fmt.Errorf("file resize error: %s", err) } } if err := db.file.Sync(); err != nil { return fmt.Errorf("file sync error: %s", err) } } db.filesz = sz return nil } func (db *DB) IsReadOnly() bool { return db.readOnly } // Options represents the options that can be set when opening a database. type Options struct { // Timeout is the amount of time to wait to obtain a file lock. // When set to zero it will wait indefinitely. This option is only // available on Darwin and Linux. Timeout time.Duration // Sets the DB.NoGrowSync flag before memory mapping the file. NoGrowSync bool // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to // grab a shared lock (UNIX). ReadOnly bool // Sets the DB.MmapFlags flag before memory mapping the file. MmapFlags int // InitialMmapSize is the initial mmap size of the database // in bytes. Read transactions won't block write transaction // if the InitialMmapSize is large enough to hold database mmap // size. (See DB.Begin for more information) // // If <=0, the initial map size is 0. // If initialMmapSize is smaller than the previous database size, // it takes no effect. InitialMmapSize int } // DefaultOptions represent the options used if nil options are passed into Open(). // No timeout is used which will cause Bolt to wait indefinitely for a lock. var DefaultOptions = &Options{ Timeout: 0, NoGrowSync: false, } // Stats represents statistics about the database. type Stats struct { // Freelist stats FreePageN int // total number of free pages on the freelist PendingPageN int // total number of pending pages on the freelist FreeAlloc int // total bytes allocated in free pages FreelistInuse int // total bytes used by the freelist // Transaction stats TxN int // total number of started read transactions OpenTxN int // number of currently open read transactions TxStats TxStats // global, ongoing stats. } // Sub calculates and returns the difference between two sets of database stats. // This is useful when obtaining stats at two different points and time and // you need the performance counters that occurred within that time span. func (s *Stats) Sub(other *Stats) Stats { if other == nil { return *s } var diff Stats diff.FreePageN = s.FreePageN diff.PendingPageN = s.PendingPageN diff.FreeAlloc = s.FreeAlloc diff.FreelistInuse = s.FreelistInuse diff.TxN = s.TxN - other.TxN diff.TxStats = s.TxStats.Sub(&other.TxStats) return diff } func (s *Stats) add(other *Stats) { s.TxStats.add(&other.TxStats) } type Info struct { Data uintptr PageSize int } type meta struct { magic uint32 version uint32 pageSize uint32 flags uint32 root bucket freelist pgid pgid pgid txid txid checksum uint64 } // validate checks the marker bytes and version of the meta page to ensure it matches this binary. func (m *meta) validate() error { if m.magic != magic { return ErrInvalid } else if m.version != version { return ErrVersionMismatch } else if m.checksum != 0 && m.checksum != m.sum64() { return ErrChecksum } return nil } // copy copies one meta object to another. func (m *meta) copy(dest *meta) { *dest = *m } // write writes the meta onto a page. func (m *meta) write(p *page) { if m.root.root >= m.pgid { panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid)) } else if m.freelist >= m.pgid { panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid)) } // Page id is either going to be 0 or 1 which we can determine by the transaction ID. p.id = pgid(m.txid % 2) p.flags |= metaPageFlag // Calculate the checksum. m.checksum = m.sum64() m.copy(p.meta()) } // generates the checksum for the meta. func (m *meta) sum64() uint64 { var h = fnv.New64a() _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:]) return h.Sum64() } // _assert will panic with a given formatted message if the given condition is false. func _assert(condition bool, msg string, v ...interface{}) { if !condition { panic(fmt.Sprintf("assertion failed: "+msg, v...)) } } func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) } func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) } func printstack() { stack := strings.Join(strings.Split(string(debug.Stack()), "\n")[2:], "\n") fmt.Fprintln(os.Stderr, stack) }
dep/vendor/github.com/boltdb/bolt/db.go/0
{ "file_path": "dep/vendor/github.com/boltdb/bolt/db.go", "repo_id": "dep", "token_count": 9692 }
40
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Package proto converts data structures to and from the wire format of protocol buffers. It works in concert with the Go source code generated for .proto files by the protocol compiler. A summary of the properties of the protocol buffer interface for a protocol buffer variable v: - Names are turned from camel_case to CamelCase for export. - There are no methods on v to set fields; just treat them as structure fields. - There are getters that return a field's value if set, and return the field's default value if unset. The getters work even if the receiver is a nil message. - The zero value for a struct is its correct initialization state. All desired fields must be set before marshaling. - A Reset() method will restore a protobuf struct to its zero state. - Non-repeated fields are pointers to the values; nil means unset. That is, optional or required field int32 f becomes F *int32. - Repeated fields are slices. - Helper functions are available to aid the setting of fields. msg.Foo = proto.String("hello") // set field - Constants are defined to hold the default values of all fields that have them. They have the form Default_StructName_FieldName. Because the getter methods handle defaulted values, direct use of these constants should be rare. - Enums are given type names and maps from names to values. Enum values are prefixed by the enclosing message's name, or by the enum's type name if it is a top-level enum. Enum types have a String method, and a Enum method to assist in message construction. - Nested messages, groups and enums have type names prefixed with the name of the surrounding message type. - Extensions are given descriptor names that start with E_, followed by an underscore-delimited list of the nested messages that contain it (if any) followed by the CamelCased name of the extension field itself. HasExtension, ClearExtension, GetExtension and SetExtension are functions for manipulating extensions. - Oneof field sets are given a single field in their message, with distinguished wrapper types for each possible field value. - Marshal and Unmarshal are functions to encode and decode the wire format. When the .proto file specifies `syntax="proto3"`, there are some differences: - Non-repeated fields of non-message type are values instead of pointers. - Enum types do not get an Enum method. The simplest way to describe this is to see an example. Given file test.proto, containing package example; enum FOO { X = 17; } message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } oneof union { int32 number = 6; string name = 7; } } The resulting file, test.pb.go, is: package example import proto "github.com/golang/protobuf/proto" import math "math" type FOO int32 const ( FOO_X FOO = 17 ) var FOO_name = map[int32]string{ 17: "X", } var FOO_value = map[string]int32{ "X": 17, } func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return proto.EnumName(FOO_name, int32(x)) } func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data) if err != nil { return err } *x = FOO(value) return nil } type Test struct { Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` // Types that are valid to be assigned to Union: // *Test_Number // *Test_Name Union isTest_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Test) Reset() { *m = Test{} } func (m *Test) String() string { return proto.CompactTextString(m) } func (*Test) ProtoMessage() {} type isTest_Union interface { isTest_Union() } type Test_Number struct { Number int32 `protobuf:"varint,6,opt,name=number"` } type Test_Name struct { Name string `protobuf:"bytes,7,opt,name=name"` } func (*Test_Number) isTest_Union() {} func (*Test_Name) isTest_Union() {} func (m *Test) GetUnion() isTest_Union { if m != nil { return m.Union } return nil } const Default_Test_Type int32 = 77 func (m *Test) GetLabel() string { if m != nil && m.Label != nil { return *m.Label } return "" } func (m *Test) GetType() int32 { if m != nil && m.Type != nil { return *m.Type } return Default_Test_Type } func (m *Test) GetOptionalgroup() *Test_OptionalGroup { if m != nil { return m.Optionalgroup } return nil } type Test_OptionalGroup struct { RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` } func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } func (m *Test_OptionalGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } func (m *Test) GetNumber() int32 { if x, ok := m.GetUnion().(*Test_Number); ok { return x.Number } return 0 } func (m *Test) GetName() string { if x, ok := m.GetUnion().(*Test_Name); ok { return x.Name } return "" } func init() { proto.RegisterEnum("example.FOO", FOO_name, FOO_value) } To create and play with a Test object: package main import ( "log" "github.com/golang/protobuf/proto" pb "./example.pb" ) func main() { test := &pb.Test{ Label: proto.String("hello"), Type: proto.Int32(17), Reps: []int64{1, 2, 3}, Optionalgroup: &pb.Test_OptionalGroup{ RequiredField: proto.String("good bye"), }, Union: &pb.Test_Name{"fred"}, } data, err := proto.Marshal(test) if err != nil { log.Fatal("marshaling error: ", err) } newTest := &pb.Test{} err = proto.Unmarshal(data, newTest) if err != nil { log.Fatal("unmarshaling error: ", err) } // Now test and newTest contain the same data. if test.GetLabel() != newTest.GetLabel() { log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } // Use a type switch to determine which oneof was set. switch u := test.Union.(type) { case *pb.Test_Number: // u.Number contains the number. case *pb.Test_Name: // u.Name contains the string. } // etc. } */ package proto import ( "encoding/json" "fmt" "log" "reflect" "sort" "strconv" "sync" ) // Message is implemented by generated protocol buffer messages. type Message interface { Reset() String() string ProtoMessage() } // Stats records allocation details about the protocol buffer encoders // and decoders. Useful for tuning the library itself. type Stats struct { Emalloc uint64 // mallocs in encode Dmalloc uint64 // mallocs in decode Encode uint64 // number of encodes Decode uint64 // number of decodes Chit uint64 // number of cache hits Cmiss uint64 // number of cache misses Size uint64 // number of sizes } // Set to true to enable stats collection. const collectStats = false var stats Stats // GetStats returns a copy of the global Stats structure. func GetStats() Stats { return stats } // A Buffer is a buffer manager for marshaling and unmarshaling // protocol buffers. It may be reused between invocations to // reduce memory usage. It is not necessary to use a Buffer; // the global functions Marshal and Unmarshal create a // temporary Buffer and are fine for most applications. type Buffer struct { buf []byte // encode/decode byte stream index int // read point // pools of basic types to amortize allocation. bools []bool uint32s []uint32 uint64s []uint64 // extra pools, only used with pointer_reflect.go int32s []int32 int64s []int64 float32s []float32 float64s []float64 } // NewBuffer allocates a new Buffer and initializes its internal data to // the contents of the argument slice. func NewBuffer(e []byte) *Buffer { return &Buffer{buf: e} } // Reset resets the Buffer, ready for marshaling a new protocol buffer. func (p *Buffer) Reset() { p.buf = p.buf[0:0] // for reading/writing p.index = 0 // for reading } // SetBuf replaces the internal buffer with the slice, // ready for unmarshaling the contents of the slice. func (p *Buffer) SetBuf(s []byte) { p.buf = s p.index = 0 } // Bytes returns the contents of the Buffer. func (p *Buffer) Bytes() []byte { return p.buf } /* * Helper routines for simplifying the creation of optional fields of basic type. */ // Bool is a helper routine that allocates a new bool value // to store v and returns a pointer to it. func Bool(v bool) *bool { return &v } // Int32 is a helper routine that allocates a new int32 value // to store v and returns a pointer to it. func Int32(v int32) *int32 { return &v } // Int is a helper routine that allocates a new int32 value // to store v and returns a pointer to it, but unlike Int32 // its argument value is an int. func Int(v int) *int32 { p := new(int32) *p = int32(v) return p } // Int64 is a helper routine that allocates a new int64 value // to store v and returns a pointer to it. func Int64(v int64) *int64 { return &v } // Float32 is a helper routine that allocates a new float32 value // to store v and returns a pointer to it. func Float32(v float32) *float32 { return &v } // Float64 is a helper routine that allocates a new float64 value // to store v and returns a pointer to it. func Float64(v float64) *float64 { return &v } // Uint32 is a helper routine that allocates a new uint32 value // to store v and returns a pointer to it. func Uint32(v uint32) *uint32 { return &v } // Uint64 is a helper routine that allocates a new uint64 value // to store v and returns a pointer to it. func Uint64(v uint64) *uint64 { return &v } // String is a helper routine that allocates a new string value // to store v and returns a pointer to it. func String(v string) *string { return &v } // EnumName is a helper function to simplify printing protocol buffer enums // by name. Given an enum map and a value, it returns a useful string. func EnumName(m map[int32]string, v int32) string { s, ok := m[v] if ok { return s } return strconv.Itoa(int(v)) } // UnmarshalJSONEnum is a helper function to simplify recovering enum int values // from their JSON-encoded representation. Given a map from the enum's symbolic // names to its int values, and a byte buffer containing the JSON-encoded // value, it returns an int32 that can be cast to the enum type by the caller. // // The function can deal with both JSON representations, numeric and symbolic. func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { if data[0] == '"' { // New style: enums are strings. var repr string if err := json.Unmarshal(data, &repr); err != nil { return -1, err } val, ok := m[repr] if !ok { return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) } return val, nil } // Old style: enums are ints. var val int32 if err := json.Unmarshal(data, &val); err != nil { return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) } return val, nil } // DebugPrint dumps the encoded data in b in a debugging format with a header // including the string s. Used in testing but made available for general debugging. func (p *Buffer) DebugPrint(s string, b []byte) { var u uint64 obuf := p.buf index := p.index p.buf = b p.index = 0 depth := 0 fmt.Printf("\n--- %s ---\n", s) out: for { for i := 0; i < depth; i++ { fmt.Print(" ") } index := p.index if index == len(p.buf) { break } op, err := p.DecodeVarint() if err != nil { fmt.Printf("%3d: fetching op err %v\n", index, err) break out } tag := op >> 3 wire := op & 7 switch wire { default: fmt.Printf("%3d: t=%3d unknown wire=%d\n", index, tag, wire) break out case WireBytes: var r []byte r, err = p.DecodeRawBytes(false) if err != nil { break out } fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) if len(r) <= 6 { for i := 0; i < len(r); i++ { fmt.Printf(" %.2x", r[i]) } } else { for i := 0; i < 3; i++ { fmt.Printf(" %.2x", r[i]) } fmt.Printf(" ..") for i := len(r) - 3; i < len(r); i++ { fmt.Printf(" %.2x", r[i]) } } fmt.Printf("\n") case WireFixed32: u, err = p.DecodeFixed32() if err != nil { fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) case WireFixed64: u, err = p.DecodeFixed64() if err != nil { fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) case WireVarint: u, err = p.DecodeVarint() if err != nil { fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) case WireStartGroup: fmt.Printf("%3d: t=%3d start\n", index, tag) depth++ case WireEndGroup: depth-- fmt.Printf("%3d: t=%3d end\n", index, tag) } } if depth != 0 { fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) } fmt.Printf("\n") p.buf = obuf p.index = index } // SetDefaults sets unset protocol buffer fields to their default values. // It only modifies fields that are both unset and have defined defaults. // It recursively sets default values in any non-nil sub-messages. func SetDefaults(pb Message) { setDefaults(reflect.ValueOf(pb), true, false) } // v is a pointer to a struct. func setDefaults(v reflect.Value, recur, zeros bool) { v = v.Elem() defaultMu.RLock() dm, ok := defaults[v.Type()] defaultMu.RUnlock() if !ok { dm = buildDefaultMessage(v.Type()) defaultMu.Lock() defaults[v.Type()] = dm defaultMu.Unlock() } for _, sf := range dm.scalars { f := v.Field(sf.index) if !f.IsNil() { // field already set continue } dv := sf.value if dv == nil && !zeros { // no explicit default, and don't want to set zeros continue } fptr := f.Addr().Interface() // **T // TODO: Consider batching the allocations we do here. switch sf.kind { case reflect.Bool: b := new(bool) if dv != nil { *b = dv.(bool) } *(fptr.(**bool)) = b case reflect.Float32: f := new(float32) if dv != nil { *f = dv.(float32) } *(fptr.(**float32)) = f case reflect.Float64: f := new(float64) if dv != nil { *f = dv.(float64) } *(fptr.(**float64)) = f case reflect.Int32: // might be an enum if ft := f.Type(); ft != int32PtrType { // enum f.Set(reflect.New(ft.Elem())) if dv != nil { f.Elem().SetInt(int64(dv.(int32))) } } else { // int32 field i := new(int32) if dv != nil { *i = dv.(int32) } *(fptr.(**int32)) = i } case reflect.Int64: i := new(int64) if dv != nil { *i = dv.(int64) } *(fptr.(**int64)) = i case reflect.String: s := new(string) if dv != nil { *s = dv.(string) } *(fptr.(**string)) = s case reflect.Uint8: // exceptional case: []byte var b []byte if dv != nil { db := dv.([]byte) b = make([]byte, len(db)) copy(b, db) } else { b = []byte{} } *(fptr.(*[]byte)) = b case reflect.Uint32: u := new(uint32) if dv != nil { *u = dv.(uint32) } *(fptr.(**uint32)) = u case reflect.Uint64: u := new(uint64) if dv != nil { *u = dv.(uint64) } *(fptr.(**uint64)) = u default: log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) } } for _, ni := range dm.nested { f := v.Field(ni) // f is *T or []*T or map[T]*T switch f.Kind() { case reflect.Ptr: if f.IsNil() { continue } setDefaults(f, recur, zeros) case reflect.Slice: for i := 0; i < f.Len(); i++ { e := f.Index(i) if e.IsNil() { continue } setDefaults(e, recur, zeros) } case reflect.Map: for _, k := range f.MapKeys() { e := f.MapIndex(k) if e.IsNil() { continue } setDefaults(e, recur, zeros) } } } } var ( // defaults maps a protocol buffer struct type to a slice of the fields, // with its scalar fields set to their proto-declared non-zero default values. defaultMu sync.RWMutex defaults = make(map[reflect.Type]defaultMessage) int32PtrType = reflect.TypeOf((*int32)(nil)) ) // defaultMessage represents information about the default values of a message. type defaultMessage struct { scalars []scalarField nested []int // struct field index of nested messages } type scalarField struct { index int // struct field index kind reflect.Kind // element type (the T in *T or []T) value interface{} // the proto-declared default value, or nil } // t is a struct type. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { sprop := GetProperties(t) for _, prop := range sprop.Prop { fi, ok := sprop.decoderTags.get(prop.Tag) if !ok { // XXX_unrecognized continue } ft := t.Field(fi).Type sf, nested, err := fieldDefault(ft, prop) switch { case err != nil: log.Print(err) case nested: dm.nested = append(dm.nested, fi) case sf != nil: sf.index = fi dm.scalars = append(dm.scalars, *sf) } } return dm } // fieldDefault returns the scalarField for field type ft. // sf will be nil if the field can not have a default. // nestedMessage will be true if this is a nested message. // Note that sf.index is not set on return. func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { var canHaveDefault bool switch ft.Kind() { case reflect.Ptr: if ft.Elem().Kind() == reflect.Struct { nestedMessage = true } else { canHaveDefault = true // proto2 scalar field } case reflect.Slice: switch ft.Elem().Kind() { case reflect.Ptr: nestedMessage = true // repeated message case reflect.Uint8: canHaveDefault = true // bytes field } case reflect.Map: if ft.Elem().Kind() == reflect.Ptr { nestedMessage = true // map with message values } } if !canHaveDefault { if nestedMessage { return nil, true, nil } return nil, false, nil } // We now know that ft is a pointer or slice. sf = &scalarField{kind: ft.Elem().Kind()} // scalar fields without defaults if !prop.HasDefault { return sf, false, nil } // a scalar field: either *T or []byte switch ft.Elem().Kind() { case reflect.Bool: x, err := strconv.ParseBool(prop.Default) if err != nil { return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) } sf.value = x case reflect.Float32: x, err := strconv.ParseFloat(prop.Default, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) } sf.value = float32(x) case reflect.Float64: x, err := strconv.ParseFloat(prop.Default, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) } sf.value = x case reflect.Int32: x, err := strconv.ParseInt(prop.Default, 10, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) } sf.value = int32(x) case reflect.Int64: x, err := strconv.ParseInt(prop.Default, 10, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) } sf.value = x case reflect.String: sf.value = prop.Default case reflect.Uint8: // []byte (not *uint8) sf.value = []byte(prop.Default) case reflect.Uint32: x, err := strconv.ParseUint(prop.Default, 10, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) } sf.value = uint32(x) case reflect.Uint64: x, err := strconv.ParseUint(prop.Default, 10, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) } sf.value = x default: return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) } return sf, false, nil } // Map fields may have key types of non-float scalars, strings and enums. // The easiest way to sort them in some deterministic order is to use fmt. // If this turns out to be inefficient we can always consider other options, // such as doing a Schwartzian transform. func mapKeys(vs []reflect.Value) sort.Interface { s := mapKeySorter{ vs: vs, // default Less function: textual comparison less: func(a, b reflect.Value) bool { return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface()) }, } // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps; // numeric keys are sorted numerically. if len(vs) == 0 { return s } switch vs[0].Kind() { case reflect.Int32, reflect.Int64: s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } case reflect.Uint32, reflect.Uint64: s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } } return s } type mapKeySorter struct { vs []reflect.Value less func(a, b reflect.Value) bool } func (s mapKeySorter) Len() int { return len(s.vs) } func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } func (s mapKeySorter) Less(i, j int) bool { return s.less(s.vs[i], s.vs[j]) } // isProto3Zero reports whether v is a zero proto3 value. func isProto3Zero(v reflect.Value) bool { switch v.Kind() { case reflect.Bool: return !v.Bool() case reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint32, reflect.Uint64: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.String: return v.String() == "" } return false } // ProtoPackageIsVersion2 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion2 = true // ProtoPackageIsVersion1 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion1 = true
dep/vendor/github.com/golang/protobuf/proto/lib.go/0
{ "file_path": "dep/vendor/github.com/golang/protobuf/proto/lib.go", "repo_id": "dep", "token_count": 9131 }
41
// Copyright 2017, The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package cmp import ( "fmt" "reflect" "strings" "unicode" "unicode/utf8" ) type ( // Path is a list of PathSteps describing the sequence of operations to get // from some root type to the current position in the value tree. // The first Path element is always an operation-less PathStep that exists // simply to identify the initial type. // // When traversing structs with embedded structs, the embedded struct will // always be accessed as a field before traversing the fields of the // embedded struct themselves. That is, an exported field from the // embedded struct will never be accessed directly from the parent struct. Path []PathStep // PathStep is a union-type for specific operations to traverse // a value's tree structure. Users of this package never need to implement // these types as values of this type will be returned by this package. PathStep interface { String() string Type() reflect.Type // Resulting type after performing the path step isPathStep() } // SliceIndex is an index operation on a slice or array at some index Key. SliceIndex interface { PathStep Key() int // May return -1 if in a split state // SplitKeys returns the indexes for indexing into slices in the // x and y values, respectively. These indexes may differ due to the // insertion or removal of an element in one of the slices, causing // all of the indexes to be shifted. If an index is -1, then that // indicates that the element does not exist in the associated slice. // // Key is guaranteed to return -1 if and only if the indexes returned // by SplitKeys are not the same. SplitKeys will never return -1 for // both indexes. SplitKeys() (x int, y int) isSliceIndex() } // MapIndex is an index operation on a map at some index Key. MapIndex interface { PathStep Key() reflect.Value isMapIndex() } // TypeAssertion represents a type assertion on an interface. TypeAssertion interface { PathStep isTypeAssertion() } // StructField represents a struct field access on a field called Name. StructField interface { PathStep Name() string Index() int isStructField() } // Indirect represents pointer indirection on the parent type. Indirect interface { PathStep isIndirect() } // Transform is a transformation from the parent type to the current type. Transform interface { PathStep Name() string Func() reflect.Value // Option returns the originally constructed Transformer option. // The == operator can be used to detect the exact option used. Option() Option isTransform() } ) func (pa *Path) push(s PathStep) { *pa = append(*pa, s) } func (pa *Path) pop() { *pa = (*pa)[:len(*pa)-1] } // Last returns the last PathStep in the Path. // If the path is empty, this returns a non-nil PathStep that reports a nil Type. func (pa Path) Last() PathStep { return pa.Index(-1) } // Index returns the ith step in the Path and supports negative indexing. // A negative index starts counting from the tail of the Path such that -1 // refers to the last step, -2 refers to the second-to-last step, and so on. // If index is invalid, this returns a non-nil PathStep that reports a nil Type. func (pa Path) Index(i int) PathStep { if i < 0 { i = len(pa) + i } if i < 0 || i >= len(pa) { return pathStep{} } return pa[i] } // String returns the simplified path to a node. // The simplified path only contains struct field accesses. // // For example: // MyMap.MySlices.MyField func (pa Path) String() string { var ss []string for _, s := range pa { if _, ok := s.(*structField); ok { ss = append(ss, s.String()) } } return strings.TrimPrefix(strings.Join(ss, ""), ".") } // GoString returns the path to a specific node using Go syntax. // // For example: // (*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField func (pa Path) GoString() string { var ssPre, ssPost []string var numIndirect int for i, s := range pa { var nextStep PathStep if i+1 < len(pa) { nextStep = pa[i+1] } switch s := s.(type) { case *indirect: numIndirect++ pPre, pPost := "(", ")" switch nextStep.(type) { case *indirect: continue // Next step is indirection, so let them batch up case *structField: numIndirect-- // Automatic indirection on struct fields case nil: pPre, pPost = "", "" // Last step; no need for parenthesis } if numIndirect > 0 { ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect)) ssPost = append(ssPost, pPost) } numIndirect = 0 continue case *transform: ssPre = append(ssPre, s.trans.name+"(") ssPost = append(ssPost, ")") continue case *typeAssertion: // As a special-case, elide type assertions on anonymous types // since they are typically generated dynamically and can be very // verbose. For example, some transforms return interface{} because // of Go's lack of generics, but typically take in and return the // exact same concrete type. if s.Type().PkgPath() == "" { continue } } ssPost = append(ssPost, s.String()) } for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 { ssPre[i], ssPre[j] = ssPre[j], ssPre[i] } return strings.Join(ssPre, "") + strings.Join(ssPost, "") } type ( pathStep struct { typ reflect.Type } sliceIndex struct { pathStep xkey, ykey int } mapIndex struct { pathStep key reflect.Value } typeAssertion struct { pathStep } structField struct { pathStep name string idx int // These fields are used for forcibly accessing an unexported field. // pvx, pvy, and field are only valid if unexported is true. unexported bool force bool // Forcibly allow visibility pvx, pvy reflect.Value // Parent values field reflect.StructField // Field information } indirect struct { pathStep } transform struct { pathStep trans *transformer } ) func (ps pathStep) Type() reflect.Type { return ps.typ } func (ps pathStep) String() string { if ps.typ == nil { return "<nil>" } s := ps.typ.String() if s == "" || strings.ContainsAny(s, "{}\n") { return "root" // Type too simple or complex to print } return fmt.Sprintf("{%s}", s) } func (si sliceIndex) String() string { switch { case si.xkey == si.ykey: return fmt.Sprintf("[%d]", si.xkey) case si.ykey == -1: // [5->?] means "I don't know where X[5] went" return fmt.Sprintf("[%d->?]", si.xkey) case si.xkey == -1: // [?->3] means "I don't know where Y[3] came from" return fmt.Sprintf("[?->%d]", si.ykey) default: // [5->3] means "X[5] moved to Y[3]" return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey) } } func (mi mapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) } func (ta typeAssertion) String() string { return fmt.Sprintf(".(%v)", ta.typ) } func (sf structField) String() string { return fmt.Sprintf(".%s", sf.name) } func (in indirect) String() string { return "*" } func (tf transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) } func (si sliceIndex) Key() int { if si.xkey != si.ykey { return -1 } return si.xkey } func (si sliceIndex) SplitKeys() (x, y int) { return si.xkey, si.ykey } func (mi mapIndex) Key() reflect.Value { return mi.key } func (sf structField) Name() string { return sf.name } func (sf structField) Index() int { return sf.idx } func (tf transform) Name() string { return tf.trans.name } func (tf transform) Func() reflect.Value { return tf.trans.fnc } func (tf transform) Option() Option { return tf.trans } func (pathStep) isPathStep() {} func (sliceIndex) isSliceIndex() {} func (mapIndex) isMapIndex() {} func (typeAssertion) isTypeAssertion() {} func (structField) isStructField() {} func (indirect) isIndirect() {} func (transform) isTransform() {} var ( _ SliceIndex = sliceIndex{} _ MapIndex = mapIndex{} _ TypeAssertion = typeAssertion{} _ StructField = structField{} _ Indirect = indirect{} _ Transform = transform{} _ PathStep = sliceIndex{} _ PathStep = mapIndex{} _ PathStep = typeAssertion{} _ PathStep = structField{} _ PathStep = indirect{} _ PathStep = transform{} ) // isExported reports whether the identifier is exported. func isExported(id string) bool { r, _ := utf8.DecodeRuneInString(id) return unicode.IsUpper(r) } // isValid reports whether the identifier is valid. // Empty and underscore-only strings are not valid. func isValid(id string) bool { ok := id != "" && id != "_" for j, c := range id { ok = ok && (j > 0 || !unicode.IsDigit(c)) ok = ok && (c == '_' || unicode.IsLetter(c) || unicode.IsDigit(c)) } return ok }
dep/vendor/github.com/google/go-cmp/cmp/path.go/0
{ "file_path": "dep/vendor/github.com/google/go-cmp/cmp/path.go", "repo_id": "dep", "token_count": 3176 }
42
// Parsing keys handling both bare and quoted keys. package toml import ( "bytes" "errors" "fmt" "unicode" ) // Convert the bare key group string to an array. // The input supports double quotation to allow "." inside the key name, // but escape sequences are not supported. Lexers must unescape them beforehand. func parseKey(key string) ([]string, error) { groups := []string{} var buffer bytes.Buffer inQuotes := false wasInQuotes := false ignoreSpace := true expectDot := false for _, char := range key { if ignoreSpace { if char == ' ' { continue } ignoreSpace = false } switch char { case '"': if inQuotes { groups = append(groups, buffer.String()) buffer.Reset() wasInQuotes = true } inQuotes = !inQuotes expectDot = false case '.': if inQuotes { buffer.WriteRune(char) } else { if !wasInQuotes { if buffer.Len() == 0 { return nil, errors.New("empty table key") } groups = append(groups, buffer.String()) buffer.Reset() } ignoreSpace = true expectDot = false wasInQuotes = false } case ' ': if inQuotes { buffer.WriteRune(char) } else { expectDot = true } default: if !inQuotes && !isValidBareChar(char) { return nil, fmt.Errorf("invalid bare character: %c", char) } if !inQuotes && expectDot { return nil, errors.New("what?") } buffer.WriteRune(char) expectDot = false } } if inQuotes { return nil, errors.New("mismatched quotes") } if buffer.Len() > 0 { groups = append(groups, buffer.String()) } if len(groups) == 0 { return nil, errors.New("empty key") } return groups, nil } func isValidBareChar(r rune) bool { return isAlphanumeric(r) || r == '-' || unicode.IsNumber(r) }
dep/vendor/github.com/pelletier/go-toml/keysparsing.go/0
{ "file_path": "dep/vendor/github.com/pelletier/go-toml/keysparsing.go", "repo_id": "dep", "token_count": 721 }
43
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Constants that were deprecated or moved to enums in the FreeBSD headers. Keep // them here for backwards compatibility. package unix const ( IFF_SMART = 0x20 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BSC = 0x53 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf2 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_IPXIP = 0xf9 IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf6 IFT_PFSYNC = 0xf7 IFT_PLC = 0xae IFT_POS = 0xab IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xd7 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VOICEEM = 0x64 IFT_VOICEENCAP = 0x67 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IPPROTO_MAXID = 0x34 IPV6_FAITH = 0x1d IP_FAITH = 0x16 MAP_NORESERVE = 0x40 MAP_RENAME = 0x20 NET_RT_MAXID = 0x6 RTF_PRCLONING = 0x10000 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa SIOCADDRT = 0x8030720a SIOCALIFADDR = 0x8118691b SIOCDELRT = 0x8030720b SIOCDLIFADDR = 0x8118691d SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCSLIFPHYADDR = 0x8118694a )
dep/vendor/golang.org/x/sys/unix/errors_freebsd_386.go/0
{ "file_path": "dep/vendor/golang.org/x/sys/unix/errors_freebsd_386.go", "repo_id": "dep", "token_count": 7268 }
44
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin dragonfly freebsd linux netbsd openbsd solaris package unix func itoa(val int) string { // do it here rather than with fmt to avoid dependency if val < 0 { return "-" + uitoa(uint(-val)) } return uitoa(uint(val)) } func uitoa(val uint) string { var buf [32]byte // big enough for int64 i := len(buf) - 1 for val >= 10 { buf[i] = byte(val%10 + '0') i-- val /= 10 } buf[i] = byte(val + '0') return string(buf[i:]) }
dep/vendor/golang.org/x/sys/unix/str.go/0
{ "file_path": "dep/vendor/golang.org/x/sys/unix/str.go", "repo_id": "dep", "token_count": 228 }
45
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build amd64,linux package unix //sys Dup2(oldfd int, newfd int) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) //sysnb Getuid() (uid int) //sysnb InotifyInit() (fd int, err error) //sys Ioperm(from int, num int, on int) (err error) //sys Iopl(level int) (err error) //sys Lchown(path string, uid int, gid int) (err error) //sys Listen(s int, n int) (err error) //sys Lstat(path string, stat *Stat_t) (err error) //sys Pause() (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK //sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) //sys Stat(path string, stat *Stat_t) (err error) //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) func Gettimeofday(tv *Timeval) (err error) { errno := gettimeofday(tv) if errno != 0 { return errno } return nil } func Getpagesize() int { return 4096 } func Time(t *Time_t) (tt Time_t, err error) { var tv Timeval errno := gettimeofday(&tv) if errno != 0 { return 0, errno } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } //sys Utime(path string, buf *Utimbuf) (err error) func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = nsec / 1e9 tv.Usec = nsec % 1e9 / 1e3 return } //sysnb pipe(p *[2]_C_int) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe(&pp) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } func (r *PtraceRegs) PC() uint64 { return r.Rip } func (r *PtraceRegs) SetPC(pc uint64) { r.Rip = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint64(length) } //sys poll(fds *PollFd, nfds int, timeout int) (n int, err error) func Poll(fds []PollFd, timeout int) (n int, err error) { if len(fds) == 0 { return poll(nil, 0, timeout) } return poll(&fds[0], len(fds), timeout) }
dep/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go/0
{ "file_path": "dep/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go", "repo_id": "dep", "token_count": 2207 }
46
// mkerrors.sh -m64 // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,dragonfly // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m64 _const.go package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_ATM = 0x1e AF_BLUETOOTH = 0x21 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1a AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x23 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1c AF_IPX = 0x17 AF_ISDN = 0x1a AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x24 AF_MPLS = 0x22 AF_NATM = 0x1d AF_NETBIOS = 0x6 AF_NETGRAPH = 0x20 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 ALTWERASE = 0x200 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc0104279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4010426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x2000427a BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80104267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x8010427b BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8010426d BIOCSSEESENT = 0x80044277 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x8 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DEFAULTBUFSIZE = 0x1000 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MAX_CLONES = 0x80 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CLOCK_MONOTONIC = 0x4 CLOCK_MONOTONIC_FAST = 0xc CLOCK_MONOTONIC_PRECISE = 0xb CLOCK_PROCESS_CPUTIME_ID = 0xf CLOCK_PROF = 0x2 CLOCK_REALTIME = 0x0 CLOCK_REALTIME_FAST = 0xa CLOCK_REALTIME_PRECISE = 0x9 CLOCK_SECOND = 0xd CLOCK_THREAD_CPUTIME_ID = 0xe CLOCK_UPTIME = 0x5 CLOCK_UPTIME_FAST = 0x8 CLOCK_UPTIME_PRECISE = 0x7 CLOCK_VIRTUAL = 0x1 CREAD = 0x800 CRTSCTS = 0x30000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 DLT_A653_ICM = 0xb9 DLT_AIRONET_HEADER = 0x78 DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ARCNET_LINUX = 0x81 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AURORA = 0x7e DLT_AX25 = 0x3 DLT_AX25_KISS = 0xca DLT_BACNET_MS_TP = 0xa5 DLT_BLUETOOTH_HCI_H4 = 0xbb DLT_BLUETOOTH_HCI_H4_WITH_PHDR = 0xc9 DLT_CAN20B = 0xbe DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_CISCO_IOS = 0x76 DLT_C_HDLC = 0x68 DLT_C_HDLC_WITH_DIR = 0xcd DLT_DOCSIS = 0x8f DLT_ECONET = 0x73 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_ENC = 0x6d DLT_ERF = 0xc5 DLT_ERF_ETH = 0xaf DLT_ERF_POS = 0xb0 DLT_FDDI = 0xa DLT_FLEXRAY = 0xd2 DLT_FRELAY = 0x6b DLT_FRELAY_WITH_DIR = 0xce DLT_GCOM_SERIAL = 0xad DLT_GCOM_T1E1 = 0xac DLT_GPF_F = 0xab DLT_GPF_T = 0xaa DLT_GPRS_LLC = 0xa9 DLT_HHDLC = 0x79 DLT_IBM_SN = 0x92 DLT_IBM_SP = 0x91 DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_IEEE802_15_4 = 0xc3 DLT_IEEE802_15_4_LINUX = 0xbf DLT_IEEE802_15_4_NONASK_PHY = 0xd7 DLT_IEEE802_16_MAC_CPS = 0xbc DLT_IEEE802_16_MAC_CPS_RADIO = 0xc1 DLT_IPFILTER = 0x74 DLT_IPMB = 0xc7 DLT_IPMB_LINUX = 0xd1 DLT_IP_OVER_FC = 0x7a DLT_JUNIPER_ATM1 = 0x89 DLT_JUNIPER_ATM2 = 0x87 DLT_JUNIPER_CHDLC = 0xb5 DLT_JUNIPER_ES = 0x84 DLT_JUNIPER_ETHER = 0xb2 DLT_JUNIPER_FRELAY = 0xb4 DLT_JUNIPER_GGSN = 0x85 DLT_JUNIPER_ISM = 0xc2 DLT_JUNIPER_MFR = 0x86 DLT_JUNIPER_MLFR = 0x83 DLT_JUNIPER_MLPPP = 0x82 DLT_JUNIPER_MONITOR = 0xa4 DLT_JUNIPER_PIC_PEER = 0xae DLT_JUNIPER_PPP = 0xb3 DLT_JUNIPER_PPPOE = 0xa7 DLT_JUNIPER_PPPOE_ATM = 0xa8 DLT_JUNIPER_SERVICES = 0x88 DLT_JUNIPER_ST = 0xc8 DLT_JUNIPER_VP = 0xb7 DLT_LAPB_WITH_DIR = 0xcf DLT_LAPD = 0xcb DLT_LIN = 0xd4 DLT_LINUX_IRDA = 0x90 DLT_LINUX_LAPD = 0xb1 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_LTALK = 0x72 DLT_MFR = 0xb6 DLT_MOST = 0xd3 DLT_MTP2 = 0x8c DLT_MTP2_WITH_PHDR = 0x8b DLT_MTP3 = 0x8d DLT_NULL = 0x0 DLT_PCI_EXP = 0x7d DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPI = 0xc0 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_ETHER = 0x33 DLT_PPP_PPPD = 0xa6 DLT_PPP_SERIAL = 0x32 DLT_PPP_WITH_DIR = 0xcc DLT_PRISM_HEADER = 0x77 DLT_PRONET = 0x4 DLT_RAIF1 = 0xc6 DLT_RAW = 0xc DLT_REDBACK_SMARTEDGE = 0x20 DLT_RIO = 0x7c DLT_SCCP = 0x8e DLT_SITA = 0xc4 DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DLT_SUNATM = 0x7b DLT_SYMANTEC_FIREWALL = 0x63 DLT_TZSP = 0x80 DLT_USB = 0xba DLT_USB_LINUX = 0xbd DLT_X2E_SERIAL = 0xd5 DLT_X2E_XORAYA = 0xd6 DT_BLK = 0x6 DT_CHR = 0x2 DT_DBF = 0xf DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_EXCEPT = -0x8 EVFILT_FS = -0xa EVFILT_MARKER = 0xf EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xa EVFILT_TIMER = -0x7 EVFILT_USER = -0x9 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_NODATA = 0x1000 EV_ONESHOT = 0x10 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTEXIT_LWP = 0x10000 EXTEXIT_PROC = 0x0 EXTEXIT_SETINT = 0x1 EXTEXIT_SIMPLE = 0x0 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_DUP2FD = 0xa F_DUP2FD_CLOEXEC = 0x12 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x11 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 F_OK = 0x0 F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETOWN = 0x6 F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x118e72 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MONITOR = 0x40000 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NPOLLING = 0x100000 IFF_OACTIVE = 0x400 IFF_OACTIVE_COMPAT = 0x400 IFF_POINTOPOINT = 0x10 IFF_POLLING = 0x10000 IFF_POLLING_COMPAT = 0x10000 IFF_PPROMISC = 0x20000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_SMART = 0x20 IFF_STATICARP = 0x80000 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_A12MPPSWITCH = 0x82 IFT_AAL2 = 0xbb IFT_AAL5 = 0x31 IFT_ADSL = 0x5e IFT_AFLANE8023 = 0x3b IFT_AFLANE8025 = 0x3c IFT_ARAP = 0x58 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ASYNC = 0x54 IFT_ATM = 0x25 IFT_ATMDXI = 0x69 IFT_ATMFUNI = 0x6a IFT_ATMIMA = 0x6b IFT_ATMLOGICAL = 0x50 IFT_ATMRADIO = 0xbd IFT_ATMSUBINTERFACE = 0x86 IFT_ATMVCIENDPT = 0xc2 IFT_ATMVIRTUAL = 0x95 IFT_BGPPOLICYACCOUNTING = 0xa2 IFT_BRIDGE = 0xd1 IFT_BSC = 0x53 IFT_CARP = 0xf8 IFT_CCTEMUL = 0x3d IFT_CEPT = 0x13 IFT_CES = 0x85 IFT_CHANNEL = 0x46 IFT_CNR = 0x55 IFT_COFFEE = 0x84 IFT_COMPOSITELINK = 0x9b IFT_DCN = 0x8d IFT_DIGITALPOWERLINE = 0x8a IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba IFT_DLSW = 0x4a IFT_DOCSCABLEDOWNSTREAM = 0x80 IFT_DOCSCABLEMACLAYER = 0x7f IFT_DOCSCABLEUPSTREAM = 0x81 IFT_DS0 = 0x51 IFT_DS0BUNDLE = 0x52 IFT_DS1FDL = 0xaa IFT_DS3 = 0x1e IFT_DTM = 0x8c IFT_DVBASILN = 0xac IFT_DVBASIOUT = 0xad IFT_DVBRCCDOWNSTREAM = 0x93 IFT_DVBRCCMACLAYER = 0x92 IFT_DVBRCCUPSTREAM = 0x94 IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_EPLRS = 0x57 IFT_ESCON = 0x49 IFT_ETHER = 0x6 IFT_FAITH = 0xf2 IFT_FAST = 0x7d IFT_FASTETHER = 0x3e IFT_FASTETHERFX = 0x45 IFT_FDDI = 0xf IFT_FIBRECHANNEL = 0x38 IFT_FRAMERELAYINTERCONNECT = 0x3a IFT_FRAMERELAYMPI = 0x5c IFT_FRDLCIENDPT = 0xc1 IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_FRF16MFRBUNDLE = 0xa3 IFT_FRFORWARD = 0x9e IFT_G703AT2MB = 0x43 IFT_G703AT64K = 0x42 IFT_GIF = 0xf0 IFT_GIGABITETHERNET = 0x75 IFT_GR303IDT = 0xb2 IFT_GR303RDT = 0xb1 IFT_H323GATEKEEPER = 0xa4 IFT_H323PROXY = 0xa5 IFT_HDH1822 = 0x3 IFT_HDLC = 0x76 IFT_HDSL2 = 0xa8 IFT_HIPERLAN2 = 0xb7 IFT_HIPPI = 0x2f IFT_HIPPIINTERFACE = 0x39 IFT_HOSTPAD = 0x5a IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IBM370PARCHAN = 0x48 IFT_IDSL = 0x9a IFT_IEEE1394 = 0x90 IFT_IEEE80211 = 0x47 IFT_IEEE80212 = 0x37 IFT_IEEE8023ADLAG = 0xa1 IFT_IFGSN = 0x91 IFT_IMT = 0xbe IFT_INTERLEAVE = 0x7c IFT_IP = 0x7e IFT_IPFORWARD = 0x8e IFT_IPOVERATM = 0x72 IFT_IPOVERCDLC = 0x6d IFT_IPOVERCLAW = 0x6e IFT_IPSWITCH = 0x4e IFT_ISDN = 0x3f IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISDNS = 0x4b IFT_ISDNU = 0x4c IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88025CRFPINT = 0x62 IFT_ISO88025DTR = 0x56 IFT_ISO88025FIBER = 0x73 IFT_ISO88026 = 0xa IFT_ISUP = 0xb3 IFT_L2VLAN = 0x87 IFT_L3IPVLAN = 0x88 IFT_L3IPXVLAN = 0x89 IFT_LAPB = 0x10 IFT_LAPD = 0x4d IFT_LAPF = 0x77 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_MPC = 0x71 IFT_MPLS = 0xa6 IFT_MPLSTUNNEL = 0x96 IFT_MSDSL = 0x8f IFT_MVL = 0xbf IFT_MYRINET = 0x63 IFT_NFAS = 0xaf IFT_NSIP = 0x1b IFT_OPTICALCHANNEL = 0xc3 IFT_OPTICALTRANSPORT = 0xc4 IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PLC = 0xae IFT_POS = 0xab IFT_PPP = 0x17 IFT_PPPMULTILINKBUNDLE = 0x6c IFT_PROPBWAP2MP = 0xb8 IFT_PROPCNLS = 0x59 IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5 IFT_PROPDOCSWIRELESSMACLAYER = 0xb4 IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PROPWIRELESSP2P = 0x9d IFT_PTPSERIAL = 0x16 IFT_PVC = 0xf1 IFT_QLLC = 0x44 IFT_RADIOMAC = 0xbc IFT_RADSL = 0x5f IFT_REACHDSL = 0xc0 IFT_RFC1483 = 0x9f IFT_RS232 = 0x21 IFT_RSRB = 0x4f IFT_SDLC = 0x11 IFT_SDSL = 0x60 IFT_SHDSL = 0xa9 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETOVERHEADCHANNEL = 0xb9 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_SRP = 0x97 IFT_SS7SIGLINK = 0x9c IFT_STACKTOSTACK = 0x6f IFT_STARLAN = 0xb IFT_STF = 0xf3 IFT_T1 = 0x12 IFT_TDLC = 0x74 IFT_TERMPAD = 0x5b IFT_TR008 = 0xb0 IFT_TRANSPHDLC = 0x7b IFT_TUNNEL = 0x83 IFT_ULTRA = 0x1d IFT_USB = 0xa0 IFT_V11 = 0x40 IFT_V35 = 0x2d IFT_V36 = 0x41 IFT_V37 = 0x78 IFT_VDSL = 0x61 IFT_VIRTUALIPADDRESS = 0x70 IFT_VOICEEM = 0x64 IFT_VOICEENCAP = 0x67 IFT_VOICEFXO = 0x65 IFT_VOICEFXS = 0x66 IFT_VOICEOVERATM = 0x98 IFT_VOICEOVERFRAMERELAY = 0x99 IFT_VOICEOVERIP = 0x68 IFT_X213 = 0x5d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25HUNTGROUP = 0x7a IFT_X25MLP = 0x79 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LOOPBACKNET = 0x7f IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CARP = 0x70 IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0xfe IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MEAS = 0x13 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MOBILE = 0x37 IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OSPFIGP = 0x59 IPPROTO_PFSYNC = 0xf0 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SDRP = 0x2a IPPROTO_SEP = 0x21 IPPROTO_SKIP = 0x39 IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TLSP = 0x38 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_UNKNOWN = 0x102 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_AUTOFLOWLABEL = 0x3b IPV6_BINDV6ONLY = 0x1b IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_DONTFRAG = 0x3e IPV6_DSTOPTS = 0x32 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_HOPLIMIT = 0x2f IPV6_HOPOPTS = 0x31 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff IPV6_MINHLIM = 0x28 IPV6_MMTU = 0x500 IPV6_MSFILTER = 0x4a IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_NEXTHOP = 0x30 IPV6_PATHMTU = 0x2c IPV6_PKTINFO = 0x2e IPV6_PKTOPTIONS = 0x34 IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_PREFER_TEMPADDR = 0x3f IPV6_RECVDSTOPTS = 0x28 IPV6_RECVHOPLIMIT = 0x25 IPV6_RECVHOPOPTS = 0x27 IPV6_RECVPATHMTU = 0x2b IPV6_RECVPKTINFO = 0x24 IPV6_RECVRTHDR = 0x26 IPV6_RECVTCLASS = 0x39 IPV6_RTHDR = 0x33 IPV6_RTHDRDSTOPTS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x3d IPV6_UNICAST_HOPS = 0x4 IPV6_USE_MIN_MTU = 0x2a IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FAITH = 0x16 IP_FW_ADD = 0x32 IP_FW_DEL = 0x33 IP_FW_FLUSH = 0x34 IP_FW_GET = 0x36 IP_FW_RESETLOG = 0x37 IP_FW_X = 0x31 IP_FW_ZERO = 0x35 IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x42 IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_OFFMASK = 0x1fff IP_OPTIONS = 0x1 IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x41 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_AUTOSYNC = 0x7 MADV_CONTROL_END = 0xb MADV_CONTROL_START = 0xa MADV_CORE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_INVAL = 0xa MADV_NOCORE = 0x8 MADV_NORMAL = 0x0 MADV_NOSYNC = 0x6 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_SETMAP = 0xb MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 MAP_ANONYMOUS = 0x1000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_INHERIT = 0x80 MAP_NOCORE = 0x20000 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_NOSYNC = 0x800 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_SHARED = 0x1 MAP_SIZEALIGN = 0x40000 MAP_STACK = 0x400 MAP_TRYFIXED = 0x10000 MAP_VPAGETABLE = 0x2000 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_CMSG_CLOEXEC = 0x1000 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_FBLOCKING = 0x10000 MSG_FMASK = 0xffff0000 MSG_FNONBLOCKING = 0x20000 MSG_NOSIGNAL = 0x400 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_SYNC = 0x800 MSG_TRUNC = 0x10 MSG_UNUSED09 = 0x200 MSG_WAITALL = 0x40 MS_ASYNC = 0x1 MS_INVALIDATE = 0x2 MS_SYNC = 0x0 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_MAXID = 0x4 NOFLSH = 0x80000000 NOKERNINFO = 0x2000000 NOTE_ATTRIB = 0x8 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FORK = 0x40000000 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_OOB = 0x2 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 OXTABS = 0x4 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x20000 O_CREAT = 0x200 O_DIRECT = 0x10000 O_DIRECTORY = 0x8000000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FAPPEND = 0x100000 O_FASYNCWRITE = 0x800000 O_FBLOCKING = 0x40000 O_FMASK = 0xfc0000 O_FNONBLOCKING = 0x80000 O_FOFFSET = 0x200000 O_FSYNC = 0x80 O_FSYNCWRITE = 0x400000 O_NDELAY = 0x4 O_NOCTTY = 0x8000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 RLIMIT_AS = 0xa RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0xb RTAX_MPLS1 = 0x8 RTAX_MPLS2 = 0x9 RTAX_MPLS3 = 0xa RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_MPLS1 = 0x100 RTA_MPLS2 = 0x200 RTA_MPLS3 = 0x400 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CLONING = 0x100 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MPLSOPS = 0x1000000 RTF_MULTICAST = 0x800000 RTF_PINNED = 0x100000 RTF_PRCLONING = 0x10000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_REJECT = 0x8 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_WASCLONED = 0x20000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_IEEE80211 = 0x12 RTM_IFANNOUNCE = 0x11 RTM_IFINFO = 0xe RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x6 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_IWCAPSEGS = 0x400 RTV_IWMAXSEGS = 0x200 RTV_MSL = 0x100 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCADDRT = 0x8040720a SIOCAIFADDR = 0x8040691a SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8040720b SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc028697b SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020691f SIOCGIFCONF = 0xc0106924 SIOCGIFDATA = 0xc0206926 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc028698a SIOCGIFINDEX = 0xc0206920 SIOCGIFMEDIA = 0xc0306938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206948 SIOCGIFPHYS = 0xc0206935 SIOCGIFPOLLCPU = 0xc020697e SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFSTATUS = 0xc331693b SIOCGIFTSOLEN = 0xc0206980 SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 SIOCIFCREATE = 0xc020697a SIOCIFCREATE2 = 0xc020697c SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106978 SIOCSDRVSPEC = 0x8028697b SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020691e SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020693c SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNAME = 0x80206928 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x80406946 SIOCSIFPHYS = 0x80206936 SIOCSIFPOLLCPU = 0x8020697d SIOCSIFTSOLEN = 0x8020697f SIOCSLIFPHYADDR = 0x8118694a SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SOCK_CLOEXEC = 0x10000000 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_NONBLOCK = 0x20000000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 SO_CPUHINT = 0x1030 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LINGER = 0x80 SO_NOSIGPIPE = 0x800 SO_OOBINLINE = 0x100 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDSPACE = 0x100a SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 TCIFLUSH = 0x1 TCIOFF = 0x3 TCIOFLUSH = 0x3 TCION = 0x4 TCOFLUSH = 0x2 TCOOFF = 0x1 TCOON = 0x2 TCP_FASTKEEP = 0x80 TCP_KEEPCNT = 0x400 TCP_KEEPIDLE = 0x100 TCP_KEEPINIT = 0x20 TCP_KEEPINTVL = 0x200 TCP_MAXBURST = 0x4 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MINMSS = 0x100 TCP_MIN_WINSHIFT = 0x5 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_SIGNATURE_ENABLE = 0x10 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x40107458 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x402c7413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGSID = 0x40047463 TIOCGSIZE = 0x40087468 TIOCGWINSZ = 0x40087468 TIOCISPTMASTER = 0x20007455 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMODG = 0x40047403 TIOCMODS = 0x80047404 TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x802c7414 TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b TIOCSIG = 0x2000745f TIOCSPGRP = 0x80047476 TIOCSSIZE = 0x80087467 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VCHECKPT = 0x13 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VERASE2 = 0x7 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VM_BCACHE_SIZE_MAX = 0x0 VM_SWZONE_SIZE_MAX = 0x4000000000 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x4 WCOREFLAG = 0x80 WLINUXCLONE = 0x80000000 WNOHANG = 0x1 WSTOPPED = 0x7f WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EASYNC = syscall.Errno(0x63) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) EBADMSG = syscall.Errno(0x59) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x55) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDOM = syscall.Errno(0x21) EDOOFUS = syscall.Errno(0x58) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x52) EILSEQ = syscall.Errno(0x56) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x63) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5a) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x57) ENOBUFS = syscall.Errno(0x37) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x5b) ENOMEDIUM = syscall.Errno(0x5d) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x53) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x54) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x5c) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUNUSED94 = syscall.Errno(0x5e) EUNUSED95 = syscall.Errno(0x5f) EUNUSED96 = syscall.Errno(0x60) EUNUSED97 = syscall.Errno(0x61) EUNUSED98 = syscall.Errno(0x62) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCKPT = syscall.Signal(0x21) SIGCKPTEXIT = syscall.Signal(0x22) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTHR = syscall.Signal(0x20) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) ) // Error table var errors = [...]string{ 1: "operation not permitted", 2: "no such file or directory", 3: "no such process", 4: "interrupted system call", 5: "input/output error", 6: "device not configured", 7: "argument list too long", 8: "exec format error", 9: "bad file descriptor", 10: "no child processes", 11: "resource deadlock avoided", 12: "cannot allocate memory", 13: "permission denied", 14: "bad address", 15: "block device required", 16: "device busy", 17: "file exists", 18: "cross-device link", 19: "operation not supported by device", 20: "not a directory", 21: "is a directory", 22: "invalid argument", 23: "too many open files in system", 24: "too many open files", 25: "inappropriate ioctl for device", 26: "text file busy", 27: "file too large", 28: "no space left on device", 29: "illegal seek", 30: "read-only file system", 31: "too many links", 32: "broken pipe", 33: "numerical argument out of domain", 34: "result too large", 35: "resource temporarily unavailable", 36: "operation now in progress", 37: "operation already in progress", 38: "socket operation on non-socket", 39: "destination address required", 40: "message too long", 41: "protocol wrong type for socket", 42: "protocol not available", 43: "protocol not supported", 44: "socket type not supported", 45: "operation not supported", 46: "protocol family not supported", 47: "address family not supported by protocol family", 48: "address already in use", 49: "can't assign requested address", 50: "network is down", 51: "network is unreachable", 52: "network dropped connection on reset", 53: "software caused connection abort", 54: "connection reset by peer", 55: "no buffer space available", 56: "socket is already connected", 57: "socket is not connected", 58: "can't send after socket shutdown", 59: "too many references: can't splice", 60: "operation timed out", 61: "connection refused", 62: "too many levels of symbolic links", 63: "file name too long", 64: "host is down", 65: "no route to host", 66: "directory not empty", 67: "too many processes", 68: "too many users", 69: "disc quota exceeded", 70: "stale NFS file handle", 71: "too many levels of remote in path", 72: "RPC struct is bad", 73: "RPC version wrong", 74: "RPC prog. not avail", 75: "program version wrong", 76: "bad procedure for program", 77: "no locks available", 78: "function not implemented", 79: "inappropriate file type or format", 80: "authentication error", 81: "need authenticator", 82: "identifier removed", 83: "no message of desired type", 84: "value too large to be stored in data type", 85: "operation canceled", 86: "illegal byte sequence", 87: "attribute not found", 88: "programming error", 89: "bad message", 90: "multihop attempted", 91: "link has been severed", 92: "protocol error", 93: "no medium found", 94: "unknown error: 94", 95: "unknown error: 95", 96: "unknown error: 96", 97: "unknown error: 97", 98: "unknown error: 98", 99: "unknown error: 99", } // Signal table var signals = [...]string{ 1: "hangup", 2: "interrupt", 3: "quit", 4: "illegal instruction", 5: "trace/BPT trap", 6: "abort trap", 7: "EMT trap", 8: "floating point exception", 9: "killed", 10: "bus error", 11: "segmentation fault", 12: "bad system call", 13: "broken pipe", 14: "alarm clock", 15: "terminated", 16: "urgent I/O condition", 17: "suspended (signal)", 18: "suspended", 19: "continued", 20: "child exited", 21: "stopped (tty input)", 22: "stopped (tty output)", 23: "I/O possible", 24: "cputime limit exceeded", 25: "filesize limit exceeded", 26: "virtual timer expired", 27: "profiling timer expired", 28: "window size changes", 29: "information request", 30: "user defined signal 1", 31: "user defined signal 2", 32: "thread Scheduler", 33: "checkPoint", 34: "checkPointExit", }
dep/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go/0
{ "file_path": "dep/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go", "repo_id": "dep", "token_count": 48445 }
47
// linux/mksysnum.pl -Wall -Werror -static -I/tmp/include /tmp/include/asm/unistd.h // Code generated by the command above; see README.md. DO NOT EDIT. // +build mips64,linux package unix const ( SYS_READ = 5000 SYS_WRITE = 5001 SYS_OPEN = 5002 SYS_CLOSE = 5003 SYS_STAT = 5004 SYS_FSTAT = 5005 SYS_LSTAT = 5006 SYS_POLL = 5007 SYS_LSEEK = 5008 SYS_MMAP = 5009 SYS_MPROTECT = 5010 SYS_MUNMAP = 5011 SYS_BRK = 5012 SYS_RT_SIGACTION = 5013 SYS_RT_SIGPROCMASK = 5014 SYS_IOCTL = 5015 SYS_PREAD64 = 5016 SYS_PWRITE64 = 5017 SYS_READV = 5018 SYS_WRITEV = 5019 SYS_ACCESS = 5020 SYS_PIPE = 5021 SYS__NEWSELECT = 5022 SYS_SCHED_YIELD = 5023 SYS_MREMAP = 5024 SYS_MSYNC = 5025 SYS_MINCORE = 5026 SYS_MADVISE = 5027 SYS_SHMGET = 5028 SYS_SHMAT = 5029 SYS_SHMCTL = 5030 SYS_DUP = 5031 SYS_DUP2 = 5032 SYS_PAUSE = 5033 SYS_NANOSLEEP = 5034 SYS_GETITIMER = 5035 SYS_SETITIMER = 5036 SYS_ALARM = 5037 SYS_GETPID = 5038 SYS_SENDFILE = 5039 SYS_SOCKET = 5040 SYS_CONNECT = 5041 SYS_ACCEPT = 5042 SYS_SENDTO = 5043 SYS_RECVFROM = 5044 SYS_SENDMSG = 5045 SYS_RECVMSG = 5046 SYS_SHUTDOWN = 5047 SYS_BIND = 5048 SYS_LISTEN = 5049 SYS_GETSOCKNAME = 5050 SYS_GETPEERNAME = 5051 SYS_SOCKETPAIR = 5052 SYS_SETSOCKOPT = 5053 SYS_GETSOCKOPT = 5054 SYS_CLONE = 5055 SYS_FORK = 5056 SYS_EXECVE = 5057 SYS_EXIT = 5058 SYS_WAIT4 = 5059 SYS_KILL = 5060 SYS_UNAME = 5061 SYS_SEMGET = 5062 SYS_SEMOP = 5063 SYS_SEMCTL = 5064 SYS_SHMDT = 5065 SYS_MSGGET = 5066 SYS_MSGSND = 5067 SYS_MSGRCV = 5068 SYS_MSGCTL = 5069 SYS_FCNTL = 5070 SYS_FLOCK = 5071 SYS_FSYNC = 5072 SYS_FDATASYNC = 5073 SYS_TRUNCATE = 5074 SYS_FTRUNCATE = 5075 SYS_GETDENTS = 5076 SYS_GETCWD = 5077 SYS_CHDIR = 5078 SYS_FCHDIR = 5079 SYS_RENAME = 5080 SYS_MKDIR = 5081 SYS_RMDIR = 5082 SYS_CREAT = 5083 SYS_LINK = 5084 SYS_UNLINK = 5085 SYS_SYMLINK = 5086 SYS_READLINK = 5087 SYS_CHMOD = 5088 SYS_FCHMOD = 5089 SYS_CHOWN = 5090 SYS_FCHOWN = 5091 SYS_LCHOWN = 5092 SYS_UMASK = 5093 SYS_GETTIMEOFDAY = 5094 SYS_GETRLIMIT = 5095 SYS_GETRUSAGE = 5096 SYS_SYSINFO = 5097 SYS_TIMES = 5098 SYS_PTRACE = 5099 SYS_GETUID = 5100 SYS_SYSLOG = 5101 SYS_GETGID = 5102 SYS_SETUID = 5103 SYS_SETGID = 5104 SYS_GETEUID = 5105 SYS_GETEGID = 5106 SYS_SETPGID = 5107 SYS_GETPPID = 5108 SYS_GETPGRP = 5109 SYS_SETSID = 5110 SYS_SETREUID = 5111 SYS_SETREGID = 5112 SYS_GETGROUPS = 5113 SYS_SETGROUPS = 5114 SYS_SETRESUID = 5115 SYS_GETRESUID = 5116 SYS_SETRESGID = 5117 SYS_GETRESGID = 5118 SYS_GETPGID = 5119 SYS_SETFSUID = 5120 SYS_SETFSGID = 5121 SYS_GETSID = 5122 SYS_CAPGET = 5123 SYS_CAPSET = 5124 SYS_RT_SIGPENDING = 5125 SYS_RT_SIGTIMEDWAIT = 5126 SYS_RT_SIGQUEUEINFO = 5127 SYS_RT_SIGSUSPEND = 5128 SYS_SIGALTSTACK = 5129 SYS_UTIME = 5130 SYS_MKNOD = 5131 SYS_PERSONALITY = 5132 SYS_USTAT = 5133 SYS_STATFS = 5134 SYS_FSTATFS = 5135 SYS_SYSFS = 5136 SYS_GETPRIORITY = 5137 SYS_SETPRIORITY = 5138 SYS_SCHED_SETPARAM = 5139 SYS_SCHED_GETPARAM = 5140 SYS_SCHED_SETSCHEDULER = 5141 SYS_SCHED_GETSCHEDULER = 5142 SYS_SCHED_GET_PRIORITY_MAX = 5143 SYS_SCHED_GET_PRIORITY_MIN = 5144 SYS_SCHED_RR_GET_INTERVAL = 5145 SYS_MLOCK = 5146 SYS_MUNLOCK = 5147 SYS_MLOCKALL = 5148 SYS_MUNLOCKALL = 5149 SYS_VHANGUP = 5150 SYS_PIVOT_ROOT = 5151 SYS__SYSCTL = 5152 SYS_PRCTL = 5153 SYS_ADJTIMEX = 5154 SYS_SETRLIMIT = 5155 SYS_CHROOT = 5156 SYS_SYNC = 5157 SYS_ACCT = 5158 SYS_SETTIMEOFDAY = 5159 SYS_MOUNT = 5160 SYS_UMOUNT2 = 5161 SYS_SWAPON = 5162 SYS_SWAPOFF = 5163 SYS_REBOOT = 5164 SYS_SETHOSTNAME = 5165 SYS_SETDOMAINNAME = 5166 SYS_CREATE_MODULE = 5167 SYS_INIT_MODULE = 5168 SYS_DELETE_MODULE = 5169 SYS_GET_KERNEL_SYMS = 5170 SYS_QUERY_MODULE = 5171 SYS_QUOTACTL = 5172 SYS_NFSSERVCTL = 5173 SYS_GETPMSG = 5174 SYS_PUTPMSG = 5175 SYS_AFS_SYSCALL = 5176 SYS_RESERVED177 = 5177 SYS_GETTID = 5178 SYS_READAHEAD = 5179 SYS_SETXATTR = 5180 SYS_LSETXATTR = 5181 SYS_FSETXATTR = 5182 SYS_GETXATTR = 5183 SYS_LGETXATTR = 5184 SYS_FGETXATTR = 5185 SYS_LISTXATTR = 5186 SYS_LLISTXATTR = 5187 SYS_FLISTXATTR = 5188 SYS_REMOVEXATTR = 5189 SYS_LREMOVEXATTR = 5190 SYS_FREMOVEXATTR = 5191 SYS_TKILL = 5192 SYS_RESERVED193 = 5193 SYS_FUTEX = 5194 SYS_SCHED_SETAFFINITY = 5195 SYS_SCHED_GETAFFINITY = 5196 SYS_CACHEFLUSH = 5197 SYS_CACHECTL = 5198 SYS_SYSMIPS = 5199 SYS_IO_SETUP = 5200 SYS_IO_DESTROY = 5201 SYS_IO_GETEVENTS = 5202 SYS_IO_SUBMIT = 5203 SYS_IO_CANCEL = 5204 SYS_EXIT_GROUP = 5205 SYS_LOOKUP_DCOOKIE = 5206 SYS_EPOLL_CREATE = 5207 SYS_EPOLL_CTL = 5208 SYS_EPOLL_WAIT = 5209 SYS_REMAP_FILE_PAGES = 5210 SYS_RT_SIGRETURN = 5211 SYS_SET_TID_ADDRESS = 5212 SYS_RESTART_SYSCALL = 5213 SYS_SEMTIMEDOP = 5214 SYS_FADVISE64 = 5215 SYS_TIMER_CREATE = 5216 SYS_TIMER_SETTIME = 5217 SYS_TIMER_GETTIME = 5218 SYS_TIMER_GETOVERRUN = 5219 SYS_TIMER_DELETE = 5220 SYS_CLOCK_SETTIME = 5221 SYS_CLOCK_GETTIME = 5222 SYS_CLOCK_GETRES = 5223 SYS_CLOCK_NANOSLEEP = 5224 SYS_TGKILL = 5225 SYS_UTIMES = 5226 SYS_MBIND = 5227 SYS_GET_MEMPOLICY = 5228 SYS_SET_MEMPOLICY = 5229 SYS_MQ_OPEN = 5230 SYS_MQ_UNLINK = 5231 SYS_MQ_TIMEDSEND = 5232 SYS_MQ_TIMEDRECEIVE = 5233 SYS_MQ_NOTIFY = 5234 SYS_MQ_GETSETATTR = 5235 SYS_VSERVER = 5236 SYS_WAITID = 5237 SYS_ADD_KEY = 5239 SYS_REQUEST_KEY = 5240 SYS_KEYCTL = 5241 SYS_SET_THREAD_AREA = 5242 SYS_INOTIFY_INIT = 5243 SYS_INOTIFY_ADD_WATCH = 5244 SYS_INOTIFY_RM_WATCH = 5245 SYS_MIGRATE_PAGES = 5246 SYS_OPENAT = 5247 SYS_MKDIRAT = 5248 SYS_MKNODAT = 5249 SYS_FCHOWNAT = 5250 SYS_FUTIMESAT = 5251 SYS_NEWFSTATAT = 5252 SYS_UNLINKAT = 5253 SYS_RENAMEAT = 5254 SYS_LINKAT = 5255 SYS_SYMLINKAT = 5256 SYS_READLINKAT = 5257 SYS_FCHMODAT = 5258 SYS_FACCESSAT = 5259 SYS_PSELECT6 = 5260 SYS_PPOLL = 5261 SYS_UNSHARE = 5262 SYS_SPLICE = 5263 SYS_SYNC_FILE_RANGE = 5264 SYS_TEE = 5265 SYS_VMSPLICE = 5266 SYS_MOVE_PAGES = 5267 SYS_SET_ROBUST_LIST = 5268 SYS_GET_ROBUST_LIST = 5269 SYS_KEXEC_LOAD = 5270 SYS_GETCPU = 5271 SYS_EPOLL_PWAIT = 5272 SYS_IOPRIO_SET = 5273 SYS_IOPRIO_GET = 5274 SYS_UTIMENSAT = 5275 SYS_SIGNALFD = 5276 SYS_TIMERFD = 5277 SYS_EVENTFD = 5278 SYS_FALLOCATE = 5279 SYS_TIMERFD_CREATE = 5280 SYS_TIMERFD_GETTIME = 5281 SYS_TIMERFD_SETTIME = 5282 SYS_SIGNALFD4 = 5283 SYS_EVENTFD2 = 5284 SYS_EPOLL_CREATE1 = 5285 SYS_DUP3 = 5286 SYS_PIPE2 = 5287 SYS_INOTIFY_INIT1 = 5288 SYS_PREADV = 5289 SYS_PWRITEV = 5290 SYS_RT_TGSIGQUEUEINFO = 5291 SYS_PERF_EVENT_OPEN = 5292 SYS_ACCEPT4 = 5293 SYS_RECVMMSG = 5294 SYS_FANOTIFY_INIT = 5295 SYS_FANOTIFY_MARK = 5296 SYS_PRLIMIT64 = 5297 SYS_NAME_TO_HANDLE_AT = 5298 SYS_OPEN_BY_HANDLE_AT = 5299 SYS_CLOCK_ADJTIME = 5300 SYS_SYNCFS = 5301 SYS_SENDMMSG = 5302 SYS_SETNS = 5303 SYS_PROCESS_VM_READV = 5304 SYS_PROCESS_VM_WRITEV = 5305 SYS_KCMP = 5306 SYS_FINIT_MODULE = 5307 SYS_GETDENTS64 = 5308 SYS_SCHED_SETATTR = 5309 SYS_SCHED_GETATTR = 5310 SYS_RENAMEAT2 = 5311 SYS_SECCOMP = 5312 SYS_GETRANDOM = 5313 SYS_MEMFD_CREATE = 5314 SYS_BPF = 5315 SYS_EXECVEAT = 5316 SYS_USERFAULTFD = 5317 SYS_MEMBARRIER = 5318 SYS_MLOCK2 = 5319 SYS_COPY_FILE_RANGE = 5320 SYS_PREADV2 = 5321 SYS_PWRITEV2 = 5322 SYS_PKEY_MPROTECT = 5323 SYS_PKEY_ALLOC = 5324 SYS_PKEY_FREE = 5325 )
dep/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go/0
{ "file_path": "dep/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go", "repo_id": "dep", "token_count": 8375 }
48
package yaml import ( "io" ) // Set the reader error and return 0. func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { parser.error = yaml_READER_ERROR parser.problem = problem parser.problem_offset = offset parser.problem_value = value return false } // Byte order marks. const ( bom_UTF8 = "\xef\xbb\xbf" bom_UTF16LE = "\xff\xfe" bom_UTF16BE = "\xfe\xff" ) // Determine the input stream encoding by checking the BOM symbol. If no BOM is // found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { // Ensure that we had enough bytes in the raw buffer. for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { if !yaml_parser_update_raw_buffer(parser) { return false } } // Determine the encoding. buf := parser.raw_buffer pos := parser.raw_buffer_pos avail := len(buf) - pos if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { parser.encoding = yaml_UTF16LE_ENCODING parser.raw_buffer_pos += 2 parser.offset += 2 } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { parser.encoding = yaml_UTF16BE_ENCODING parser.raw_buffer_pos += 2 parser.offset += 2 } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { parser.encoding = yaml_UTF8_ENCODING parser.raw_buffer_pos += 3 parser.offset += 3 } else { parser.encoding = yaml_UTF8_ENCODING } return true } // Update the raw buffer. func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { size_read := 0 // Return if the raw buffer is full. if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { return true } // Return on EOF. if parser.eof { return true } // Move the remaining bytes in the raw buffer to the beginning. if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) } parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] parser.raw_buffer_pos = 0 // Call the read handler to fill the buffer. size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] if err == io.EOF { parser.eof = true } else if err != nil { return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) } return true } // Ensure that the buffer contains at least `length` characters. // Return true on success, false on failure. // // The length is supposed to be significantly less that the buffer size. func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { if parser.read_handler == nil { panic("read handler must be set") } // If the EOF flag is set and the raw buffer is empty, do nothing. if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { return true } // Return if the buffer contains enough characters. if parser.unread >= length { return true } // Determine the input encoding if it is not known yet. if parser.encoding == yaml_ANY_ENCODING { if !yaml_parser_determine_encoding(parser) { return false } } // Move the unread characters to the beginning of the buffer. buffer_len := len(parser.buffer) if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { copy(parser.buffer, parser.buffer[parser.buffer_pos:]) buffer_len -= parser.buffer_pos parser.buffer_pos = 0 } else if parser.buffer_pos == buffer_len { buffer_len = 0 parser.buffer_pos = 0 } // Open the whole buffer for writing, and cut it before returning. parser.buffer = parser.buffer[:cap(parser.buffer)] // Fill the buffer until it has enough characters. first := true for parser.unread < length { // Fill the raw buffer if necessary. if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { if !yaml_parser_update_raw_buffer(parser) { parser.buffer = parser.buffer[:buffer_len] return false } } first = false // Decode the raw buffer. inner: for parser.raw_buffer_pos != len(parser.raw_buffer) { var value rune var width int raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos // Decode the next character. switch parser.encoding { case yaml_UTF8_ENCODING: // Decode a UTF-8 character. Check RFC 3629 // (http://www.ietf.org/rfc/rfc3629.txt) for more details. // // The following table (taken from the RFC) is used for // decoding. // // Char. number range | UTF-8 octet sequence // (hexadecimal) | (binary) // --------------------+------------------------------------ // 0000 0000-0000 007F | 0xxxxxxx // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // // Additionally, the characters in the range 0xD800-0xDFFF // are prohibited as they are reserved for use with UTF-16 // surrogate pairs. // Determine the length of the UTF-8 sequence. octet := parser.raw_buffer[parser.raw_buffer_pos] switch { case octet&0x80 == 0x00: width = 1 case octet&0xE0 == 0xC0: width = 2 case octet&0xF0 == 0xE0: width = 3 case octet&0xF8 == 0xF0: width = 4 default: // The leading octet is invalid. return yaml_parser_set_reader_error(parser, "invalid leading UTF-8 octet", parser.offset, int(octet)) } // Check if the raw buffer contains an incomplete character. if width > raw_unread { if parser.eof { return yaml_parser_set_reader_error(parser, "incomplete UTF-8 octet sequence", parser.offset, -1) } break inner } // Decode the leading octet. switch { case octet&0x80 == 0x00: value = rune(octet & 0x7F) case octet&0xE0 == 0xC0: value = rune(octet & 0x1F) case octet&0xF0 == 0xE0: value = rune(octet & 0x0F) case octet&0xF8 == 0xF0: value = rune(octet & 0x07) default: value = 0 } // Check and decode the trailing octets. for k := 1; k < width; k++ { octet = parser.raw_buffer[parser.raw_buffer_pos+k] // Check if the octet is valid. if (octet & 0xC0) != 0x80 { return yaml_parser_set_reader_error(parser, "invalid trailing UTF-8 octet", parser.offset+k, int(octet)) } // Decode the octet. value = (value << 6) + rune(octet&0x3F) } // Check the length of the sequence against the value. switch { case width == 1: case width == 2 && value >= 0x80: case width == 3 && value >= 0x800: case width == 4 && value >= 0x10000: default: return yaml_parser_set_reader_error(parser, "invalid length of a UTF-8 sequence", parser.offset, -1) } // Check the range of the value. if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { return yaml_parser_set_reader_error(parser, "invalid Unicode character", parser.offset, int(value)) } case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: var low, high int if parser.encoding == yaml_UTF16LE_ENCODING { low, high = 0, 1 } else { low, high = 1, 0 } // The UTF-16 encoding is not as simple as one might // naively think. Check RFC 2781 // (http://www.ietf.org/rfc/rfc2781.txt). // // Normally, two subsequent bytes describe a Unicode // character. However a special technique (called a // surrogate pair) is used for specifying character // values larger than 0xFFFF. // // A surrogate pair consists of two pseudo-characters: // high surrogate area (0xD800-0xDBFF) // low surrogate area (0xDC00-0xDFFF) // // The following formulas are used for decoding // and encoding characters using surrogate pairs: // // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) // W1 = 110110yyyyyyyyyy // W2 = 110111xxxxxxxxxx // // where U is the character value, W1 is the high surrogate // area, W2 is the low surrogate area. // Check for incomplete UTF-16 character. if raw_unread < 2 { if parser.eof { return yaml_parser_set_reader_error(parser, "incomplete UTF-16 character", parser.offset, -1) } break inner } // Get the character. value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) // Check for unexpected low surrogate area. if value&0xFC00 == 0xDC00 { return yaml_parser_set_reader_error(parser, "unexpected low surrogate area", parser.offset, int(value)) } // Check for a high surrogate area. if value&0xFC00 == 0xD800 { width = 4 // Check for incomplete surrogate pair. if raw_unread < 4 { if parser.eof { return yaml_parser_set_reader_error(parser, "incomplete UTF-16 surrogate pair", parser.offset, -1) } break inner } // Get the next character. value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) // Check for a low surrogate area. if value2&0xFC00 != 0xDC00 { return yaml_parser_set_reader_error(parser, "expected low surrogate area", parser.offset+2, int(value2)) } // Generate the value of the surrogate pair. value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) } else { width = 2 } default: panic("impossible") } // Check if the character is in the allowed range: // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) // | [#x10000-#x10FFFF] (32 bit) switch { case value == 0x09: case value == 0x0A: case value == 0x0D: case value >= 0x20 && value <= 0x7E: case value == 0x85: case value >= 0xA0 && value <= 0xD7FF: case value >= 0xE000 && value <= 0xFFFD: case value >= 0x10000 && value <= 0x10FFFF: default: return yaml_parser_set_reader_error(parser, "control characters are not allowed", parser.offset, int(value)) } // Move the raw pointers. parser.raw_buffer_pos += width parser.offset += width // Finally put the character into the buffer. if value <= 0x7F { // 0000 0000-0000 007F . 0xxxxxxx parser.buffer[buffer_len+0] = byte(value) buffer_len += 1 } else if value <= 0x7FF { // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) buffer_len += 2 } else if value <= 0xFFFF { // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) buffer_len += 3 } else { // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) buffer_len += 4 } parser.unread++ } // On EOF, put NUL into the buffer and return. if parser.eof { parser.buffer[buffer_len] = 0 buffer_len++ parser.unread++ break } } parser.buffer = parser.buffer[:buffer_len] return true }
dep/vendor/gopkg.in/yaml.v2/readerc.go/0
{ "file_path": "dep/vendor/gopkg.in/yaml.v2/readerc.go", "repo_id": "dep", "token_count": 5042 }
49
const React = require('react'); const CompLibrary = require('../../core/CompLibrary.js'); const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */ const Container = CompLibrary.Container; const GridBlock = CompLibrary.GridBlock; const siteConfig = require(process.cwd() + '/siteConfig.js'); class Button extends React.Component { render() { return ( <div className="pluginWrapper buttonWrapper"> <a className="button" href={this.props.href} target={this.props.target}> {this.props.children} </a> </div> ); } } function assetUrl(img) { return siteConfig.baseUrl + 'docs/assets/' + img; } function docUrl(doc, language) { return siteConfig.baseUrl + 'docs/' + (language ? language + '/' : '') + doc; } Button.defaultProps = { target: '_self', }; const SplashContainer = props => ( <div className="homeContainer"> <div className="homeSplashFade"> <div className="wrapper homeWrapper">{props.children}</div> </div> </div> ); const Logo = props => ( <div className="projectLogo"> <img src={props.img_src} /> </div> ); const ProjectTitle = props => ( <h2 className="projectTitle"> {siteConfig.title} <small>{siteConfig.tagline}</small> </h2> ); const PromoSection = props => ( <div className="section promoSection"> <div className="promoRow"> <div className="pluginRowBlock">{props.children}</div> </div> </div> ); class HomeSplash extends React.Component { render() { let language = this.props.language || ''; return ( <SplashContainer> <Logo img_src={assetUrl('DigbyShadows.svg')} /> <div className="inner"> <ProjectTitle /> <PromoSection> <Button href={docUrl('introduction.html', language)}>Docs</Button> <Button href={siteConfig.baseUrl + 'blog'}>Blog</Button> <Button href='https://github.com/golang/dep'>Code</Button> </PromoSection> </div> </SplashContainer> ); } } class Index extends React.Component { render() { let language = this.props.language || ''; return ( <HomeSplash language={language} /> ); } } module.exports = Index;
dep/website/pages/en/index.js/0
{ "file_path": "dep/website/pages/en/index.js", "repo_id": "dep", "token_count": 871 }
50
//go:generate bash -c "go run ../internal/cmd/weave/weave.go ./go-types.md > README.md" package gotypes
example/gotypes/gen.go/0
{ "file_path": "example/gotypes/gen.go", "repo_id": "example", "token_count": 42 }
51
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Hello is a simple hello, world demonstration web server. // // It serves version information on /version and answers // any other request like /name by saying "Hello, name!". // // See golang.org/x/example/outyet for a more sophisticated server. package main import ( "flag" "fmt" "html" "log" "net/http" "os" "runtime/debug" "strings" ) func usage() { fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n") flag.PrintDefaults() os.Exit(2) } var ( greeting = flag.String("g", "Hello", "Greet with `greeting`") addr = flag.String("addr", "localhost:8080", "address to serve") ) func main() { // Parse flags. flag.Usage = usage flag.Parse() // Parse and validate arguments (none). args := flag.Args() if len(args) != 0 { usage() } // Register handlers. // All requests not otherwise mapped with go to greet. // /version is mapped specifically to version. http.HandleFunc("/", greet) http.HandleFunc("/version", version) log.Printf("serving http://%s\n", *addr) log.Fatal(http.ListenAndServe(*addr, nil)) } func version(w http.ResponseWriter, r *http.Request) { info, ok := debug.ReadBuildInfo() if !ok { http.Error(w, "no build information available", 500) return } fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n") fmt.Fprintf(w, "%s\n", html.EscapeString(info.String())) } func greet(w http.ResponseWriter, r *http.Request) { name := strings.Trim(r.URL.Path, "/") if name == "" { name = "Gopher" } fmt.Fprintf(w, "<!DOCTYPE html>\n") fmt.Fprintf(w, "%s, %s!\n", *greeting, html.EscapeString(name)) }
example/helloserver/server.go/0
{ "file_path": "example/helloserver/server.go", "repo_id": "example", "token_count": 645 }
52
# glog [![PkgGoDev](https://pkg.go.dev/badge/github.com/golang/glog)](https://pkg.go.dev/github.com/golang/glog) Leveled execution logs for Go. This is an efficient pure Go implementation of leveled logs in the manner of the open source C++ package [_glog_](https://github.com/google/glog). By binding methods to booleans it is possible to use the log package without paying the expense of evaluating the arguments to the log. Through the `-vmodule` flag, the package also provides fine-grained control over logging at the file level. The comment from `glog.go` introduces the ideas: Package _glog_ implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. It provides the functions Info, Warning, Error, Fatal, plus formatting variants such as Infof. It also provides V-style loggingcontrolled by the `-v` and `-vmodule=file=2` flags. Basic examples: ```go glog.Info("Prepare to repel boarders") glog.Fatalf("Initialization failed: %s", err) ``` See the documentation for the V function for an explanation of these examples: ```go if glog.V(2) { glog.Info("Starting transaction...") } glog.V(2).Infoln("Processed", nItems, "elements") ``` The repository contains an open source version of the log package used inside Google. The master copy of the source lives inside Google, not here. The code in this repo is for export only and is not itself under development. Feature requests will be ignored. Send bug reports to golang-nuts@googlegroups.com.
glog/README.md/0
{ "file_path": "glog/README.md", "repo_id": "glog", "token_count": 433 }
53
package logsink import ( "sync/atomic" "unsafe" ) func fatalMessageStore(e savedEntry) { // Only put a new one in if we haven't assigned before. atomic.CompareAndSwapPointer(&fatalMessage, nil, unsafe.Pointer(&e)) } var fatalMessage unsafe.Pointer // savedEntry stored with CompareAndSwapPointer // FatalMessage returns the Meta and message contents of the first message // logged with Fatal severity, or false if none has occurred. func FatalMessage() (*Meta, []byte, bool) { e := (*savedEntry)(atomic.LoadPointer(&fatalMessage)) if e == nil { return nil, nil, false } return e.meta, e.msg, true } // DoNotUseRacyFatalMessage is FatalMessage, but worse. // //go:norace //go:nosplit func DoNotUseRacyFatalMessage() (*Meta, []byte, bool) { e := (*savedEntry)(fatalMessage) if e == nil { return nil, nil, false } return e.meta, e.msg, true }
glog/internal/logsink/logsink_fatal.go/0
{ "file_path": "glog/internal/logsink/logsink_fatal.go", "repo_id": "glog", "token_count": 291 }
54
<!-- NOTE: In this document and others in this directory, the convention is to set fixed-width phrases with non-fixed-width spaces, as in `hello` `world`. --> <style> main ul li { margin: 0.5em 0; } </style> ## DRAFT RELEASE NOTES — Introduction to Go 1.N {#introduction} **Go 1.N is not yet released. These are work-in-progress release notes. Go 1.N is expected to be released in {Month} {Year}.**
go/doc/initial/1-intro.md/0
{ "file_path": "go/doc/initial/1-intro.md", "repo_id": "go", "token_count": 128 }
55
API changes and other small changes to the standard library go here.
go/doc/next/6-stdlib/99-minor/README/0
{ "file_path": "go/doc/next/6-stdlib/99-minor/README", "repo_id": "go", "token_count": 14 }
56
<html> <!-- Copyright 2011 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <head> <script src="gopher.js"></script> <script src="popup.js"></script> </head> <body style='margin: 0.5em; font-family: sans;'> <small><a href="#" url="https://golang.org/issue">issue</a>, <a href="#" url="https://golang.org/cl">codereview</a>, <a href="#" url="https://golang.org/change">commit</a>, or <a href="#" url="https://golang.org/pkg/">pkg</a> id/name:</small> <form style='margin: 0' id='navform'><nobr><input id="inputbox" size=10 tabindex=1 /><input type="submit" value="go" /></nobr></form> <small>Also: <a href="#" url="https://build.golang.org">buildbots</a> <a href="#" url="https://github.com/golang/go">GitHub</a> </small> </body> </html>
go/misc/chrome/gophertool/popup.html/0
{ "file_path": "go/misc/chrome/gophertool/popup.html", "repo_id": "go", "token_count": 313 }
57
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. "use strict"; if (process.argv.length < 3) { console.error("usage: go_js_wasm_exec [wasm binary] [arguments]"); process.exit(1); } globalThis.require = require; globalThis.fs = require("fs"); globalThis.TextEncoder = require("util").TextEncoder; globalThis.TextDecoder = require("util").TextDecoder; globalThis.performance ??= require("performance"); globalThis.crypto ??= require("crypto"); require("./wasm_exec"); const go = new Go(); go.argv = process.argv.slice(2); go.env = Object.assign({ TMPDIR: require("os").tmpdir() }, process.env); go.exit = process.exit; WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => { process.on("exit", (code) => { // Node.js exits if no event handler is pending if (code === 0 && !go.exited) { // deadlock, make Go print error and stack traces go._pendingEvent = { id: 0 }; go._resume(); } }); return go.run(result.instance); }).catch((err) => { console.error(err); process.exit(1); });
go/misc/wasm/wasm_exec_node.js/0
{ "file_path": "go/misc/wasm/wasm_exec_node.js", "repo_id": "go", "token_count": 398 }
58
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tar import ( "math" "strings" "testing" "time" ) func TestFitsInBase256(t *testing.T) { vectors := []struct { in int64 width int ok bool }{ {+1, 8, true}, {0, 8, true}, {-1, 8, true}, {1 << 56, 8, false}, {(1 << 56) - 1, 8, true}, {-1 << 56, 8, true}, {(-1 << 56) - 1, 8, false}, {121654, 8, true}, {-9849849, 8, true}, {math.MaxInt64, 9, true}, {0, 9, true}, {math.MinInt64, 9, true}, {math.MaxInt64, 12, true}, {0, 12, true}, {math.MinInt64, 12, true}, } for _, v := range vectors { ok := fitsInBase256(v.width, v.in) if ok != v.ok { t.Errorf("fitsInBase256(%d, %d): got %v, want %v", v.in, v.width, ok, v.ok) } } } func TestParseNumeric(t *testing.T) { vectors := []struct { in string want int64 ok bool }{ // Test base-256 (binary) encoded values. {"", 0, true}, {"\x80", 0, true}, {"\x80\x00", 0, true}, {"\x80\x00\x00", 0, true}, {"\xbf", (1 << 6) - 1, true}, {"\xbf\xff", (1 << 14) - 1, true}, {"\xbf\xff\xff", (1 << 22) - 1, true}, {"\xff", -1, true}, {"\xff\xff", -1, true}, {"\xff\xff\xff", -1, true}, {"\xc0", -1 * (1 << 6), true}, {"\xc0\x00", -1 * (1 << 14), true}, {"\xc0\x00\x00", -1 * (1 << 22), true}, {"\x87\x76\xa2\x22\xeb\x8a\x72\x61", 537795476381659745, true}, {"\x80\x00\x00\x00\x07\x76\xa2\x22\xeb\x8a\x72\x61", 537795476381659745, true}, {"\xf7\x76\xa2\x22\xeb\x8a\x72\x61", -615126028225187231, true}, {"\xff\xff\xff\xff\xf7\x76\xa2\x22\xeb\x8a\x72\x61", -615126028225187231, true}, {"\x80\x7f\xff\xff\xff\xff\xff\xff\xff", math.MaxInt64, true}, {"\x80\x80\x00\x00\x00\x00\x00\x00\x00", 0, false}, {"\xff\x80\x00\x00\x00\x00\x00\x00\x00", math.MinInt64, true}, {"\xff\x7f\xff\xff\xff\xff\xff\xff\xff", 0, false}, {"\xf5\xec\xd1\xc7\x7e\x5f\x26\x48\x81\x9f\x8f\x9b", 0, false}, // Test base-8 (octal) encoded values. {"0000000\x00", 0, true}, {" \x0000000\x00", 0, true}, {" \x0000003\x00", 3, true}, {"00000000227\x00", 0227, true}, {"032033\x00 ", 032033, true}, {"320330\x00 ", 0320330, true}, {"0000660\x00 ", 0660, true}, {"\x00 0000660\x00 ", 0660, true}, {"0123456789abcdef", 0, false}, {"0123456789\x00abcdef", 0, false}, {"01234567\x0089abcdef", 342391, true}, {"0123\x7e\x5f\x264123", 0, false}, } for _, v := range vectors { var p parser got := p.parseNumeric([]byte(v.in)) ok := (p.err == nil) if ok != v.ok { if v.ok { t.Errorf("parseNumeric(%q): got parsing failure, want success", v.in) } else { t.Errorf("parseNumeric(%q): got parsing success, want failure", v.in) } } if ok && got != v.want { t.Errorf("parseNumeric(%q): got %d, want %d", v.in, got, v.want) } } } func TestFormatNumeric(t *testing.T) { vectors := []struct { in int64 want string ok bool }{ // Test base-8 (octal) encoded values. {0, "0\x00", true}, {7, "7\x00", true}, {8, "\x80\x08", true}, {077, "77\x00", true}, {0100, "\x80\x00\x40", true}, {0, "0000000\x00", true}, {0123, "0000123\x00", true}, {07654321, "7654321\x00", true}, {07777777, "7777777\x00", true}, {010000000, "\x80\x00\x00\x00\x00\x20\x00\x00", true}, {0, "00000000000\x00", true}, {000001234567, "00001234567\x00", true}, {076543210321, "76543210321\x00", true}, {012345670123, "12345670123\x00", true}, {077777777777, "77777777777\x00", true}, {0100000000000, "\x80\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00", true}, {math.MaxInt64, "777777777777777777777\x00", true}, // Test base-256 (binary) encoded values. {-1, "\xff", true}, {-1, "\xff\xff", true}, {-1, "\xff\xff\xff", true}, {(1 << 0), "0", false}, {(1 << 8) - 1, "\x80\xff", true}, {(1 << 8), "0\x00", false}, {(1 << 16) - 1, "\x80\xff\xff", true}, {(1 << 16), "00\x00", false}, {-1 * (1 << 0), "\xff", true}, {-1*(1<<0) - 1, "0", false}, {-1 * (1 << 8), "\xff\x00", true}, {-1*(1<<8) - 1, "0\x00", false}, {-1 * (1 << 16), "\xff\x00\x00", true}, {-1*(1<<16) - 1, "00\x00", false}, {537795476381659745, "0000000\x00", false}, {537795476381659745, "\x80\x00\x00\x00\x07\x76\xa2\x22\xeb\x8a\x72\x61", true}, {-615126028225187231, "0000000\x00", false}, {-615126028225187231, "\xff\xff\xff\xff\xf7\x76\xa2\x22\xeb\x8a\x72\x61", true}, {math.MaxInt64, "0000000\x00", false}, {math.MaxInt64, "\x80\x00\x00\x00\x7f\xff\xff\xff\xff\xff\xff\xff", true}, {math.MinInt64, "0000000\x00", false}, {math.MinInt64, "\xff\xff\xff\xff\x80\x00\x00\x00\x00\x00\x00\x00", true}, {math.MaxInt64, "\x80\x7f\xff\xff\xff\xff\xff\xff\xff", true}, {math.MinInt64, "\xff\x80\x00\x00\x00\x00\x00\x00\x00", true}, } for _, v := range vectors { var f formatter got := make([]byte, len(v.want)) f.formatNumeric(got, v.in) ok := (f.err == nil) if ok != v.ok { if v.ok { t.Errorf("formatNumeric(%d): got formatting failure, want success", v.in) } else { t.Errorf("formatNumeric(%d): got formatting success, want failure", v.in) } } if string(got) != v.want { t.Errorf("formatNumeric(%d): got %q, want %q", v.in, got, v.want) } } } func TestFitsInOctal(t *testing.T) { vectors := []struct { input int64 width int ok bool }{ {-1, 1, false}, {-1, 2, false}, {-1, 3, false}, {0, 1, true}, {0 + 1, 1, false}, {0, 2, true}, {07, 2, true}, {07 + 1, 2, false}, {0, 4, true}, {0777, 4, true}, {0777 + 1, 4, false}, {0, 8, true}, {07777777, 8, true}, {07777777 + 1, 8, false}, {0, 12, true}, {077777777777, 12, true}, {077777777777 + 1, 12, false}, {math.MaxInt64, 22, true}, {012345670123, 12, true}, {01564164, 12, true}, {-012345670123, 12, false}, {-01564164, 12, false}, {-1564164, 30, false}, } for _, v := range vectors { ok := fitsInOctal(v.width, v.input) if ok != v.ok { t.Errorf("checkOctal(%d, %d): got %v, want %v", v.input, v.width, ok, v.ok) } } } func TestParsePAXTime(t *testing.T) { vectors := []struct { in string want time.Time ok bool }{ {"1350244992.023960108", time.Unix(1350244992, 23960108), true}, {"1350244992.02396010", time.Unix(1350244992, 23960100), true}, {"1350244992.0239601089", time.Unix(1350244992, 23960108), true}, {"1350244992.3", time.Unix(1350244992, 300000000), true}, {"1350244992", time.Unix(1350244992, 0), true}, {"-1.000000001", time.Unix(-1, -1e0+0e0), true}, {"-1.000001", time.Unix(-1, -1e3+0e0), true}, {"-1.001000", time.Unix(-1, -1e6+0e0), true}, {"-1", time.Unix(-1, -0e0+0e0), true}, {"-1.999000", time.Unix(-1, -1e9+1e6), true}, {"-1.999999", time.Unix(-1, -1e9+1e3), true}, {"-1.999999999", time.Unix(-1, -1e9+1e0), true}, {"0.000000001", time.Unix(0, 1e0+0e0), true}, {"0.000001", time.Unix(0, 1e3+0e0), true}, {"0.001000", time.Unix(0, 1e6+0e0), true}, {"0", time.Unix(0, 0e0), true}, {"0.999000", time.Unix(0, 1e9-1e6), true}, {"0.999999", time.Unix(0, 1e9-1e3), true}, {"0.999999999", time.Unix(0, 1e9-1e0), true}, {"1.000000001", time.Unix(+1, +1e0-0e0), true}, {"1.000001", time.Unix(+1, +1e3-0e0), true}, {"1.001000", time.Unix(+1, +1e6-0e0), true}, {"1", time.Unix(+1, +0e0-0e0), true}, {"1.999000", time.Unix(+1, +1e9-1e6), true}, {"1.999999", time.Unix(+1, +1e9-1e3), true}, {"1.999999999", time.Unix(+1, +1e9-1e0), true}, {"-1350244992.023960108", time.Unix(-1350244992, -23960108), true}, {"-1350244992.02396010", time.Unix(-1350244992, -23960100), true}, {"-1350244992.0239601089", time.Unix(-1350244992, -23960108), true}, {"-1350244992.3", time.Unix(-1350244992, -300000000), true}, {"-1350244992", time.Unix(-1350244992, 0), true}, {"", time.Time{}, false}, {"0", time.Unix(0, 0), true}, {"1.", time.Unix(1, 0), true}, {"0.0", time.Unix(0, 0), true}, {".5", time.Time{}, false}, {"-1.3", time.Unix(-1, -3e8), true}, {"-1.0", time.Unix(-1, -0e0), true}, {"-0.0", time.Unix(-0, -0e0), true}, {"-0.1", time.Unix(-0, -1e8), true}, {"-0.01", time.Unix(-0, -1e7), true}, {"-0.99", time.Unix(-0, -99e7), true}, {"-0.98", time.Unix(-0, -98e7), true}, {"-1.1", time.Unix(-1, -1e8), true}, {"-1.01", time.Unix(-1, -1e7), true}, {"-2.99", time.Unix(-2, -99e7), true}, {"-5.98", time.Unix(-5, -98e7), true}, {"-", time.Time{}, false}, {"+", time.Time{}, false}, {"-1.-1", time.Time{}, false}, {"99999999999999999999999999999999999999999999999", time.Time{}, false}, {"0.123456789abcdef", time.Time{}, false}, {"foo", time.Time{}, false}, {"\x00", time.Time{}, false}, {"𝟵𝟴𝟳𝟲𝟱.𝟰𝟯𝟮𝟭𝟬", time.Time{}, false}, // Unicode numbers (U+1D7EC to U+1D7F5) {"98765﹒43210", time.Time{}, false}, // Unicode period (U+FE52) } for _, v := range vectors { ts, err := parsePAXTime(v.in) ok := (err == nil) if v.ok != ok { if v.ok { t.Errorf("parsePAXTime(%q): got parsing failure, want success", v.in) } else { t.Errorf("parsePAXTime(%q): got parsing success, want failure", v.in) } } if ok && !ts.Equal(v.want) { t.Errorf("parsePAXTime(%q): got (%ds %dns), want (%ds %dns)", v.in, ts.Unix(), ts.Nanosecond(), v.want.Unix(), v.want.Nanosecond()) } } } func TestFormatPAXTime(t *testing.T) { vectors := []struct { sec, nsec int64 want string }{ {1350244992, 0, "1350244992"}, {1350244992, 300000000, "1350244992.3"}, {1350244992, 23960100, "1350244992.0239601"}, {1350244992, 23960108, "1350244992.023960108"}, {+1, +1e9 - 1e0, "1.999999999"}, {+1, +1e9 - 1e3, "1.999999"}, {+1, +1e9 - 1e6, "1.999"}, {+1, +0e0 - 0e0, "1"}, {+1, +1e6 - 0e0, "1.001"}, {+1, +1e3 - 0e0, "1.000001"}, {+1, +1e0 - 0e0, "1.000000001"}, {0, 1e9 - 1e0, "0.999999999"}, {0, 1e9 - 1e3, "0.999999"}, {0, 1e9 - 1e6, "0.999"}, {0, 0e0, "0"}, {0, 1e6 + 0e0, "0.001"}, {0, 1e3 + 0e0, "0.000001"}, {0, 1e0 + 0e0, "0.000000001"}, {-1, -1e9 + 1e0, "-1.999999999"}, {-1, -1e9 + 1e3, "-1.999999"}, {-1, -1e9 + 1e6, "-1.999"}, {-1, -0e0 + 0e0, "-1"}, {-1, -1e6 + 0e0, "-1.001"}, {-1, -1e3 + 0e0, "-1.000001"}, {-1, -1e0 + 0e0, "-1.000000001"}, {-1350244992, 0, "-1350244992"}, {-1350244992, -300000000, "-1350244992.3"}, {-1350244992, -23960100, "-1350244992.0239601"}, {-1350244992, -23960108, "-1350244992.023960108"}, } for _, v := range vectors { got := formatPAXTime(time.Unix(v.sec, v.nsec)) if got != v.want { t.Errorf("formatPAXTime(%ds, %dns): got %q, want %q", v.sec, v.nsec, got, v.want) } } } func TestParsePAXRecord(t *testing.T) { medName := strings.Repeat("CD", 50) longName := strings.Repeat("AB", 100) vectors := []struct { in string wantRes string wantKey string wantVal string ok bool }{ {"6 k=v\n\n", "\n", "k", "v", true}, {"19 path=/etc/hosts\n", "", "path", "/etc/hosts", true}, {"210 path=" + longName + "\nabc", "abc", "path", longName, true}, {"110 path=" + medName + "\n", "", "path", medName, true}, {"9 foo=ba\n", "", "foo", "ba", true}, {"11 foo=bar\n\x00", "\x00", "foo", "bar", true}, {"18 foo=b=\nar=\n==\x00\n", "", "foo", "b=\nar=\n==\x00", true}, {"27 foo=hello9 foo=ba\nworld\n", "", "foo", "hello9 foo=ba\nworld", true}, {"27 ☺☻☹=日a本b語ç\nmeow mix", "meow mix", "☺☻☹", "日a本b語ç", true}, {"17 \x00hello=\x00world\n", "17 \x00hello=\x00world\n", "", "", false}, {"1 k=1\n", "1 k=1\n", "", "", false}, {"6 k~1\n", "6 k~1\n", "", "", false}, {"6_k=1\n", "6_k=1\n", "", "", false}, {"6 k=1 ", "6 k=1 ", "", "", false}, {"632 k=1\n", "632 k=1\n", "", "", false}, {"16 longkeyname=hahaha\n", "16 longkeyname=hahaha\n", "", "", false}, {"3 somelongkey=\n", "3 somelongkey=\n", "", "", false}, {"50 tooshort=\n", "50 tooshort=\n", "", "", false}, {"0000000000000000000000000000000030 mtime=1432668921.098285006\n30 ctime=2147483649.15163319", "0000000000000000000000000000000030 mtime=1432668921.098285006\n30 ctime=2147483649.15163319", "mtime", "1432668921.098285006", false}, {"06 k=v\n", "06 k=v\n", "", "", false}, {"00006 k=v\n", "00006 k=v\n", "", "", false}, {"000006 k=v\n", "000006 k=v\n", "", "", false}, {"000000 k=v\n", "000000 k=v\n", "", "", false}, {"0 k=v\n", "0 k=v\n", "", "", false}, {"+0000005 x=\n", "+0000005 x=\n", "", "", false}, } for _, v := range vectors { key, val, res, err := parsePAXRecord(v.in) ok := (err == nil) if ok != v.ok { if v.ok { t.Errorf("parsePAXRecord(%q): got parsing failure, want success", v.in) } else { t.Errorf("parsePAXRecord(%q): got parsing success, want failure", v.in) } } if v.ok && (key != v.wantKey || val != v.wantVal) { t.Errorf("parsePAXRecord(%q): got (%q: %q), want (%q: %q)", v.in, key, val, v.wantKey, v.wantVal) } if res != v.wantRes { t.Errorf("parsePAXRecord(%q): got residual %q, want residual %q", v.in, res, v.wantRes) } } } func TestFormatPAXRecord(t *testing.T) { medName := strings.Repeat("CD", 50) longName := strings.Repeat("AB", 100) vectors := []struct { inKey string inVal string want string ok bool }{ {"k", "v", "6 k=v\n", true}, {"path", "/etc/hosts", "19 path=/etc/hosts\n", true}, {"path", longName, "210 path=" + longName + "\n", true}, {"path", medName, "110 path=" + medName + "\n", true}, {"foo", "ba", "9 foo=ba\n", true}, {"foo", "bar", "11 foo=bar\n", true}, {"foo", "b=\nar=\n==\x00", "18 foo=b=\nar=\n==\x00\n", true}, {"foo", "hello9 foo=ba\nworld", "27 foo=hello9 foo=ba\nworld\n", true}, {"☺☻☹", "日a本b語ç", "27 ☺☻☹=日a本b語ç\n", true}, {"xhello", "\x00world", "17 xhello=\x00world\n", true}, {"path", "null\x00", "", false}, {"null\x00", "value", "", false}, {paxSchilyXattr + "key", "null\x00", "26 SCHILY.xattr.key=null\x00\n", true}, } for _, v := range vectors { got, err := formatPAXRecord(v.inKey, v.inVal) ok := (err == nil) if ok != v.ok { if v.ok { t.Errorf("formatPAXRecord(%q, %q): got format failure, want success", v.inKey, v.inVal) } else { t.Errorf("formatPAXRecord(%q, %q): got format success, want failure", v.inKey, v.inVal) } } if got != v.want { t.Errorf("formatPAXRecord(%q, %q): got %q, want %q", v.inKey, v.inVal, got, v.want) } } }
go/src/archive/tar/strconv_test.go/0
{ "file_path": "go/src/archive/tar/strconv_test.go", "repo_id": "go", "token_count": 7291 }
59
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package tar import ( "bytes" "encoding/hex" "errors" "io" "io/fs" "maps" "os" "path" "slices" "strings" "testing" "testing/fstest" "testing/iotest" "time" ) func bytediff(a, b []byte) string { const ( uniqueA = "- " uniqueB = "+ " identity = " " ) var ss []string sa := strings.Split(strings.TrimSpace(hex.Dump(a)), "\n") sb := strings.Split(strings.TrimSpace(hex.Dump(b)), "\n") for len(sa) > 0 && len(sb) > 0 { if sa[0] == sb[0] { ss = append(ss, identity+sa[0]) } else { ss = append(ss, uniqueA+sa[0]) ss = append(ss, uniqueB+sb[0]) } sa, sb = sa[1:], sb[1:] } for len(sa) > 0 { ss = append(ss, uniqueA+sa[0]) sa = sa[1:] } for len(sb) > 0 { ss = append(ss, uniqueB+sb[0]) sb = sb[1:] } return strings.Join(ss, "\n") } func TestWriter(t *testing.T) { type ( testHeader struct { // WriteHeader(hdr) == wantErr hdr Header wantErr error } testWrite struct { // Write(str) == (wantCnt, wantErr) str string wantCnt int wantErr error } testReadFrom struct { // ReadFrom(testFile{ops}) == (wantCnt, wantErr) ops fileOps wantCnt int64 wantErr error } testClose struct { // Close() == wantErr wantErr error } testFnc any // testHeader | testWrite | testReadFrom | testClose ) vectors := []struct { file string // Optional filename of expected output tests []testFnc }{{ // The writer test file was produced with this command: // tar (GNU tar) 1.26 // ln -s small.txt link.txt // tar -b 1 --format=ustar -c -f writer.tar small.txt small2.txt link.txt file: "testdata/writer.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "small.txt", Size: 5, Mode: 0640, Uid: 73025, Gid: 5000, Uname: "dsymonds", Gname: "eng", ModTime: time.Unix(1246508266, 0), }, nil}, testWrite{"Kilts", 5, nil}, testHeader{Header{ Typeflag: TypeReg, Name: "small2.txt", Size: 11, Mode: 0640, Uid: 73025, Uname: "dsymonds", Gname: "eng", Gid: 5000, ModTime: time.Unix(1245217492, 0), }, nil}, testWrite{"Google.com\n", 11, nil}, testHeader{Header{ Typeflag: TypeSymlink, Name: "link.txt", Linkname: "small.txt", Mode: 0777, Uid: 1000, Gid: 1000, Uname: "strings", Gname: "strings", ModTime: time.Unix(1314603082, 0), }, nil}, testWrite{"", 0, nil}, testClose{nil}, }, }, { // The truncated test file was produced using these commands: // dd if=/dev/zero bs=1048576 count=16384 > /tmp/16gig.txt // tar -b 1 -c -f- /tmp/16gig.txt | dd bs=512 count=8 > writer-big.tar file: "testdata/writer-big.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "tmp/16gig.txt", Size: 16 << 30, Mode: 0640, Uid: 73025, Gid: 5000, Uname: "dsymonds", Gname: "eng", ModTime: time.Unix(1254699560, 0), Format: FormatGNU, }, nil}, }, }, { // This truncated file was produced using this library. // It was verified to work with GNU tar 1.27.1 and BSD tar 3.1.2. // dd if=/dev/zero bs=1G count=16 >> writer-big-long.tar // gnutar -xvf writer-big-long.tar // bsdtar -xvf writer-big-long.tar // // This file is in PAX format. file: "testdata/writer-big-long.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: strings.Repeat("longname/", 15) + "16gig.txt", Size: 16 << 30, Mode: 0644, Uid: 1000, Gid: 1000, Uname: "guillaume", Gname: "guillaume", ModTime: time.Unix(1399583047, 0), }, nil}, }, }, { // This file was produced using GNU tar v1.17. // gnutar -b 4 --format=ustar (longname/)*15 + file.txt file: "testdata/ustar.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: strings.Repeat("longname/", 15) + "file.txt", Size: 6, Mode: 0644, Uid: 501, Gid: 20, Uname: "shane", Gname: "staff", ModTime: time.Unix(1360135598, 0), }, nil}, testWrite{"hello\n", 6, nil}, testClose{nil}, }, }, { // This file was produced using GNU tar v1.26: // echo "Slartibartfast" > file.txt // ln file.txt hard.txt // tar -b 1 --format=ustar -c -f hardlink.tar file.txt hard.txt file: "testdata/hardlink.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "file.txt", Size: 15, Mode: 0644, Uid: 1000, Gid: 100, Uname: "vbatts", Gname: "users", ModTime: time.Unix(1425484303, 0), }, nil}, testWrite{"Slartibartfast\n", 15, nil}, testHeader{Header{ Typeflag: TypeLink, Name: "hard.txt", Linkname: "file.txt", Mode: 0644, Uid: 1000, Gid: 100, Uname: "vbatts", Gname: "users", ModTime: time.Unix(1425484303, 0), }, nil}, testWrite{"", 0, nil}, testClose{nil}, }, }, { tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "bad-null.txt", Xattrs: map[string]string{"null\x00null\x00": "fizzbuzz"}, }, headerError{}}, }, }, { tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "null\x00.txt", }, headerError{}}, }, }, { file: "testdata/pax-records.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "file", Uname: strings.Repeat("long", 10), PAXRecords: map[string]string{ "path": "FILE", // Should be ignored "GNU.sparse.map": "0,0", // Should be ignored "comment": "Hello, 世界", "GOLANG.pkg": "tar", }, }, nil}, testClose{nil}, }, }, { // Craft a theoretically valid PAX archive with global headers. // The GNU and BSD tar tools do not parse these the same way. // // BSD tar v3.1.2 parses and ignores all global headers; // the behavior is verified by researching the source code. // // $ bsdtar -tvf pax-global-records.tar // ---------- 0 0 0 0 Dec 31 1969 file1 // ---------- 0 0 0 0 Dec 31 1969 file2 // ---------- 0 0 0 0 Dec 31 1969 file3 // ---------- 0 0 0 0 May 13 2014 file4 // // GNU tar v1.27.1 applies global headers to subsequent records, // but does not do the following properly: // * It does not treat an empty record as deletion. // * It does not use subsequent global headers to update previous ones. // // $ gnutar -tvf pax-global-records.tar // ---------- 0/0 0 2017-07-13 19:40 global1 // ---------- 0/0 0 2017-07-13 19:40 file2 // gnutar: Substituting `.' for empty member name // ---------- 0/0 0 1969-12-31 16:00 // gnutar: Substituting `.' for empty member name // ---------- 0/0 0 2014-05-13 09:53 // // According to the PAX specification, this should have been the result: // ---------- 0/0 0 2017-07-13 19:40 global1 // ---------- 0/0 0 2017-07-13 19:40 file2 // ---------- 0/0 0 2017-07-13 19:40 file3 // ---------- 0/0 0 2014-05-13 09:53 file4 file: "testdata/pax-global-records.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeXGlobalHeader, PAXRecords: map[string]string{"path": "global1", "mtime": "1500000000.0"}, }, nil}, testHeader{Header{ Typeflag: TypeReg, Name: "file1", }, nil}, testHeader{Header{ Typeflag: TypeReg, Name: "file2", PAXRecords: map[string]string{"path": "file2"}, }, nil}, testHeader{Header{ Typeflag: TypeXGlobalHeader, PAXRecords: map[string]string{"path": ""}, // Should delete "path", but keep "mtime" }, nil}, testHeader{Header{ Typeflag: TypeReg, Name: "file3", }, nil}, testHeader{Header{ Typeflag: TypeReg, Name: "file4", ModTime: time.Unix(1400000000, 0), PAXRecords: map[string]string{"mtime": "1400000000"}, }, nil}, testClose{nil}, }, }, { file: "testdata/gnu-utf8.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹☺☻☹", Mode: 0644, Uid: 1000, Gid: 1000, Uname: "☺", Gname: "⚹", ModTime: time.Unix(0, 0), Format: FormatGNU, }, nil}, testClose{nil}, }, }, { file: "testdata/gnu-not-utf8.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "hi\x80\x81\x82\x83bye", Mode: 0644, Uid: 1000, Gid: 1000, Uname: "rawr", Gname: "dsnet", ModTime: time.Unix(0, 0), Format: FormatGNU, }, nil}, testClose{nil}, }, // TODO(dsnet): Re-enable this test when adding sparse support. // See https://golang.org/issue/22735 /* }, { file: "testdata/gnu-nil-sparse-data.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeGNUSparse, Name: "sparse.db", Size: 1000, SparseHoles: []sparseEntry{{Offset: 1000, Length: 0}}, }, nil}, testWrite{strings.Repeat("0123456789", 100), 1000, nil}, testClose{}, }, }, { file: "testdata/gnu-nil-sparse-hole.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeGNUSparse, Name: "sparse.db", Size: 1000, SparseHoles: []sparseEntry{{Offset: 0, Length: 1000}}, }, nil}, testWrite{strings.Repeat("\x00", 1000), 1000, nil}, testClose{}, }, }, { file: "testdata/pax-nil-sparse-data.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "sparse.db", Size: 1000, SparseHoles: []sparseEntry{{Offset: 1000, Length: 0}}, }, nil}, testWrite{strings.Repeat("0123456789", 100), 1000, nil}, testClose{}, }, }, { file: "testdata/pax-nil-sparse-hole.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "sparse.db", Size: 1000, SparseHoles: []sparseEntry{{Offset: 0, Length: 1000}}, }, nil}, testWrite{strings.Repeat("\x00", 1000), 1000, nil}, testClose{}, }, }, { file: "testdata/gnu-sparse-big.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeGNUSparse, Name: "gnu-sparse", Size: 6e10, SparseHoles: []sparseEntry{ {Offset: 0e10, Length: 1e10 - 100}, {Offset: 1e10, Length: 1e10 - 100}, {Offset: 2e10, Length: 1e10 - 100}, {Offset: 3e10, Length: 1e10 - 100}, {Offset: 4e10, Length: 1e10 - 100}, {Offset: 5e10, Length: 1e10 - 100}, }, }, nil}, testReadFrom{fileOps{ int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), }, 6e10, nil}, testClose{nil}, }, }, { file: "testdata/pax-sparse-big.tar", tests: []testFnc{ testHeader{Header{ Typeflag: TypeReg, Name: "pax-sparse", Size: 6e10, SparseHoles: []sparseEntry{ {Offset: 0e10, Length: 1e10 - 100}, {Offset: 1e10, Length: 1e10 - 100}, {Offset: 2e10, Length: 1e10 - 100}, {Offset: 3e10, Length: 1e10 - 100}, {Offset: 4e10, Length: 1e10 - 100}, {Offset: 5e10, Length: 1e10 - 100}, }, }, nil}, testReadFrom{fileOps{ int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), int64(1e10 - blockSize), strings.Repeat("\x00", blockSize-100) + strings.Repeat("0123456789", 10), }, 6e10, nil}, testClose{nil}, }, */ }, { file: "testdata/trailing-slash.tar", tests: []testFnc{ testHeader{Header{Name: strings.Repeat("123456789/", 30)}, nil}, testClose{nil}, }, }, { // Automatically promote zero value of Typeflag depending on the name. file: "testdata/file-and-dir.tar", tests: []testFnc{ testHeader{Header{Name: "small.txt", Size: 5}, nil}, testWrite{"Kilts", 5, nil}, testHeader{Header{Name: "dir/"}, nil}, testClose{nil}, }, }} equalError := func(x, y error) bool { _, ok1 := x.(headerError) _, ok2 := y.(headerError) if ok1 || ok2 { return ok1 && ok2 } return x == y } for _, v := range vectors { t.Run(path.Base(v.file), func(t *testing.T) { const maxSize = 10 << 10 // 10KiB buf := new(bytes.Buffer) tw := NewWriter(iotest.TruncateWriter(buf, maxSize)) for i, tf := range v.tests { switch tf := tf.(type) { case testHeader: err := tw.WriteHeader(&tf.hdr) if !equalError(err, tf.wantErr) { t.Fatalf("test %d, WriteHeader() = %v, want %v", i, err, tf.wantErr) } case testWrite: got, err := tw.Write([]byte(tf.str)) if got != tf.wantCnt || !equalError(err, tf.wantErr) { t.Fatalf("test %d, Write() = (%d, %v), want (%d, %v)", i, got, err, tf.wantCnt, tf.wantErr) } case testReadFrom: f := &testFile{ops: tf.ops} got, err := tw.readFrom(f) if _, ok := err.(testError); ok { t.Errorf("test %d, ReadFrom(): %v", i, err) } else if got != tf.wantCnt || !equalError(err, tf.wantErr) { t.Errorf("test %d, ReadFrom() = (%d, %v), want (%d, %v)", i, got, err, tf.wantCnt, tf.wantErr) } if len(f.ops) > 0 { t.Errorf("test %d, expected %d more operations", i, len(f.ops)) } case testClose: err := tw.Close() if !equalError(err, tf.wantErr) { t.Fatalf("test %d, Close() = %v, want %v", i, err, tf.wantErr) } default: t.Fatalf("test %d, unknown test operation: %T", i, tf) } } if v.file != "" { want, err := os.ReadFile(v.file) if err != nil { t.Fatalf("ReadFile() = %v, want nil", err) } got := buf.Bytes() if !bytes.Equal(want, got) { t.Fatalf("incorrect result: (-got +want)\n%v", bytediff(got, want)) } } }) } } func TestPax(t *testing.T) { // Create an archive with a large name fileinfo, err := os.Stat("testdata/small.txt") if err != nil { t.Fatal(err) } hdr, err := FileInfoHeader(fileinfo, "") if err != nil { t.Fatalf("os.Stat: %v", err) } // Force a PAX long name to be written longName := strings.Repeat("ab", 100) contents := strings.Repeat(" ", int(hdr.Size)) hdr.Name = longName var buf bytes.Buffer writer := NewWriter(&buf) if err := writer.WriteHeader(hdr); err != nil { t.Fatal(err) } if _, err = writer.Write([]byte(contents)); err != nil { t.Fatal(err) } if err := writer.Close(); err != nil { t.Fatal(err) } // Simple test to make sure PAX extensions are in effect if !bytes.Contains(buf.Bytes(), []byte("PaxHeaders.0")) { t.Fatal("Expected at least one PAX header to be written.") } // Test that we can get a long name back out of the archive. reader := NewReader(&buf) hdr, err = reader.Next() if err != nil { t.Fatal(err) } if hdr.Name != longName { t.Fatal("Couldn't recover long file name") } } func TestPaxSymlink(t *testing.T) { // Create an archive with a large linkname fileinfo, err := os.Stat("testdata/small.txt") if err != nil { t.Fatal(err) } hdr, err := FileInfoHeader(fileinfo, "") if err != nil { t.Fatalf("os.Stat:1 %v", err) } hdr.Typeflag = TypeSymlink // Force a PAX long linkname to be written longLinkname := strings.Repeat("1234567890/1234567890", 10) hdr.Linkname = longLinkname hdr.Size = 0 var buf bytes.Buffer writer := NewWriter(&buf) if err := writer.WriteHeader(hdr); err != nil { t.Fatal(err) } if err := writer.Close(); err != nil { t.Fatal(err) } // Simple test to make sure PAX extensions are in effect if !bytes.Contains(buf.Bytes(), []byte("PaxHeaders.0")) { t.Fatal("Expected at least one PAX header to be written.") } // Test that we can get a long name back out of the archive. reader := NewReader(&buf) hdr, err = reader.Next() if err != nil { t.Fatal(err) } if hdr.Linkname != longLinkname { t.Fatal("Couldn't recover long link name") } } func TestPaxNonAscii(t *testing.T) { // Create an archive with non ascii. These should trigger a pax header // because pax headers have a defined utf-8 encoding. fileinfo, err := os.Stat("testdata/small.txt") if err != nil { t.Fatal(err) } hdr, err := FileInfoHeader(fileinfo, "") if err != nil { t.Fatalf("os.Stat:1 %v", err) } // some sample data chineseFilename := "文件名" chineseGroupname := "組" chineseUsername := "用戶名" hdr.Name = chineseFilename hdr.Gname = chineseGroupname hdr.Uname = chineseUsername contents := strings.Repeat(" ", int(hdr.Size)) var buf bytes.Buffer writer := NewWriter(&buf) if err := writer.WriteHeader(hdr); err != nil { t.Fatal(err) } if _, err = writer.Write([]byte(contents)); err != nil { t.Fatal(err) } if err := writer.Close(); err != nil { t.Fatal(err) } // Simple test to make sure PAX extensions are in effect if !bytes.Contains(buf.Bytes(), []byte("PaxHeaders.0")) { t.Fatal("Expected at least one PAX header to be written.") } // Test that we can get a long name back out of the archive. reader := NewReader(&buf) hdr, err = reader.Next() if err != nil { t.Fatal(err) } if hdr.Name != chineseFilename { t.Fatal("Couldn't recover unicode name") } if hdr.Gname != chineseGroupname { t.Fatal("Couldn't recover unicode group") } if hdr.Uname != chineseUsername { t.Fatal("Couldn't recover unicode user") } } func TestPaxXattrs(t *testing.T) { xattrs := map[string]string{ "user.key": "value", } // Create an archive with an xattr fileinfo, err := os.Stat("testdata/small.txt") if err != nil { t.Fatal(err) } hdr, err := FileInfoHeader(fileinfo, "") if err != nil { t.Fatalf("os.Stat: %v", err) } contents := "Kilts" hdr.Xattrs = xattrs var buf bytes.Buffer writer := NewWriter(&buf) if err := writer.WriteHeader(hdr); err != nil { t.Fatal(err) } if _, err = writer.Write([]byte(contents)); err != nil { t.Fatal(err) } if err := writer.Close(); err != nil { t.Fatal(err) } // Test that we can get the xattrs back out of the archive. reader := NewReader(&buf) hdr, err = reader.Next() if err != nil { t.Fatal(err) } if !maps.Equal(hdr.Xattrs, xattrs) { t.Fatalf("xattrs did not survive round trip: got %+v, want %+v", hdr.Xattrs, xattrs) } } func TestPaxHeadersSorted(t *testing.T) { fileinfo, err := os.Stat("testdata/small.txt") if err != nil { t.Fatal(err) } hdr, err := FileInfoHeader(fileinfo, "") if err != nil { t.Fatalf("os.Stat: %v", err) } contents := strings.Repeat(" ", int(hdr.Size)) hdr.Xattrs = map[string]string{ "foo": "foo", "bar": "bar", "baz": "baz", "qux": "qux", } var buf bytes.Buffer writer := NewWriter(&buf) if err := writer.WriteHeader(hdr); err != nil { t.Fatal(err) } if _, err = writer.Write([]byte(contents)); err != nil { t.Fatal(err) } if err := writer.Close(); err != nil { t.Fatal(err) } // Simple test to make sure PAX extensions are in effect if !bytes.Contains(buf.Bytes(), []byte("PaxHeaders.0")) { t.Fatal("Expected at least one PAX header to be written.") } // xattr bar should always appear before others indices := []int{ bytes.Index(buf.Bytes(), []byte("bar=bar")), bytes.Index(buf.Bytes(), []byte("baz=baz")), bytes.Index(buf.Bytes(), []byte("foo=foo")), bytes.Index(buf.Bytes(), []byte("qux=qux")), } if !slices.IsSorted(indices) { t.Fatal("PAX headers are not sorted") } } func TestUSTARLongName(t *testing.T) { // Create an archive with a path that failed to split with USTAR extension in previous versions. fileinfo, err := os.Stat("testdata/small.txt") if err != nil { t.Fatal(err) } hdr, err := FileInfoHeader(fileinfo, "") if err != nil { t.Fatalf("os.Stat:1 %v", err) } hdr.Typeflag = TypeDir // Force a PAX long name to be written. The name was taken from a practical example // that fails and replaced ever char through numbers to anonymize the sample. longName := "/0000_0000000/00000-000000000/0000_0000000/00000-0000000000000/0000_0000000/00000-0000000-00000000/0000_0000000/00000000/0000_0000000/000/0000_0000000/00000000v00/0000_0000000/000000/0000_0000000/0000000/0000_0000000/00000y-00/0000/0000/00000000/0x000000/" hdr.Name = longName hdr.Size = 0 var buf bytes.Buffer writer := NewWriter(&buf) if err := writer.WriteHeader(hdr); err != nil { t.Fatal(err) } if err := writer.Close(); err != nil { t.Fatal(err) } // Test that we can get a long name back out of the archive. reader := NewReader(&buf) hdr, err = reader.Next() if err != nil && err != ErrInsecurePath { t.Fatal(err) } if hdr.Name != longName { t.Fatal("Couldn't recover long name") } } func TestValidTypeflagWithPAXHeader(t *testing.T) { var buffer bytes.Buffer tw := NewWriter(&buffer) fileName := strings.Repeat("ab", 100) hdr := &Header{ Name: fileName, Size: 4, Typeflag: 0, } if err := tw.WriteHeader(hdr); err != nil { t.Fatalf("Failed to write header: %s", err) } if _, err := tw.Write([]byte("fooo")); err != nil { t.Fatalf("Failed to write the file's data: %s", err) } tw.Close() tr := NewReader(&buffer) for { header, err := tr.Next() if err == io.EOF { break } if err != nil { t.Fatalf("Failed to read header: %s", err) } if header.Typeflag != TypeReg { t.Fatalf("Typeflag should've been %d, found %d", TypeReg, header.Typeflag) } } } // failOnceWriter fails exactly once and then always reports success. type failOnceWriter bool func (w *failOnceWriter) Write(b []byte) (int, error) { if !*w { return 0, io.ErrShortWrite } *w = true return len(b), nil } func TestWriterErrors(t *testing.T) { t.Run("HeaderOnly", func(t *testing.T) { tw := NewWriter(new(bytes.Buffer)) hdr := &Header{Name: "dir/", Typeflag: TypeDir} if err := tw.WriteHeader(hdr); err != nil { t.Fatalf("WriteHeader() = %v, want nil", err) } if _, err := tw.Write([]byte{0x00}); err != ErrWriteTooLong { t.Fatalf("Write() = %v, want %v", err, ErrWriteTooLong) } }) t.Run("NegativeSize", func(t *testing.T) { tw := NewWriter(new(bytes.Buffer)) hdr := &Header{Name: "small.txt", Size: -1} if err := tw.WriteHeader(hdr); err == nil { t.Fatalf("WriteHeader() = nil, want non-nil error") } }) t.Run("BeforeHeader", func(t *testing.T) { tw := NewWriter(new(bytes.Buffer)) if _, err := tw.Write([]byte("Kilts")); err != ErrWriteTooLong { t.Fatalf("Write() = %v, want %v", err, ErrWriteTooLong) } }) t.Run("AfterClose", func(t *testing.T) { tw := NewWriter(new(bytes.Buffer)) hdr := &Header{Name: "small.txt"} if err := tw.WriteHeader(hdr); err != nil { t.Fatalf("WriteHeader() = %v, want nil", err) } if err := tw.Close(); err != nil { t.Fatalf("Close() = %v, want nil", err) } if _, err := tw.Write([]byte("Kilts")); err != ErrWriteAfterClose { t.Fatalf("Write() = %v, want %v", err, ErrWriteAfterClose) } if err := tw.Flush(); err != ErrWriteAfterClose { t.Fatalf("Flush() = %v, want %v", err, ErrWriteAfterClose) } if err := tw.Close(); err != nil { t.Fatalf("Close() = %v, want nil", err) } }) t.Run("PrematureFlush", func(t *testing.T) { tw := NewWriter(new(bytes.Buffer)) hdr := &Header{Name: "small.txt", Size: 5} if err := tw.WriteHeader(hdr); err != nil { t.Fatalf("WriteHeader() = %v, want nil", err) } if err := tw.Flush(); err == nil { t.Fatalf("Flush() = %v, want non-nil error", err) } }) t.Run("PrematureClose", func(t *testing.T) { tw := NewWriter(new(bytes.Buffer)) hdr := &Header{Name: "small.txt", Size: 5} if err := tw.WriteHeader(hdr); err != nil { t.Fatalf("WriteHeader() = %v, want nil", err) } if err := tw.Close(); err == nil { t.Fatalf("Close() = %v, want non-nil error", err) } }) t.Run("Persistence", func(t *testing.T) { tw := NewWriter(new(failOnceWriter)) if err := tw.WriteHeader(&Header{}); err != io.ErrShortWrite { t.Fatalf("WriteHeader() = %v, want %v", err, io.ErrShortWrite) } if err := tw.WriteHeader(&Header{Name: "small.txt"}); err == nil { t.Errorf("WriteHeader() = got %v, want non-nil error", err) } if _, err := tw.Write(nil); err == nil { t.Errorf("Write() = %v, want non-nil error", err) } if err := tw.Flush(); err == nil { t.Errorf("Flush() = %v, want non-nil error", err) } if err := tw.Close(); err == nil { t.Errorf("Close() = %v, want non-nil error", err) } }) } func TestSplitUSTARPath(t *testing.T) { sr := strings.Repeat vectors := []struct { input string // Input path prefix string // Expected output prefix suffix string // Expected output suffix ok bool // Split success? }{ {"", "", "", false}, {"abc", "", "", false}, {"用戶名", "", "", false}, {sr("a", nameSize), "", "", false}, {sr("a", nameSize) + "/", "", "", false}, {sr("a", nameSize) + "/a", sr("a", nameSize), "a", true}, {sr("a", prefixSize) + "/", "", "", false}, {sr("a", prefixSize) + "/a", sr("a", prefixSize), "a", true}, {sr("a", nameSize+1), "", "", false}, {sr("/", nameSize+1), sr("/", nameSize-1), "/", true}, {sr("a", prefixSize) + "/" + sr("b", nameSize), sr("a", prefixSize), sr("b", nameSize), true}, {sr("a", prefixSize) + "//" + sr("b", nameSize), "", "", false}, {sr("a/", nameSize), sr("a/", 77) + "a", sr("a/", 22), true}, } for _, v := range vectors { prefix, suffix, ok := splitUSTARPath(v.input) if prefix != v.prefix || suffix != v.suffix || ok != v.ok { t.Errorf("splitUSTARPath(%q):\ngot (%q, %q, %v)\nwant (%q, %q, %v)", v.input, prefix, suffix, ok, v.prefix, v.suffix, v.ok) } } } // TestIssue12594 tests that the Writer does not attempt to populate the prefix // field when encoding a header in the GNU format. The prefix field is valid // in USTAR and PAX, but not GNU. func TestIssue12594(t *testing.T) { names := []string{ "0/1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/24/25/26/27/28/29/30/file.txt", "0/1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/24/25/26/27/28/29/30/31/32/33/file.txt", "0/1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/24/25/26/27/28/29/30/31/32/333/file.txt", "0/1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20/21/22/23/24/25/26/27/28/29/30/31/32/33/34/35/36/37/38/39/40/file.txt", "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000/file.txt", "/home/support/.openoffice.org/3/user/uno_packages/cache/registry/com.sun.star.comp.deployment.executable.PackageRegistryBackend", } for i, name := range names { var b bytes.Buffer tw := NewWriter(&b) if err := tw.WriteHeader(&Header{ Name: name, Uid: 1 << 25, // Prevent USTAR format }); err != nil { t.Errorf("test %d, unexpected WriteHeader error: %v", i, err) } if err := tw.Close(); err != nil { t.Errorf("test %d, unexpected Close error: %v", i, err) } // The prefix field should never appear in the GNU format. var blk block copy(blk[:], b.Bytes()) prefix := string(blk.toUSTAR().prefix()) prefix, _, _ = strings.Cut(prefix, "\x00") // Truncate at the NUL terminator if blk.getFormat() == FormatGNU && len(prefix) > 0 && strings.HasPrefix(name, prefix) { t.Errorf("test %d, found prefix in GNU format: %s", i, prefix) } tr := NewReader(&b) hdr, err := tr.Next() if err != nil && err != ErrInsecurePath { t.Errorf("test %d, unexpected Next error: %v", i, err) } if hdr.Name != name { t.Errorf("test %d, hdr.Name = %s, want %s", i, hdr.Name, name) } } } func TestWriteLongHeader(t *testing.T) { for _, test := range []struct { name string h *Header }{{ name: "name too long", h: &Header{Name: strings.Repeat("a", maxSpecialFileSize)}, }, { name: "linkname too long", h: &Header{Linkname: strings.Repeat("a", maxSpecialFileSize)}, }, { name: "uname too long", h: &Header{Uname: strings.Repeat("a", maxSpecialFileSize)}, }, { name: "gname too long", h: &Header{Gname: strings.Repeat("a", maxSpecialFileSize)}, }, { name: "PAX header too long", h: &Header{PAXRecords: map[string]string{"GOLANG.x": strings.Repeat("a", maxSpecialFileSize)}}, }} { w := NewWriter(io.Discard) if err := w.WriteHeader(test.h); err != ErrFieldTooLong { t.Errorf("%v: w.WriteHeader() = %v, want ErrFieldTooLong", test.name, err) } } } // testNonEmptyWriter wraps an io.Writer and ensures that // Write is never called with an empty buffer. type testNonEmptyWriter struct{ io.Writer } func (w testNonEmptyWriter) Write(b []byte) (int, error) { if len(b) == 0 { return 0, errors.New("unexpected empty Write call") } return w.Writer.Write(b) } func TestFileWriter(t *testing.T) { type ( testWrite struct { // Write(str) == (wantCnt, wantErr) str string wantCnt int wantErr error } testReadFrom struct { // ReadFrom(testFile{ops}) == (wantCnt, wantErr) ops fileOps wantCnt int64 wantErr error } testRemaining struct { // logicalRemaining() == wantLCnt, physicalRemaining() == wantPCnt wantLCnt int64 wantPCnt int64 } testFnc any // testWrite | testReadFrom | testRemaining ) type ( makeReg struct { size int64 wantStr string } makeSparse struct { makeReg makeReg sph sparseHoles size int64 } fileMaker any // makeReg | makeSparse ) vectors := []struct { maker fileMaker tests []testFnc }{{ maker: makeReg{0, ""}, tests: []testFnc{ testRemaining{0, 0}, testWrite{"", 0, nil}, testWrite{"a", 0, ErrWriteTooLong}, testReadFrom{fileOps{""}, 0, nil}, testReadFrom{fileOps{"a"}, 0, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeReg{1, "a"}, tests: []testFnc{ testRemaining{1, 1}, testWrite{"", 0, nil}, testWrite{"a", 1, nil}, testWrite{"bcde", 0, ErrWriteTooLong}, testWrite{"", 0, nil}, testReadFrom{fileOps{""}, 0, nil}, testReadFrom{fileOps{"a"}, 0, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeReg{5, "hello"}, tests: []testFnc{ testRemaining{5, 5}, testWrite{"hello", 5, nil}, testRemaining{0, 0}, }, }, { maker: makeReg{5, "\x00\x00\x00\x00\x00"}, tests: []testFnc{ testRemaining{5, 5}, testReadFrom{fileOps{"\x00\x00\x00\x00\x00"}, 5, nil}, testRemaining{0, 0}, }, }, { maker: makeReg{5, "\x00\x00\x00\x00\x00"}, tests: []testFnc{ testRemaining{5, 5}, testReadFrom{fileOps{"\x00\x00\x00\x00\x00extra"}, 5, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeReg{5, "abc\x00\x00"}, tests: []testFnc{ testRemaining{5, 5}, testWrite{"abc", 3, nil}, testRemaining{2, 2}, testReadFrom{fileOps{"\x00\x00"}, 2, nil}, testRemaining{0, 0}, }, }, { maker: makeReg{5, "\x00\x00abc"}, tests: []testFnc{ testRemaining{5, 5}, testWrite{"\x00\x00", 2, nil}, testRemaining{3, 3}, testWrite{"abc", 3, nil}, testReadFrom{fileOps{"z"}, 0, ErrWriteTooLong}, testWrite{"z", 0, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{5, "abcde"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testRemaining{8, 5}, testWrite{"ab\x00\x00\x00cde", 8, nil}, testWrite{"a", 0, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{5, "abcde"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testWrite{"ab\x00\x00\x00cdez", 8, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{5, "abcde"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testWrite{"ab\x00", 3, nil}, testRemaining{5, 3}, testWrite{"\x00\x00cde", 5, nil}, testWrite{"a", 0, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{5, "abcde"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testWrite{"ab", 2, nil}, testRemaining{6, 3}, testReadFrom{fileOps{int64(3), "cde"}, 6, nil}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{5, "abcde"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testReadFrom{fileOps{"ab", int64(3), "cde"}, 8, nil}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{5, "abcde"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testReadFrom{fileOps{"ab", int64(3), "cdeX"}, 8, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{4, "abcd"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testReadFrom{fileOps{"ab", int64(3), "cd"}, 7, io.ErrUnexpectedEOF}, testRemaining{1, 0}, }, }, { maker: makeSparse{makeReg{4, "abcd"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testReadFrom{fileOps{"ab", int64(3), "cde"}, 7, errMissData}, testRemaining{1, 0}, }, }, { maker: makeSparse{makeReg{6, "abcde"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testReadFrom{fileOps{"ab", int64(3), "cde"}, 8, errUnrefData}, testRemaining{0, 1}, }, }, { maker: makeSparse{makeReg{4, "abcd"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testWrite{"ab", 2, nil}, testRemaining{6, 2}, testWrite{"\x00\x00\x00", 3, nil}, testRemaining{3, 2}, testWrite{"cde", 2, errMissData}, testRemaining{1, 0}, }, }, { maker: makeSparse{makeReg{6, "abcde"}, sparseHoles{{2, 3}}, 8}, tests: []testFnc{ testWrite{"ab", 2, nil}, testRemaining{6, 4}, testWrite{"\x00\x00\x00", 3, nil}, testRemaining{3, 4}, testWrite{"cde", 3, errUnrefData}, testRemaining{0, 1}, }, }, { maker: makeSparse{makeReg{3, "abc"}, sparseHoles{{0, 2}, {5, 2}}, 7}, tests: []testFnc{ testRemaining{7, 3}, testWrite{"\x00\x00abc\x00\x00", 7, nil}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{3, "abc"}, sparseHoles{{0, 2}, {5, 2}}, 7}, tests: []testFnc{ testRemaining{7, 3}, testReadFrom{fileOps{int64(2), "abc", int64(1), "\x00"}, 7, nil}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{3, ""}, sparseHoles{{0, 2}, {5, 2}}, 7}, tests: []testFnc{ testWrite{"abcdefg", 0, errWriteHole}, }, }, { maker: makeSparse{makeReg{3, "abc"}, sparseHoles{{0, 2}, {5, 2}}, 7}, tests: []testFnc{ testWrite{"\x00\x00abcde", 5, errWriteHole}, }, }, { maker: makeSparse{makeReg{3, "abc"}, sparseHoles{{0, 2}, {5, 2}}, 7}, tests: []testFnc{ testWrite{"\x00\x00abc\x00\x00z", 7, ErrWriteTooLong}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{3, "abc"}, sparseHoles{{0, 2}, {5, 2}}, 7}, tests: []testFnc{ testWrite{"\x00\x00", 2, nil}, testRemaining{5, 3}, testWrite{"abc", 3, nil}, testRemaining{2, 0}, testWrite{"\x00\x00", 2, nil}, testRemaining{0, 0}, }, }, { maker: makeSparse{makeReg{2, "ab"}, sparseHoles{{0, 2}, {5, 2}}, 7}, tests: []testFnc{ testWrite{"\x00\x00", 2, nil}, testWrite{"abc", 2, errMissData}, testWrite{"\x00\x00", 0, errMissData}, }, }, { maker: makeSparse{makeReg{4, "abc"}, sparseHoles{{0, 2}, {5, 2}}, 7}, tests: []testFnc{ testWrite{"\x00\x00", 2, nil}, testWrite{"abc", 3, nil}, testWrite{"\x00\x00", 2, errUnrefData}, }, }} for i, v := range vectors { var wantStr string bb := new(strings.Builder) w := testNonEmptyWriter{bb} var fw fileWriter switch maker := v.maker.(type) { case makeReg: fw = &regFileWriter{w, maker.size} wantStr = maker.wantStr case makeSparse: if !validateSparseEntries(maker.sph, maker.size) { t.Fatalf("invalid sparse map: %v", maker.sph) } spd := invertSparseEntries(maker.sph, maker.size) fw = &regFileWriter{w, maker.makeReg.size} fw = &sparseFileWriter{fw, spd, 0} wantStr = maker.makeReg.wantStr default: t.Fatalf("test %d, unknown make operation: %T", i, maker) } for j, tf := range v.tests { switch tf := tf.(type) { case testWrite: got, err := fw.Write([]byte(tf.str)) if got != tf.wantCnt || err != tf.wantErr { t.Errorf("test %d.%d, Write(%s):\ngot (%d, %v)\nwant (%d, %v)", i, j, tf.str, got, err, tf.wantCnt, tf.wantErr) } case testReadFrom: f := &testFile{ops: tf.ops} got, err := fw.ReadFrom(f) if _, ok := err.(testError); ok { t.Errorf("test %d.%d, ReadFrom(): %v", i, j, err) } else if got != tf.wantCnt || err != tf.wantErr { t.Errorf("test %d.%d, ReadFrom() = (%d, %v), want (%d, %v)", i, j, got, err, tf.wantCnt, tf.wantErr) } if len(f.ops) > 0 { t.Errorf("test %d.%d, expected %d more operations", i, j, len(f.ops)) } case testRemaining: if got := fw.logicalRemaining(); got != tf.wantLCnt { t.Errorf("test %d.%d, logicalRemaining() = %d, want %d", i, j, got, tf.wantLCnt) } if got := fw.physicalRemaining(); got != tf.wantPCnt { t.Errorf("test %d.%d, physicalRemaining() = %d, want %d", i, j, got, tf.wantPCnt) } default: t.Fatalf("test %d.%d, unknown test operation: %T", i, j, tf) } } if got := bb.String(); got != wantStr { t.Fatalf("test %d, String() = %q, want %q", i, got, wantStr) } } } func TestWriterAddFS(t *testing.T) { fsys := fstest.MapFS{ "file.go": {Data: []byte("hello")}, "subfolder/another.go": {Data: []byte("world")}, } var buf bytes.Buffer tw := NewWriter(&buf) if err := tw.AddFS(fsys); err != nil { t.Fatal(err) } // Test that we can get the files back from the archive tr := NewReader(&buf) entries, err := fsys.ReadDir(".") if err != nil { t.Fatal(err) } var curfname string for _, entry := range entries { curfname = entry.Name() if entry.IsDir() { curfname += "/" continue } hdr, err := tr.Next() if err == io.EOF { break // End of archive } if err != nil { t.Fatal(err) } data, err := io.ReadAll(tr) if err != nil { t.Fatal(err) } if hdr.Name != curfname { t.Fatalf("got filename %v, want %v", curfname, hdr.Name) } origdata := fsys[curfname].Data if string(data) != string(origdata) { t.Fatalf("got file content %v, want %v", data, origdata) } } } func TestWriterAddFSNonRegularFiles(t *testing.T) { fsys := fstest.MapFS{ "device": {Data: []byte("hello"), Mode: 0755 | fs.ModeDevice}, "symlink": {Data: []byte("world"), Mode: 0755 | fs.ModeSymlink}, } var buf bytes.Buffer tw := NewWriter(&buf) if err := tw.AddFS(fsys); err == nil { t.Fatal("expected error, got nil") } }
go/src/archive/tar/writer_test.go/0
{ "file_path": "go/src/archive/tar/writer_test.go", "repo_id": "go", "token_count": 18172 }
60
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bufio_test import ( "bufio" "bytes" "fmt" "os" "strconv" "strings" ) func ExampleWriter() { w := bufio.NewWriter(os.Stdout) fmt.Fprint(w, "Hello, ") fmt.Fprint(w, "world!") w.Flush() // Don't forget to flush! // Output: Hello, world! } func ExampleWriter_AvailableBuffer() { w := bufio.NewWriter(os.Stdout) for _, i := range []int64{1, 2, 3, 4} { b := w.AvailableBuffer() b = strconv.AppendInt(b, i, 10) b = append(b, ' ') w.Write(b) } w.Flush() // Output: 1 2 3 4 } // The simplest use of a Scanner, to read standard input as a set of lines. func ExampleScanner_lines() { scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { fmt.Println(scanner.Text()) // Println will add back the final '\n' } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } } // Return the most recent call to Scan as a []byte. func ExampleScanner_Bytes() { scanner := bufio.NewScanner(strings.NewReader("gopher")) for scanner.Scan() { fmt.Println(len(scanner.Bytes()) == 6) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string") } // Output: // true } // Use a Scanner to implement a simple word-count utility by scanning the // input as a sequence of space-delimited tokens. func ExampleScanner_words() { // An artificial input source. const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n" scanner := bufio.NewScanner(strings.NewReader(input)) // Set the split function for the scanning operation. scanner.Split(bufio.ScanWords) // Count the words. count := 0 for scanner.Scan() { count++ } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } fmt.Printf("%d\n", count) // Output: 15 } // Use a Scanner with a custom split function (built by wrapping ScanWords) to validate // 32-bit decimal input. func ExampleScanner_custom() { // An artificial input source. const input = "1234 5678 1234567901234567890" scanner := bufio.NewScanner(strings.NewReader(input)) // Create a custom split function by wrapping the existing ScanWords function. split := func(data []byte, atEOF bool) (advance int, token []byte, err error) { advance, token, err = bufio.ScanWords(data, atEOF) if err == nil && token != nil { _, err = strconv.ParseInt(string(token), 10, 32) } return } // Set the split function for the scanning operation. scanner.Split(split) // Validate the input for scanner.Scan() { fmt.Printf("%s\n", scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Printf("Invalid input: %s", err) } // Output: // 1234 // 5678 // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range } // Use a Scanner with a custom split function to parse a comma-separated // list with an empty final value. func ExampleScanner_emptyFinalToken() { // Comma-separated list; last entry is empty. const input = "1,2,3,4," scanner := bufio.NewScanner(strings.NewReader(input)) // Define a split function that separates on commas. onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) { for i := 0; i < len(data); i++ { if data[i] == ',' { return i + 1, data[:i], nil } } if !atEOF { return 0, nil, nil } // There is one final token to be delivered, which may be the empty string. // Returning bufio.ErrFinalToken here tells Scan there are no more tokens after this // but does not trigger an error to be returned from Scan itself. return 0, data, bufio.ErrFinalToken } scanner.Split(onComma) // Scan. for scanner.Scan() { fmt.Printf("%q ", scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } // Output: "1" "2" "3" "4" "" } // Use a Scanner with a custom split function to parse a comma-separated // list with an empty final value but stops at the token "STOP". func ExampleScanner_earlyStop() { onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) { i := bytes.IndexByte(data, ',') if i == -1 { if !atEOF { return 0, nil, nil } // If we have reached the end, return the last token. return 0, data, bufio.ErrFinalToken } // If the token is "STOP", stop the scanning and ignore the rest. if string(data[:i]) == "STOP" { return i + 1, nil, bufio.ErrFinalToken } // Otherwise, return the token before the comma. return i + 1, data[:i], nil } const input = "1,2,STOP,4," scanner := bufio.NewScanner(strings.NewReader(input)) scanner.Split(onComma) for scanner.Scan() { fmt.Printf("Got a token %q\n", scanner.Text()) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } // Output: // Got a token "1" // Got a token "2" }
go/src/bufio/example_test.go/0
{ "file_path": "go/src/bufio/example_test.go", "repo_id": "go", "token_count": 1858 }
61
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package bytes_test import ( . "bytes" "fmt" "io" "sync" "testing" ) func TestReader(t *testing.T) { r := NewReader([]byte("0123456789")) tests := []struct { off int64 seek int n int want string wantpos int64 readerr error seekerr string }{ {seek: io.SeekStart, off: 0, n: 20, want: "0123456789"}, {seek: io.SeekStart, off: 1, n: 1, want: "1"}, {seek: io.SeekCurrent, off: 1, wantpos: 3, n: 2, want: "34"}, {seek: io.SeekStart, off: -1, seekerr: "bytes.Reader.Seek: negative position"}, {seek: io.SeekStart, off: 1 << 33, wantpos: 1 << 33, readerr: io.EOF}, {seek: io.SeekCurrent, off: 1, wantpos: 1<<33 + 1, readerr: io.EOF}, {seek: io.SeekStart, n: 5, want: "01234"}, {seek: io.SeekCurrent, n: 5, want: "56789"}, {seek: io.SeekEnd, off: -1, n: 1, wantpos: 9, want: "9"}, } for i, tt := range tests { pos, err := r.Seek(tt.off, tt.seek) if err == nil && tt.seekerr != "" { t.Errorf("%d. want seek error %q", i, tt.seekerr) continue } if err != nil && err.Error() != tt.seekerr { t.Errorf("%d. seek error = %q; want %q", i, err.Error(), tt.seekerr) continue } if tt.wantpos != 0 && tt.wantpos != pos { t.Errorf("%d. pos = %d, want %d", i, pos, tt.wantpos) } buf := make([]byte, tt.n) n, err := r.Read(buf) if err != tt.readerr { t.Errorf("%d. read = %v; want %v", i, err, tt.readerr) continue } got := string(buf[:n]) if got != tt.want { t.Errorf("%d. got %q; want %q", i, got, tt.want) } } } func TestReadAfterBigSeek(t *testing.T) { r := NewReader([]byte("0123456789")) if _, err := r.Seek(1<<31+5, io.SeekStart); err != nil { t.Fatal(err) } if n, err := r.Read(make([]byte, 10)); n != 0 || err != io.EOF { t.Errorf("Read = %d, %v; want 0, EOF", n, err) } } func TestReaderAt(t *testing.T) { r := NewReader([]byte("0123456789")) tests := []struct { off int64 n int want string wanterr any }{ {0, 10, "0123456789", nil}, {1, 10, "123456789", io.EOF}, {1, 9, "123456789", nil}, {11, 10, "", io.EOF}, {0, 0, "", nil}, {-1, 0, "", "bytes.Reader.ReadAt: negative offset"}, } for i, tt := range tests { b := make([]byte, tt.n) rn, err := r.ReadAt(b, tt.off) got := string(b[:rn]) if got != tt.want { t.Errorf("%d. got %q; want %q", i, got, tt.want) } if fmt.Sprintf("%v", err) != fmt.Sprintf("%v", tt.wanterr) { t.Errorf("%d. got error = %v; want %v", i, err, tt.wanterr) } } } func TestReaderAtConcurrent(t *testing.T) { // Test for the race detector, to verify ReadAt doesn't mutate // any state. r := NewReader([]byte("0123456789")) var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func(i int) { defer wg.Done() var buf [1]byte r.ReadAt(buf[:], int64(i)) }(i) } wg.Wait() } func TestEmptyReaderConcurrent(t *testing.T) { // Test for the race detector, to verify a Read that doesn't yield any bytes // is okay to use from multiple goroutines. This was our historic behavior. // See golang.org/issue/7856 r := NewReader([]byte{}) var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(2) go func() { defer wg.Done() var buf [1]byte r.Read(buf[:]) }() go func() { defer wg.Done() r.Read(nil) }() } wg.Wait() } func TestReaderWriteTo(t *testing.T) { for i := 0; i < 30; i += 3 { var l int if i > 0 { l = len(testString) / i } s := testString[:l] r := NewReader(testBytes[:l]) var b Buffer n, err := r.WriteTo(&b) if expect := int64(len(s)); n != expect { t.Errorf("got %v; want %v", n, expect) } if err != nil { t.Errorf("for length %d: got error = %v; want nil", l, err) } if b.String() != s { t.Errorf("got string %q; want %q", b.String(), s) } if r.Len() != 0 { t.Errorf("reader contains %v bytes; want 0", r.Len()) } } } func TestReaderLen(t *testing.T) { const data = "hello world" r := NewReader([]byte(data)) if got, want := r.Len(), 11; got != want { t.Errorf("r.Len(): got %d, want %d", got, want) } if n, err := r.Read(make([]byte, 10)); err != nil || n != 10 { t.Errorf("Read failed: read %d %v", n, err) } if got, want := r.Len(), 1; got != want { t.Errorf("r.Len(): got %d, want %d", got, want) } if n, err := r.Read(make([]byte, 1)); err != nil || n != 1 { t.Errorf("Read failed: read %d %v; want 1, nil", n, err) } if got, want := r.Len(), 0; got != want { t.Errorf("r.Len(): got %d, want %d", got, want) } } var UnreadRuneErrorTests = []struct { name string f func(*Reader) }{ {"Read", func(r *Reader) { r.Read([]byte{0}) }}, {"ReadByte", func(r *Reader) { r.ReadByte() }}, {"UnreadRune", func(r *Reader) { r.UnreadRune() }}, {"Seek", func(r *Reader) { r.Seek(0, io.SeekCurrent) }}, {"WriteTo", func(r *Reader) { r.WriteTo(&Buffer{}) }}, } func TestUnreadRuneError(t *testing.T) { for _, tt := range UnreadRuneErrorTests { reader := NewReader([]byte("0123456789")) if _, _, err := reader.ReadRune(); err != nil { // should not happen t.Fatal(err) } tt.f(reader) err := reader.UnreadRune() if err == nil { t.Errorf("Unreading after %s: expected error", tt.name) } } } func TestReaderDoubleUnreadRune(t *testing.T) { buf := NewBuffer([]byte("groucho")) if _, _, err := buf.ReadRune(); err != nil { // should not happen t.Fatal(err) } if err := buf.UnreadByte(); err != nil { // should not happen t.Fatal(err) } if err := buf.UnreadByte(); err == nil { t.Fatal("UnreadByte: expected error, got nil") } } // verify that copying from an empty reader always has the same results, // regardless of the presence of a WriteTo method. func TestReaderCopyNothing(t *testing.T) { type nErr struct { n int64 err error } type justReader struct { io.Reader } type justWriter struct { io.Writer } discard := justWriter{io.Discard} // hide ReadFrom var with, withOut nErr with.n, with.err = io.Copy(discard, NewReader(nil)) withOut.n, withOut.err = io.Copy(discard, justReader{NewReader(nil)}) if with != withOut { t.Errorf("behavior differs: with = %#v; without: %#v", with, withOut) } } // tests that Len is affected by reads, but Size is not. func TestReaderLenSize(t *testing.T) { r := NewReader([]byte("abc")) io.CopyN(io.Discard, r, 1) if r.Len() != 2 { t.Errorf("Len = %d; want 2", r.Len()) } if r.Size() != 3 { t.Errorf("Size = %d; want 3", r.Size()) } } func TestReaderReset(t *testing.T) { r := NewReader([]byte("世界")) if _, _, err := r.ReadRune(); err != nil { t.Errorf("ReadRune: unexpected error: %v", err) } const want = "abcdef" r.Reset([]byte(want)) if err := r.UnreadRune(); err == nil { t.Errorf("UnreadRune: expected error, got nil") } buf, err := io.ReadAll(r) if err != nil { t.Errorf("ReadAll: unexpected error: %v", err) } if got := string(buf); got != want { t.Errorf("ReadAll: got %q, want %q", got, want) } } func TestReaderZero(t *testing.T) { if l := (&Reader{}).Len(); l != 0 { t.Errorf("Len: got %d, want 0", l) } if n, err := (&Reader{}).Read(nil); n != 0 || err != io.EOF { t.Errorf("Read: got %d, %v; want 0, io.EOF", n, err) } if n, err := (&Reader{}).ReadAt(nil, 11); n != 0 || err != io.EOF { t.Errorf("ReadAt: got %d, %v; want 0, io.EOF", n, err) } if b, err := (&Reader{}).ReadByte(); b != 0 || err != io.EOF { t.Errorf("ReadByte: got %d, %v; want 0, io.EOF", b, err) } if ch, size, err := (&Reader{}).ReadRune(); ch != 0 || size != 0 || err != io.EOF { t.Errorf("ReadRune: got %d, %d, %v; want 0, 0, io.EOF", ch, size, err) } if offset, err := (&Reader{}).Seek(11, io.SeekStart); offset != 11 || err != nil { t.Errorf("Seek: got %d, %v; want 11, nil", offset, err) } if s := (&Reader{}).Size(); s != 0 { t.Errorf("Size: got %d, want 0", s) } if (&Reader{}).UnreadByte() == nil { t.Errorf("UnreadByte: got nil, want error") } if (&Reader{}).UnreadRune() == nil { t.Errorf("UnreadRune: got nil, want error") } if n, err := (&Reader{}).WriteTo(io.Discard); n != 0 || err != nil { t.Errorf("WriteTo: got %d, %v; want 0, nil", n, err) } }
go/src/bytes/reader_test.go/0
{ "file_path": "go/src/bytes/reader_test.go", "repo_id": "go", "token_count": 3707 }
62
Empty directory for test, see https://golang.org/issues/29837.
go/src/cmd/api/testdata/src/issue29837/p/README/0
{ "file_path": "go/src/cmd/api/testdata/src/issue29837/p/README", "repo_id": "go", "token_count": 19 }
63
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This file encapsulates some of the odd characteristics of the // 64-bit PowerPC (PPC64) instruction set, to minimize its interaction // with the core of the assembler. package arch import ( "cmd/internal/obj" "cmd/internal/obj/ppc64" ) func jumpPPC64(word string) bool { switch word { case "BC", "BCL", "BEQ", "BGE", "BGT", "BL", "BLE", "BLT", "BNE", "BR", "BVC", "BVS", "BDNZ", "BDZ", "CALL", "JMP": return true } return false } // IsPPC64CMP reports whether the op (as defined by an ppc64.A* constant) is // one of the CMP instructions that require special handling. func IsPPC64CMP(op obj.As) bool { switch op { case ppc64.ACMP, ppc64.ACMPU, ppc64.ACMPW, ppc64.ACMPWU, ppc64.AFCMPO, ppc64.AFCMPU: return true } return false } // IsPPC64NEG reports whether the op (as defined by an ppc64.A* constant) is // one of the NEG-like instructions that require special handling. func IsPPC64NEG(op obj.As) bool { switch op { case ppc64.AADDMECC, ppc64.AADDMEVCC, ppc64.AADDMEV, ppc64.AADDME, ppc64.AADDZECC, ppc64.AADDZEVCC, ppc64.AADDZEV, ppc64.AADDZE, ppc64.ACNTLZDCC, ppc64.ACNTLZD, ppc64.ACNTLZWCC, ppc64.ACNTLZW, ppc64.AEXTSBCC, ppc64.AEXTSB, ppc64.AEXTSHCC, ppc64.AEXTSH, ppc64.AEXTSWCC, ppc64.AEXTSW, ppc64.ANEGCC, ppc64.ANEGVCC, ppc64.ANEGV, ppc64.ANEG, ppc64.ASLBMFEE, ppc64.ASLBMFEV, ppc64.ASLBMTE, ppc64.ASUBMECC, ppc64.ASUBMEVCC, ppc64.ASUBMEV, ppc64.ASUBME, ppc64.ASUBZECC, ppc64.ASUBZEVCC, ppc64.ASUBZEV, ppc64.ASUBZE: return true } return false } func ppc64RegisterNumber(name string, n int16) (int16, bool) { switch name { case "CR": if 0 <= n && n <= 7 { return ppc64.REG_CR0 + n, true } case "A": if 0 <= n && n <= 8 { return ppc64.REG_A0 + n, true } case "VS": if 0 <= n && n <= 63 { return ppc64.REG_VS0 + n, true } case "V": if 0 <= n && n <= 31 { return ppc64.REG_V0 + n, true } case "F": if 0 <= n && n <= 31 { return ppc64.REG_F0 + n, true } case "R": if 0 <= n && n <= 31 { return ppc64.REG_R0 + n, true } case "SPR": if 0 <= n && n <= 1024 { return ppc64.REG_SPR0 + n, true } } return 0, false }
go/src/cmd/asm/internal/arch/ppc64.go/0
{ "file_path": "go/src/cmd/asm/internal/arch/ppc64.go", "repo_id": "go", "token_count": 1064 }
64
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. TEXT errors(SB),$0 MOVL foo<>(SB)(AX), AX // ERROR "invalid instruction" MOVL (AX)(SP*1), AX // ERROR "invalid instruction" EXTRACTPS $4, X2, (BX) // ERROR "invalid instruction" EXTRACTPS $-1, X2, (BX) // ERROR "invalid instruction" // VSIB addressing does not permit non-vector (X/Y) // scaled index register. VPGATHERDQ X12,(R13)(AX*2), X11 // ERROR "invalid instruction" VPGATHERDQ X2, 664(BX*1), X1 // ERROR "invalid instruction" VPGATHERDQ Y2, (BP)(AX*2), Y1 // ERROR "invalid instruction" VPGATHERDQ Y5, 664(DX*8), Y6 // ERROR "invalid instruction" VPGATHERDQ Y5, (DX), Y0 // ERROR "invalid instruction" // VM/X rejects Y index register. VPGATHERDQ Y5, 664(Y14*8), Y6 // ERROR "invalid instruction" VPGATHERQQ X2, (BP)(Y7*2), X1 // ERROR "invalid instruction" // VM/Y rejects X index register. VPGATHERQQ Y2, (BP)(X7*2), Y1 // ERROR "invalid instruction" VPGATHERDD Y5, -8(X14*8), Y6 // ERROR "invalid instruction" // No VSIB for legacy instructions. MOVL (AX)(X0*1), AX // ERROR "invalid instruction" MOVL (AX)(Y0*1), AX // ERROR "invalid instruction" // VSIB/VM is invalid without vector index. // TODO(quasilyte): improve error message (#21860). // "invalid VSIB address (missing vector index)" VPGATHERQQ Y2, (BP), Y1 // ERROR "invalid instruction" // AVX2GATHER mask/index/dest #UD cases. VPGATHERQQ Y2, (BP)(X2*2), Y2 // ERROR "mask, index, and destination registers should be distinct" VPGATHERQQ Y2, (BP)(X2*2), Y7 // ERROR "mask, index, and destination registers should be distinct" VPGATHERQQ Y2, (BP)(X7*2), Y2 // ERROR "mask, index, and destination registers should be distinct" VPGATHERQQ Y7, (BP)(X2*2), Y2 // ERROR "mask, index, and destination registers should be distinct" VPGATHERDQ X2, 664(X2*8), X2 // ERROR "mask, index, and destination registers should be distinct" VPGATHERDQ X2, 664(X2*8), X7 // ERROR "mask, index, and destination registers should be distinct" VPGATHERDQ X2, 664(X7*8), X2 // ERROR "mask, index, and destination registers should be distinct" VPGATHERDQ X7, 664(X2*8), X2 // ERROR "mask, index, and destination registers should be distinct" // Non-X0 for Yxr0 should produce an error BLENDVPD X1, (BX), X2 // ERROR "invalid instruction" // Check offset overflow. Must fit in int32. MOVQ 2147483647+1(AX), AX // ERROR "offset too large" MOVQ 3395469782(R10), R8 // ERROR "offset too large" LEAQ 3395469782(AX), AX // ERROR "offset too large" ADDQ 3395469782(AX), AX // ERROR "offset too large" ADDL 3395469782(AX), AX // ERROR "offset too large" ADDW 3395469782(AX), AX // ERROR "offset too large" LEAQ 433954697820(AX), AX // ERROR "offset too large" ADDQ 433954697820(AX), AX // ERROR "offset too large" ADDL 433954697820(AX), AX // ERROR "offset too large" ADDW 433954697820(AX), AX // ERROR "offset too large" // Pseudo-registers should not be used as scaled index. CALL (AX)(PC*1) // ERROR "invalid instruction" CALL (AX)(SB*1) // ERROR "invalid instruction" CALL (AX)(FP*1) // ERROR "invalid instruction" // Forbid memory operands for MOV CR/DR. See #24981. MOVQ CR0, (AX) // ERROR "invalid instruction" MOVQ CR2, (AX) // ERROR "invalid instruction" MOVQ CR3, (AX) // ERROR "invalid instruction" MOVQ CR4, (AX) // ERROR "invalid instruction" MOVQ CR8, (AX) // ERROR "invalid instruction" MOVQ (AX), CR0 // ERROR "invalid instruction" MOVQ (AX), CR2 // ERROR "invalid instruction" MOVQ (AX), CR3 // ERROR "invalid instruction" MOVQ (AX), CR4 // ERROR "invalid instruction" MOVQ (AX), CR8 // ERROR "invalid instruction" MOVQ DR0, (AX) // ERROR "invalid instruction" MOVQ DR2, (AX) // ERROR "invalid instruction" MOVQ DR3, (AX) // ERROR "invalid instruction" MOVQ DR6, (AX) // ERROR "invalid instruction" MOVQ DR7, (AX) // ERROR "invalid instruction" MOVQ (AX), DR0 // ERROR "invalid instruction" MOVQ (AX), DR2 // ERROR "invalid instruction" MOVQ (AX), DR3 // ERROR "invalid instruction" MOVQ (AX), DR6 // ERROR "invalid instruction" MOVQ (AX), DR7 // ERROR "invalid instruction" // AVX512GATHER index/index #UD cases. VPGATHERQQ (BP)(X2*2), K1, X2 // ERROR "index and destination registers should be distinct" VPGATHERQQ (BP)(Y15*2), K1, Y15 // ERROR "index and destination registers should be distinct" VPGATHERQQ (BP)(Z20*2), K1, Z20 // ERROR "index and destination registers should be distinct" VPGATHERDQ (BP)(X2*2), K1, X2 // ERROR "index and destination registers should be distinct" VPGATHERDQ (BP)(X15*2), K1, Y15 // ERROR "index and destination registers should be distinct" VPGATHERDQ (BP)(Y20*2), K1, Z20 // ERROR "index and destination registers should be distinct" // Instructions without EVEX variant can't use High-16 registers. VADDSUBPD X20, X1, X2 // ERROR "invalid instruction" VADDSUBPS X0, X20, X2 // ERROR "invalid instruction" // Use of K0 for write mask (Yknot0). // TODO(quasilyte): improve error message (#21860). // "K0 can't be used for write mask" VADDPD X0, X1, K0, X2 // ERROR "invalid instruction" VADDPD Y0, Y1, K0, Y2 // ERROR "invalid instruction" VADDPD Z0, Z1, K0, Z2 // ERROR "invalid instruction" // VEX-encoded VSIB can't use High-16 registers as index (unlike EVEX). // TODO(quasilyte): improve error message (#21860). VPGATHERQQ X2, (BP)(X20*2), X3 // ERROR "invalid instruction" VPGATHERQQ Y2, (BP)(Y20*2), Y3 // ERROR "invalid instruction" // YzrMulti4 expects exactly 4 registers referenced by REG_LIST. // TODO(quasilyte): improve error message (#21860). V4FMADDPS (AX), [Z0-Z4], K1, Z7 // ERROR "invalid instruction" V4FMADDPS (AX), [Z0-Z0], K1, Z7 // ERROR "invalid instruction" // Invalid ranges in REG_LIST (low > high). // TODO(quasilyte): improve error message (#21860). V4FMADDPS (AX), [Z4-Z0], K1, Z7 // ERROR "invalid instruction" V4FMADDPS (AX), [Z1-Z0], K1, Z7 // ERROR "invalid instruction" // Mismatching registers in a range. // TODO(quasilyte): improve error message (#21860). V4FMADDPS (AX), [AX-Z3], K1, Z7 // ERROR "invalid instruction" V4FMADDPS (AX), [Z0-AX], K1, Z7 // ERROR "invalid instruction" // Usage of suffixes for non-EVEX instructions. ADCB.Z $7, AL // ERROR "invalid instruction" ADCB.RU_SAE $7, AL // ERROR "invalid instruction" ADCB.RU_SAE.Z $7, AL // ERROR "invalid instruction" // Usage of rounding with invalid operands. VADDPD.RU_SAE X3, X2, K1, X1 // ERROR "unsupported rounding" VADDPD.RD_SAE X3, X2, K1, X1 // ERROR "unsupported rounding" VADDPD.RZ_SAE X3, X2, K1, X1 // ERROR "unsupported rounding" VADDPD.RN_SAE X3, X2, K1, X1 // ERROR "unsupported rounding" VADDPD.RU_SAE Y3, Y2, K1, Y1 // ERROR "unsupported rounding" VADDPD.RD_SAE Y3, Y2, K1, Y1 // ERROR "unsupported rounding" VADDPD.RZ_SAE Y3, Y2, K1, Y1 // ERROR "unsupported rounding" VADDPD.RN_SAE Y3, Y2, K1, Y1 // ERROR "unsupported rounding" // Unsupported SAE. VMAXPD.SAE (AX), Z2, K1, Z1 // ERROR "illegal SAE with memory argument" VADDPD.SAE X3, X2, K1, X1 // ERROR "unsupported SAE" // Unsupported zeroing. VFPCLASSPDX.Z $0, (AX), K2, K1 // ERROR "unsupported zeroing" VFPCLASSPDY.Z $0, (AX), K2, K1 // ERROR "unsupported zeroing" // Unsupported broadcast. VFPCLASSSD.BCST $0, (AX), K2, K1 // ERROR "unsupported broadcast" VFPCLASSSS.BCST $0, (AX), K2, K1 // ERROR "unsupported broadcast" // Broadcast without memory operand. VADDPD.BCST X3, X2, K1, X1 // ERROR "illegal broadcast without memory argument" VADDPD.BCST X3, X2, K1, X1 // ERROR "illegal broadcast without memory argument" VADDPD.BCST X3, X2, K1, X1 // ERROR "illegal broadcast without memory argument" // CLWB instructions: CLWB BX // ERROR "invalid instruction" // CLDEMOTE instructions: CLDEMOTE BX // ERROR "invalid instruction" // WAITPKG instructions: TPAUSE (BX) // ERROR "invalid instruction" UMONITOR (BX) // ERROR "invalid instruction" UMWAIT (BX) // ERROR "invalid instruction" // .Z instructions VMOVDQA32.Z Z0, Z1 // ERROR "mask register must be specified for .Z instructions" VMOVDQA32.Z Z0, K0, Z1 // ERROR "invalid instruction" VMOVDQA32.Z Z0, K1, Z1 // ok RDPID (BX) // ERROR "invalid instruction" RET
go/src/cmd/asm/internal/asm/testdata/amd64error.s/0
{ "file_path": "go/src/cmd/asm/internal/asm/testdata/amd64error.s", "repo_id": "go", "token_count": 3965 }
65
// Code generated by avx512test. DO NOT EDIT. #include "../../../../../../runtime/textflag.h" TEXT asmtest_avx512bw(SB), NOSPLIT, $0 KADDD K4, K7, K5 // c4e1c54aec KADDD K6, K7, K5 // c4e1c54aee KADDD K4, K6, K5 // c4e1cd4aec KADDD K6, K6, K5 // c4e1cd4aee KADDD K4, K7, K4 // c4e1c54ae4 KADDD K6, K7, K4 // c4e1c54ae6 KADDD K4, K6, K4 // c4e1cd4ae4 KADDD K6, K6, K4 // c4e1cd4ae6 KADDQ K4, K5, K0 // c4e1d44ac4 KADDQ K6, K5, K0 // c4e1d44ac6 KADDQ K4, K4, K0 // c4e1dc4ac4 KADDQ K6, K4, K0 // c4e1dc4ac6 KADDQ K4, K5, K7 // c4e1d44afc KADDQ K6, K5, K7 // c4e1d44afe KADDQ K4, K4, K7 // c4e1dc4afc KADDQ K6, K4, K7 // c4e1dc4afe KANDD K1, K6, K0 // c4e1cd41c1 KANDD K5, K6, K0 // c4e1cd41c5 KANDD K1, K5, K0 // c4e1d541c1 KANDD K5, K5, K0 // c4e1d541c5 KANDD K1, K6, K5 // c4e1cd41e9 KANDD K5, K6, K5 // c4e1cd41ed KANDD K1, K5, K5 // c4e1d541e9 KANDD K5, K5, K5 // c4e1d541ed KANDND K5, K0, K4 // c4e1fd42e5 KANDND K4, K0, K4 // c4e1fd42e4 KANDND K5, K7, K4 // c4e1c542e5 KANDND K4, K7, K4 // c4e1c542e4 KANDND K5, K0, K6 // c4e1fd42f5 KANDND K4, K0, K6 // c4e1fd42f4 KANDND K5, K7, K6 // c4e1c542f5 KANDND K4, K7, K6 // c4e1c542f4 KANDNQ K6, K1, K4 // c4e1f442e6 KANDNQ K7, K1, K4 // c4e1f442e7 KANDNQ K6, K3, K4 // c4e1e442e6 KANDNQ K7, K3, K4 // c4e1e442e7 KANDNQ K6, K1, K6 // c4e1f442f6 KANDNQ K7, K1, K6 // c4e1f442f7 KANDNQ K6, K3, K6 // c4e1e442f6 KANDNQ K7, K3, K6 // c4e1e442f7 KANDQ K6, K0, K2 // c4e1fc41d6 KANDQ K5, K0, K2 // c4e1fc41d5 KANDQ K6, K5, K2 // c4e1d441d6 KANDQ K5, K5, K2 // c4e1d441d5 KANDQ K6, K0, K7 // c4e1fc41fe KANDQ K5, K0, K7 // c4e1fc41fd KANDQ K6, K5, K7 // c4e1d441fe KANDQ K5, K5, K7 // c4e1d441fd KMOVD K1, 17(SP) // c4e1f9914c2411 KMOVD K3, 17(SP) // c4e1f9915c2411 KMOVD K1, -17(BP)(SI*4) // c4e1f9914cb5ef KMOVD K3, -17(BP)(SI*4) // c4e1f9915cb5ef KMOVD K6, R14 // c57b93f6 KMOVD K7, R14 // c57b93f7 KMOVD K6, AX // c5fb93c6 KMOVD K7, AX // c5fb93c7 KMOVD K4, K6 // c4e1f990f4 KMOVD K6, K6 // c4e1f990f6 KMOVD 7(AX), K6 // c4e1f9907007 KMOVD (DI), K6 // c4e1f99037 KMOVD K4, K4 // c4e1f990e4 KMOVD K6, K4 // c4e1f990e6 KMOVD 7(AX), K4 // c4e1f9906007 KMOVD (DI), K4 // c4e1f99027 KMOVD R9, K4 // c4c17b92e1 KMOVD CX, K4 // c5fb92e1 KMOVD R9, K5 // c4c17b92e9 KMOVD CX, K5 // c5fb92e9 KMOVQ K2, 17(SP) // c4e1f891542411 KMOVQ K7, 17(SP) // c4e1f8917c2411 KMOVQ K2, -17(BP)(SI*4) // c4e1f89154b5ef KMOVQ K7, -17(BP)(SI*4) // c4e1f8917cb5ef KMOVQ K0, DX // c4e1fb93d0 KMOVQ K5, DX // c4e1fb93d5 KMOVQ K0, BP // c4e1fb93e8 KMOVQ K5, BP // c4e1fb93ed KMOVQ K1, K6 // c4e1f890f1 KMOVQ K5, K6 // c4e1f890f5 KMOVQ 7(AX), K6 // c4e1f8907007 KMOVQ (DI), K6 // c4e1f89037 KMOVQ K1, K5 // c4e1f890e9 KMOVQ K5, K5 // c4e1f890ed KMOVQ 7(AX), K5 // c4e1f8906807 KMOVQ (DI), K5 // c4e1f8902f KMOVQ R10, K3 // c4c1fb92da KMOVQ CX, K3 // c4e1fb92d9 KMOVQ R10, K1 // c4c1fb92ca KMOVQ CX, K1 // c4e1fb92c9 KNOTD K6, K6 // c4e1f944f6 KNOTD K4, K6 // c4e1f944f4 KNOTD K6, K7 // c4e1f944fe KNOTD K4, K7 // c4e1f944fc KNOTQ K4, K4 // c4e1f844e4 KNOTQ K5, K4 // c4e1f844e5 KNOTQ K4, K6 // c4e1f844f4 KNOTQ K5, K6 // c4e1f844f5 KORD K4, K7, K5 // c4e1c545ec KORD K6, K7, K5 // c4e1c545ee KORD K4, K6, K5 // c4e1cd45ec KORD K6, K6, K5 // c4e1cd45ee KORD K4, K7, K4 // c4e1c545e4 KORD K6, K7, K4 // c4e1c545e6 KORD K4, K6, K4 // c4e1cd45e4 KORD K6, K6, K4 // c4e1cd45e6 KORQ K4, K5, K0 // c4e1d445c4 KORQ K6, K5, K0 // c4e1d445c6 KORQ K4, K4, K0 // c4e1dc45c4 KORQ K6, K4, K0 // c4e1dc45c6 KORQ K4, K5, K7 // c4e1d445fc KORQ K6, K5, K7 // c4e1d445fe KORQ K4, K4, K7 // c4e1dc45fc KORQ K6, K4, K7 // c4e1dc45fe KORTESTD K4, K6 // c4e1f998f4 KORTESTD K6, K6 // c4e1f998f6 KORTESTD K4, K4 // c4e1f998e4 KORTESTD K6, K4 // c4e1f998e6 KORTESTQ K2, K4 // c4e1f898e2 KORTESTQ K7, K4 // c4e1f898e7 KORTESTQ K2, K5 // c4e1f898ea KORTESTQ K7, K5 // c4e1f898ef KSHIFTLD $0, K5, K0 // c4e37933c500 KSHIFTLD $0, K4, K0 // c4e37933c400 KSHIFTLD $0, K5, K7 // c4e37933fd00 KSHIFTLD $0, K4, K7 // c4e37933fc00 KSHIFTLQ $97, K1, K4 // c4e3f933e161 KSHIFTLQ $97, K3, K4 // c4e3f933e361 KSHIFTLQ $97, K1, K6 // c4e3f933f161 KSHIFTLQ $97, K3, K6 // c4e3f933f361 KSHIFTRD $79, K0, K2 // c4e37931d04f KSHIFTRD $79, K5, K2 // c4e37931d54f KSHIFTRD $79, K0, K7 // c4e37931f84f KSHIFTRD $79, K5, K7 // c4e37931fd4f KSHIFTRQ $64, K1, K6 // c4e3f931f140 KSHIFTRQ $64, K5, K6 // c4e3f931f540 KSHIFTRQ $64, K1, K5 // c4e3f931e940 KSHIFTRQ $64, K5, K5 // c4e3f931ed40 KTESTD K5, K0 // c4e1f999c5 KTESTD K4, K0 // c4e1f999c4 KTESTD K5, K7 // c4e1f999fd KTESTD K4, K7 // c4e1f999fc KTESTQ K1, K4 // c4e1f899e1 KTESTQ K3, K4 // c4e1f899e3 KTESTQ K1, K6 // c4e1f899f1 KTESTQ K3, K6 // c4e1f899f3 KUNPCKDQ K1, K6, K0 // c4e1cc4bc1 KUNPCKDQ K5, K6, K0 // c4e1cc4bc5 KUNPCKDQ K1, K5, K0 // c4e1d44bc1 KUNPCKDQ K5, K5, K0 // c4e1d44bc5 KUNPCKDQ K1, K6, K5 // c4e1cc4be9 KUNPCKDQ K5, K6, K5 // c4e1cc4bed KUNPCKDQ K1, K5, K5 // c4e1d44be9 KUNPCKDQ K5, K5, K5 // c4e1d44bed KUNPCKWD K7, K5, K3 // c5d44bdf KUNPCKWD K6, K5, K3 // c5d44bde KUNPCKWD K7, K4, K3 // c5dc4bdf KUNPCKWD K6, K4, K3 // c5dc4bde KUNPCKWD K7, K5, K1 // c5d44bcf KUNPCKWD K6, K5, K1 // c5d44bce KUNPCKWD K7, K4, K1 // c5dc4bcf KUNPCKWD K6, K4, K1 // c5dc4bce KXNORD K6, K1, K4 // c4e1f546e6 KXNORD K7, K1, K4 // c4e1f546e7 KXNORD K6, K3, K4 // c4e1e546e6 KXNORD K7, K3, K4 // c4e1e546e7 KXNORD K6, K1, K6 // c4e1f546f6 KXNORD K7, K1, K6 // c4e1f546f7 KXNORD K6, K3, K6 // c4e1e546f6 KXNORD K7, K3, K6 // c4e1e546f7 KXNORQ K4, K4, K6 // c4e1dc46f4 KXNORQ K5, K4, K6 // c4e1dc46f5 KXNORQ K4, K6, K6 // c4e1cc46f4 KXNORQ K5, K6, K6 // c4e1cc46f5 KXNORQ K4, K4, K4 // c4e1dc46e4 KXNORQ K5, K4, K4 // c4e1dc46e5 KXNORQ K4, K6, K4 // c4e1cc46e4 KXNORQ K5, K6, K4 // c4e1cc46e5 KXORD K0, K4, K7 // c4e1dd47f8 KXORD K7, K4, K7 // c4e1dd47ff KXORD K0, K6, K7 // c4e1cd47f8 KXORD K7, K6, K7 // c4e1cd47ff KXORD K0, K4, K6 // c4e1dd47f0 KXORD K7, K4, K6 // c4e1dd47f7 KXORD K0, K6, K6 // c4e1cd47f0 KXORD K7, K6, K6 // c4e1cd47f7 KXORQ K1, K4, K5 // c4e1dc47e9 KXORQ K3, K4, K5 // c4e1dc47eb KXORQ K1, K6, K5 // c4e1cc47e9 KXORQ K3, K6, K5 // c4e1cc47eb KXORQ K1, K4, K4 // c4e1dc47e1 KXORQ K3, K4, K4 // c4e1dc47e3 KXORQ K1, K6, K4 // c4e1cc47e1 KXORQ K3, K6, K4 // c4e1cc47e3 VDBPSADBW $65, X15, X17, K3, X5 // 62d3750342ef41 VDBPSADBW $65, 7(AX)(CX*4), X17, K3, X5 // 62f3750342ac880700000041 VDBPSADBW $65, 7(AX)(CX*1), X17, K3, X5 // 62f3750342ac080700000041 VDBPSADBW $67, Y17, Y5, K4, Y19 // 62a3552c42d943 VDBPSADBW $67, 99(R15)(R15*2), Y5, K4, Y19 // 6283552c429c7f6300000043 VDBPSADBW $67, -7(DI), Y5, K4, Y19 // 62e3552c429ff9ffffff43 VDBPSADBW $127, Z3, Z5, K2, Z19 // 62e3554a42db7f VDBPSADBW $127, Z5, Z5, K2, Z19 // 62e3554a42dd7f VDBPSADBW $127, 17(SP)(BP*1), Z5, K2, Z19 // 62e3554a429c2c110000007f VDBPSADBW $127, -7(CX)(DX*8), Z5, K2, Z19 // 62e3554a429cd1f9ffffff7f VDBPSADBW $127, Z3, Z1, K2, Z19 // 62e3754a42db7f VDBPSADBW $127, Z5, Z1, K2, Z19 // 62e3754a42dd7f VDBPSADBW $127, 17(SP)(BP*1), Z1, K2, Z19 // 62e3754a429c2c110000007f VDBPSADBW $127, -7(CX)(DX*8), Z1, K2, Z19 // 62e3754a429cd1f9ffffff7f VDBPSADBW $127, Z3, Z5, K2, Z15 // 6273554a42fb7f VDBPSADBW $127, Z5, Z5, K2, Z15 // 6273554a42fd7f VDBPSADBW $127, 17(SP)(BP*1), Z5, K2, Z15 // 6273554a42bc2c110000007f VDBPSADBW $127, -7(CX)(DX*8), Z5, K2, Z15 // 6273554a42bcd1f9ffffff7f VDBPSADBW $127, Z3, Z1, K2, Z15 // 6273754a42fb7f VDBPSADBW $127, Z5, Z1, K2, Z15 // 6273754a42fd7f VDBPSADBW $127, 17(SP)(BP*1), Z1, K2, Z15 // 6273754a42bc2c110000007f VDBPSADBW $127, -7(CX)(DX*8), Z1, K2, Z15 // 6273754a42bcd1f9ffffff7f VMOVDQU16 X14, K1, X16 // 6231ff097ff0 VMOVDQU16 X14, K1, -17(BP)(SI*2) // 6271ff097fb475efffffff VMOVDQU16 X14, K1, 7(AX)(CX*2) // 6271ff097fb44807000000 VMOVDQU16 X14, K1, X11 // 6251ff097ff3 VMOVDQU16 15(R8)(R14*1), K1, X11 // 6211ff096f9c300f000000 VMOVDQU16 15(R8)(R14*2), K1, X11 // 6211ff096f9c700f000000 VMOVDQU16 Y24, K7, Y18 // 6221ff2f7fc2 VMOVDQU16 Y24, K7, 7(SI)(DI*4) // 6261ff2f7f84be07000000 VMOVDQU16 Y24, K7, -7(DI)(R8*2) // 6221ff2f7f8447f9ffffff VMOVDQU16 Y11, K2, Y8 // 6251ff2a7fd8 VMOVDQU16 17(SP), K2, Y8 // 6271ff2a6f842411000000 VMOVDQU16 -17(BP)(SI*4), K2, Y8 // 6271ff2a6f84b5efffffff VMOVDQU16 Z6, K4, Z22 // 62b1ff4c7ff6 VMOVDQU16 Z8, K4, Z22 // 6231ff4c7fc6 VMOVDQU16 Z6, K4, Z11 // 62d1ff4c7ff3 VMOVDQU16 Z8, K4, Z11 // 6251ff4c7fc3 VMOVDQU16 Z6, K4, (CX) // 62f1ff4c7f31 VMOVDQU16 Z8, K4, (CX) // 6271ff4c7f01 VMOVDQU16 Z6, K4, 99(R15) // 62d1ff4c7fb763000000 VMOVDQU16 Z8, K4, 99(R15) // 6251ff4c7f8763000000 VMOVDQU16 Z12, K1, Z25 // 6211ff497fe1 VMOVDQU16 Z17, K1, Z25 // 6281ff497fc9 VMOVDQU16 99(R15)(R15*2), K1, Z25 // 6201ff496f8c7f63000000 VMOVDQU16 -7(DI), K1, Z25 // 6261ff496f8ff9ffffff VMOVDQU16 Z12, K1, Z12 // 6251ff497fe4 VMOVDQU16 Z17, K1, Z12 // 62c1ff497fcc VMOVDQU16 99(R15)(R15*2), K1, Z12 // 6211ff496fa47f63000000 VMOVDQU16 -7(DI), K1, Z12 // 6271ff496fa7f9ffffff VMOVDQU8 X11, K5, X23 // 62317f0d7fdf VMOVDQU8 X11, K5, -7(CX)(DX*1) // 62717f0d7f9c11f9ffffff VMOVDQU8 X11, K5, -15(R14)(R15*4) // 62117f0d7f9cbef1ffffff VMOVDQU8 X24, K3, X31 // 62017f0b7fc7 VMOVDQU8 15(DX)(BX*1), K3, X31 // 62617f0b6fbc1a0f000000 VMOVDQU8 -7(CX)(DX*2), K3, X31 // 62617f0b6fbc51f9ffffff VMOVDQU8 Y3, K4, Y6 // 62f17f2c7fde VMOVDQU8 Y3, K4, 7(SI)(DI*1) // 62f17f2c7f9c3e07000000 VMOVDQU8 Y3, K4, 15(DX)(BX*8) // 62f17f2c7f9cda0f000000 VMOVDQU8 Y6, K2, Y7 // 62f17f2a7ff7 VMOVDQU8 -7(DI)(R8*1), K2, Y7 // 62b17f2a6fbc07f9ffffff VMOVDQU8 (SP), K2, Y7 // 62f17f2a6f3c24 VMOVDQU8 Z9, K2, Z3 // 62717f4a7fcb VMOVDQU8 Z19, K2, Z3 // 62e17f4a7fdb VMOVDQU8 Z9, K2, Z30 // 62117f4a7fce VMOVDQU8 Z19, K2, Z30 // 62817f4a7fde VMOVDQU8 Z9, K2, 15(R8) // 62517f4a7f880f000000 VMOVDQU8 Z19, K2, 15(R8) // 62c17f4a7f980f000000 VMOVDQU8 Z9, K2, (BP) // 62717f4a7f4d00 VMOVDQU8 Z19, K2, (BP) // 62e17f4a7f5d00 VMOVDQU8 Z11, K3, Z12 // 62517f4b7fdc VMOVDQU8 Z5, K3, Z12 // 62d17f4b7fec VMOVDQU8 15(R8)(R14*8), K3, Z12 // 62117f4b6fa4f00f000000 VMOVDQU8 -15(R14)(R15*2), K3, Z12 // 62117f4b6fa47ef1ffffff VMOVDQU8 Z11, K3, Z22 // 62317f4b7fde VMOVDQU8 Z5, K3, Z22 // 62b17f4b7fee VMOVDQU8 15(R8)(R14*8), K3, Z22 // 62817f4b6fb4f00f000000 VMOVDQU8 -15(R14)(R15*2), K3, Z22 // 62817f4b6fb47ef1ffffff VPABSB X22, K3, X6 // 62b27d0b1cf6 or 62b2fd0b1cf6 VPABSB -7(CX), K3, X6 // 62f27d0b1cb1f9ffffff or 62f2fd0b1cb1f9ffffff VPABSB 15(DX)(BX*4), K3, X6 // 62f27d0b1cb49a0f000000 or 62f2fd0b1cb49a0f000000 VPABSB Y27, K4, Y11 // 62127d2c1cdb or 6212fd2c1cdb VPABSB 15(DX)(BX*1), K4, Y11 // 62727d2c1c9c1a0f000000 or 6272fd2c1c9c1a0f000000 VPABSB -7(CX)(DX*2), K4, Y11 // 62727d2c1c9c51f9ffffff or 6272fd2c1c9c51f9ffffff VPABSB Z6, K5, Z21 // 62e27d4d1cee or 62e2fd4d1cee VPABSB Z9, K5, Z21 // 62c27d4d1ce9 or 62c2fd4d1ce9 VPABSB (AX), K5, Z21 // 62e27d4d1c28 or 62e2fd4d1c28 VPABSB 7(SI), K5, Z21 // 62e27d4d1cae07000000 or 62e2fd4d1cae07000000 VPABSB Z6, K5, Z9 // 62727d4d1cce or 6272fd4d1cce VPABSB Z9, K5, Z9 // 62527d4d1cc9 or 6252fd4d1cc9 VPABSB (AX), K5, Z9 // 62727d4d1c08 or 6272fd4d1c08 VPABSB 7(SI), K5, Z9 // 62727d4d1c8e07000000 or 6272fd4d1c8e07000000 VPABSW X11, K4, X15 // 62527d0c1dfb or 6252fd0c1dfb VPABSW (BX), K4, X15 // 62727d0c1d3b or 6272fd0c1d3b VPABSW -17(BP)(SI*1), K4, X15 // 62727d0c1dbc35efffffff or 6272fd0c1dbc35efffffff VPABSW Y3, K7, Y26 // 62627d2f1dd3 or 6262fd2f1dd3 VPABSW 15(R8), K7, Y26 // 62427d2f1d900f000000 or 6242fd2f1d900f000000 VPABSW (BP), K7, Y26 // 62627d2f1d5500 or 6262fd2f1d5500 VPABSW Z16, K2, Z7 // 62b27d4a1df8 or 62b2fd4a1df8 VPABSW Z25, K2, Z7 // 62927d4a1df9 or 6292fd4a1df9 VPABSW (R8), K2, Z7 // 62d27d4a1d38 or 62d2fd4a1d38 VPABSW 15(DX)(BX*2), K2, Z7 // 62f27d4a1dbc5a0f000000 or 62f2fd4a1dbc5a0f000000 VPABSW Z16, K2, Z21 // 62a27d4a1de8 or 62a2fd4a1de8 VPABSW Z25, K2, Z21 // 62827d4a1de9 or 6282fd4a1de9 VPABSW (R8), K2, Z21 // 62c27d4a1d28 or 62c2fd4a1d28 VPABSW 15(DX)(BX*2), K2, Z21 // 62e27d4a1dac5a0f000000 or 62e2fd4a1dac5a0f000000 VPACKSSDW X13, X19, K5, X1 // 62d165056bcd VPACKSSDW 15(R8)(R14*4), X19, K5, X1 // 629165056b8cb00f000000 VPACKSSDW -7(CX)(DX*4), X19, K5, X1 // 62f165056b8c91f9ffffff VPACKSSDW Y1, Y28, K3, Y8 // 62711d236bc1 VPACKSSDW 15(R8)(R14*8), Y28, K3, Y8 // 62111d236b84f00f000000 VPACKSSDW -15(R14)(R15*2), Y28, K3, Y8 // 62111d236b847ef1ffffff VPACKSSDW Z21, Z12, K4, Z14 // 62311d4c6bf5 VPACKSSDW Z9, Z12, K4, Z14 // 62511d4c6bf1 VPACKSSDW 17(SP)(BP*1), Z12, K4, Z14 // 62711d4c6bb42c11000000 VPACKSSDW -7(CX)(DX*8), Z12, K4, Z14 // 62711d4c6bb4d1f9ffffff VPACKSSDW Z21, Z13, K4, Z14 // 6231154c6bf5 VPACKSSDW Z9, Z13, K4, Z14 // 6251154c6bf1 VPACKSSDW 17(SP)(BP*1), Z13, K4, Z14 // 6271154c6bb42c11000000 VPACKSSDW -7(CX)(DX*8), Z13, K4, Z14 // 6271154c6bb4d1f9ffffff VPACKSSDW Z21, Z12, K4, Z13 // 62311d4c6bed VPACKSSDW Z9, Z12, K4, Z13 // 62511d4c6be9 VPACKSSDW 17(SP)(BP*1), Z12, K4, Z13 // 62711d4c6bac2c11000000 VPACKSSDW -7(CX)(DX*8), Z12, K4, Z13 // 62711d4c6bacd1f9ffffff VPACKSSDW Z21, Z13, K4, Z13 // 6231154c6bed VPACKSSDW Z9, Z13, K4, Z13 // 6251154c6be9 VPACKSSDW 17(SP)(BP*1), Z13, K4, Z13 // 6271154c6bac2c11000000 VPACKSSDW -7(CX)(DX*8), Z13, K4, Z13 // 6271154c6bacd1f9ffffff VPACKSSWB X0, X14, K2, X2 // 62f10d0a63d0 or 62f18d0a63d0 VPACKSSWB (R8), X14, K2, X2 // 62d10d0a6310 or 62d18d0a6310 VPACKSSWB 15(DX)(BX*2), X14, K2, X2 // 62f10d0a63945a0f000000 or 62f18d0a63945a0f000000 VPACKSSWB Y31, Y14, K2, Y23 // 62810d2a63ff or 62818d2a63ff VPACKSSWB -15(R14)(R15*1), Y14, K2, Y23 // 62810d2a63bc3ef1ffffff or 62818d2a63bc3ef1ffffff VPACKSSWB -15(BX), Y14, K2, Y23 // 62e10d2a63bbf1ffffff or 62e18d2a63bbf1ffffff VPACKSSWB Z23, Z27, K3, Z2 // 62b1254363d7 or 62b1a54363d7 VPACKSSWB Z9, Z27, K3, Z2 // 62d1254363d1 or 62d1a54363d1 VPACKSSWB -17(BP)(SI*2), Z27, K3, Z2 // 62f12543639475efffffff or 62f1a543639475efffffff VPACKSSWB 7(AX)(CX*2), Z27, K3, Z2 // 62f1254363944807000000 or 62f1a54363944807000000 VPACKSSWB Z23, Z25, K3, Z2 // 62b1354363d7 or 62b1b54363d7 VPACKSSWB Z9, Z25, K3, Z2 // 62d1354363d1 or 62d1b54363d1 VPACKSSWB -17(BP)(SI*2), Z25, K3, Z2 // 62f13543639475efffffff or 62f1b543639475efffffff VPACKSSWB 7(AX)(CX*2), Z25, K3, Z2 // 62f1354363944807000000 or 62f1b54363944807000000 VPACKSSWB Z23, Z27, K3, Z7 // 62b1254363ff or 62b1a54363ff VPACKSSWB Z9, Z27, K3, Z7 // 62d1254363f9 or 62d1a54363f9 VPACKSSWB -17(BP)(SI*2), Z27, K3, Z7 // 62f1254363bc75efffffff or 62f1a54363bc75efffffff VPACKSSWB 7(AX)(CX*2), Z27, K3, Z7 // 62f1254363bc4807000000 or 62f1a54363bc4807000000 VPACKSSWB Z23, Z25, K3, Z7 // 62b1354363ff or 62b1b54363ff VPACKSSWB Z9, Z25, K3, Z7 // 62d1354363f9 or 62d1b54363f9 VPACKSSWB -17(BP)(SI*2), Z25, K3, Z7 // 62f1354363bc75efffffff or 62f1b54363bc75efffffff VPACKSSWB 7(AX)(CX*2), Z25, K3, Z7 // 62f1354363bc4807000000 or 62f1b54363bc4807000000 VPACKUSDW X11, X25, K3, X0 // 62d235032bc3 VPACKUSDW 17(SP)(BP*1), X25, K3, X0 // 62f235032b842c11000000 VPACKUSDW -7(CX)(DX*8), X25, K3, X0 // 62f235032b84d1f9ffffff VPACKUSDW Y22, Y2, K3, Y25 // 62226d2b2bce VPACKUSDW 7(AX)(CX*4), Y2, K3, Y25 // 62626d2b2b8c8807000000 VPACKUSDW 7(AX)(CX*1), Y2, K3, Y25 // 62626d2b2b8c0807000000 VPACKUSDW Z14, Z3, K2, Z27 // 6242654a2bde VPACKUSDW Z7, Z3, K2, Z27 // 6262654a2bdf VPACKUSDW 15(R8)(R14*1), Z3, K2, Z27 // 6202654a2b9c300f000000 VPACKUSDW 15(R8)(R14*2), Z3, K2, Z27 // 6202654a2b9c700f000000 VPACKUSDW Z14, Z0, K2, Z27 // 62427d4a2bde VPACKUSDW Z7, Z0, K2, Z27 // 62627d4a2bdf VPACKUSDW 15(R8)(R14*1), Z0, K2, Z27 // 62027d4a2b9c300f000000 VPACKUSDW 15(R8)(R14*2), Z0, K2, Z27 // 62027d4a2b9c700f000000 VPACKUSDW Z14, Z3, K2, Z14 // 6252654a2bf6 VPACKUSDW Z7, Z3, K2, Z14 // 6272654a2bf7 VPACKUSDW 15(R8)(R14*1), Z3, K2, Z14 // 6212654a2bb4300f000000 VPACKUSDW 15(R8)(R14*2), Z3, K2, Z14 // 6212654a2bb4700f000000 VPACKUSDW Z14, Z0, K2, Z14 // 62527d4a2bf6 VPACKUSDW Z7, Z0, K2, Z14 // 62727d4a2bf7 VPACKUSDW 15(R8)(R14*1), Z0, K2, Z14 // 62127d4a2bb4300f000000 VPACKUSDW 15(R8)(R14*2), Z0, K2, Z14 // 62127d4a2bb4700f000000 VPACKUSWB X11, X18, K1, X17 // 62c16d0167cb or 62c1ed0167cb VPACKUSWB -17(BP)(SI*2), X18, K1, X17 // 62e16d01678c75efffffff or 62e1ed01678c75efffffff VPACKUSWB 7(AX)(CX*2), X18, K1, X17 // 62e16d01678c4807000000 or 62e1ed01678c4807000000 VPACKUSWB Y9, Y8, K2, Y27 // 62413d2a67d9 or 6241bd2a67d9 VPACKUSWB (SI), Y8, K2, Y27 // 62613d2a671e or 6261bd2a671e VPACKUSWB 7(SI)(DI*2), Y8, K2, Y27 // 62613d2a679c7e07000000 or 6261bd2a679c7e07000000 VPACKUSWB Z1, Z22, K1, Z8 // 62714d4167c1 or 6271cd4167c1 VPACKUSWB Z16, Z22, K1, Z8 // 62314d4167c0 or 6231cd4167c0 VPACKUSWB (R14), Z22, K1, Z8 // 62514d416706 or 6251cd416706 VPACKUSWB -7(DI)(R8*8), Z22, K1, Z8 // 62314d416784c7f9ffffff or 6231cd416784c7f9ffffff VPACKUSWB Z1, Z25, K1, Z8 // 6271354167c1 or 6271b54167c1 VPACKUSWB Z16, Z25, K1, Z8 // 6231354167c0 or 6231b54167c0 VPACKUSWB (R14), Z25, K1, Z8 // 625135416706 or 6251b5416706 VPACKUSWB -7(DI)(R8*8), Z25, K1, Z8 // 623135416784c7f9ffffff or 6231b5416784c7f9ffffff VPACKUSWB Z1, Z22, K1, Z24 // 62614d4167c1 or 6261cd4167c1 VPACKUSWB Z16, Z22, K1, Z24 // 62214d4167c0 or 6221cd4167c0 VPACKUSWB (R14), Z22, K1, Z24 // 62414d416706 or 6241cd416706 VPACKUSWB -7(DI)(R8*8), Z22, K1, Z24 // 62214d416784c7f9ffffff or 6221cd416784c7f9ffffff VPACKUSWB Z1, Z25, K1, Z24 // 6261354167c1 or 6261b54167c1 VPACKUSWB Z16, Z25, K1, Z24 // 6221354167c0 or 6221b54167c0 VPACKUSWB (R14), Z25, K1, Z24 // 624135416706 or 6241b5416706 VPACKUSWB -7(DI)(R8*8), Z25, K1, Z24 // 622135416784c7f9ffffff or 6221b5416784c7f9ffffff VPADDB X24, X2, K7, X9 // 62116d0ffcc8 or 6211ed0ffcc8 VPADDB 15(R8)(R14*1), X2, K7, X9 // 62116d0ffc8c300f000000 or 6211ed0ffc8c300f000000 VPADDB 15(R8)(R14*2), X2, K7, X9 // 62116d0ffc8c700f000000 or 6211ed0ffc8c700f000000 VPADDB Y14, Y9, K1, Y22 // 62c13529fcf6 or 62c1b529fcf6 VPADDB 17(SP)(BP*8), Y9, K1, Y22 // 62e13529fcb4ec11000000 or 62e1b529fcb4ec11000000 VPADDB 17(SP)(BP*4), Y9, K1, Y22 // 62e13529fcb4ac11000000 or 62e1b529fcb4ac11000000 VPADDB Z15, Z0, K1, Z6 // 62d17d49fcf7 or 62d1fd49fcf7 VPADDB Z12, Z0, K1, Z6 // 62d17d49fcf4 or 62d1fd49fcf4 VPADDB 99(R15)(R15*4), Z0, K1, Z6 // 62917d49fcb4bf63000000 or 6291fd49fcb4bf63000000 VPADDB 15(DX), Z0, K1, Z6 // 62f17d49fcb20f000000 or 62f1fd49fcb20f000000 VPADDB Z15, Z8, K1, Z6 // 62d13d49fcf7 or 62d1bd49fcf7 VPADDB Z12, Z8, K1, Z6 // 62d13d49fcf4 or 62d1bd49fcf4 VPADDB 99(R15)(R15*4), Z8, K1, Z6 // 62913d49fcb4bf63000000 or 6291bd49fcb4bf63000000 VPADDB 15(DX), Z8, K1, Z6 // 62f13d49fcb20f000000 or 62f1bd49fcb20f000000 VPADDB Z15, Z0, K1, Z2 // 62d17d49fcd7 or 62d1fd49fcd7 VPADDB Z12, Z0, K1, Z2 // 62d17d49fcd4 or 62d1fd49fcd4 VPADDB 99(R15)(R15*4), Z0, K1, Z2 // 62917d49fc94bf63000000 or 6291fd49fc94bf63000000 VPADDB 15(DX), Z0, K1, Z2 // 62f17d49fc920f000000 or 62f1fd49fc920f000000 VPADDB Z15, Z8, K1, Z2 // 62d13d49fcd7 or 62d1bd49fcd7 VPADDB Z12, Z8, K1, Z2 // 62d13d49fcd4 or 62d1bd49fcd4 VPADDB 99(R15)(R15*4), Z8, K1, Z2 // 62913d49fc94bf63000000 or 6291bd49fc94bf63000000 VPADDB 15(DX), Z8, K1, Z2 // 62f13d49fc920f000000 or 62f1bd49fc920f000000 VPADDSB X15, X11, K4, X3 // 62d1250cecdf or 62d1a50cecdf VPADDSB (CX), X11, K4, X3 // 62f1250cec19 or 62f1a50cec19 VPADDSB 99(R15), X11, K4, X3 // 62d1250cec9f63000000 or 62d1a50cec9f63000000 VPADDSB Y9, Y22, K5, Y31 // 62414d25ecf9 or 6241cd25ecf9 VPADDSB 7(AX), Y22, K5, Y31 // 62614d25ecb807000000 or 6261cd25ecb807000000 VPADDSB (DI), Y22, K5, Y31 // 62614d25ec3f or 6261cd25ec3f VPADDSB Z13, Z28, K7, Z26 // 62411d47ecd5 or 62419d47ecd5 VPADDSB Z21, Z28, K7, Z26 // 62211d47ecd5 or 62219d47ecd5 VPADDSB -7(CX)(DX*1), Z28, K7, Z26 // 62611d47ec9411f9ffffff or 62619d47ec9411f9ffffff VPADDSB -15(R14)(R15*4), Z28, K7, Z26 // 62011d47ec94bef1ffffff or 62019d47ec94bef1ffffff VPADDSB Z13, Z6, K7, Z26 // 62414d4fecd5 or 6241cd4fecd5 VPADDSB Z21, Z6, K7, Z26 // 62214d4fecd5 or 6221cd4fecd5 VPADDSB -7(CX)(DX*1), Z6, K7, Z26 // 62614d4fec9411f9ffffff or 6261cd4fec9411f9ffffff VPADDSB -15(R14)(R15*4), Z6, K7, Z26 // 62014d4fec94bef1ffffff or 6201cd4fec94bef1ffffff VPADDSB Z13, Z28, K7, Z14 // 62511d47ecf5 or 62519d47ecf5 VPADDSB Z21, Z28, K7, Z14 // 62311d47ecf5 or 62319d47ecf5 VPADDSB -7(CX)(DX*1), Z28, K7, Z14 // 62711d47ecb411f9ffffff or 62719d47ecb411f9ffffff VPADDSB -15(R14)(R15*4), Z28, K7, Z14 // 62111d47ecb4bef1ffffff or 62119d47ecb4bef1ffffff VPADDSB Z13, Z6, K7, Z14 // 62514d4fecf5 or 6251cd4fecf5 VPADDSB Z21, Z6, K7, Z14 // 62314d4fecf5 or 6231cd4fecf5 VPADDSB -7(CX)(DX*1), Z6, K7, Z14 // 62714d4fecb411f9ffffff or 6271cd4fecb411f9ffffff VPADDSB -15(R14)(R15*4), Z6, K7, Z14 // 62114d4fecb4bef1ffffff or 6211cd4fecb4bef1ffffff VPADDSW X6, X13, K7, X30 // 6261150fedf6 or 6261950fedf6 VPADDSW 99(R15)(R15*2), X13, K7, X30 // 6201150fedb47f63000000 or 6201950fedb47f63000000 VPADDSW -7(DI), X13, K7, X30 // 6261150fedb7f9ffffff or 6261950fedb7f9ffffff VPADDSW Y5, Y31, K6, Y23 // 62e10526edfd or 62e18526edfd VPADDSW 99(R15)(R15*1), Y31, K6, Y23 // 62810526edbc3f63000000 or 62818526edbc3f63000000 VPADDSW (DX), Y31, K6, Y23 // 62e10526ed3a or 62e18526ed3a VPADDSW Z21, Z3, K3, Z26 // 6221654bedd5 or 6221e54bedd5 VPADDSW Z13, Z3, K3, Z26 // 6241654bedd5 or 6241e54bedd5 VPADDSW 15(DX)(BX*1), Z3, K3, Z26 // 6261654bed941a0f000000 or 6261e54bed941a0f000000 VPADDSW -7(CX)(DX*2), Z3, K3, Z26 // 6261654bed9451f9ffffff or 6261e54bed9451f9ffffff VPADDSW Z21, Z0, K3, Z26 // 62217d4bedd5 or 6221fd4bedd5 VPADDSW Z13, Z0, K3, Z26 // 62417d4bedd5 or 6241fd4bedd5 VPADDSW 15(DX)(BX*1), Z0, K3, Z26 // 62617d4bed941a0f000000 or 6261fd4bed941a0f000000 VPADDSW -7(CX)(DX*2), Z0, K3, Z26 // 62617d4bed9451f9ffffff or 6261fd4bed9451f9ffffff VPADDSW Z21, Z3, K3, Z3 // 62b1654beddd or 62b1e54beddd VPADDSW Z13, Z3, K3, Z3 // 62d1654beddd or 62d1e54beddd VPADDSW 15(DX)(BX*1), Z3, K3, Z3 // 62f1654bed9c1a0f000000 or 62f1e54bed9c1a0f000000 VPADDSW -7(CX)(DX*2), Z3, K3, Z3 // 62f1654bed9c51f9ffffff or 62f1e54bed9c51f9ffffff VPADDSW Z21, Z0, K3, Z3 // 62b17d4beddd or 62b1fd4beddd VPADDSW Z13, Z0, K3, Z3 // 62d17d4beddd or 62d1fd4beddd VPADDSW 15(DX)(BX*1), Z0, K3, Z3 // 62f17d4bed9c1a0f000000 or 62f1fd4bed9c1a0f000000 VPADDSW -7(CX)(DX*2), Z0, K3, Z3 // 62f17d4bed9c51f9ffffff or 62f1fd4bed9c51f9ffffff VPADDUSB X30, X23, K7, X12 // 62114507dce6 or 6211c507dce6 VPADDUSB -7(CX)(DX*1), X23, K7, X12 // 62714507dca411f9ffffff or 6271c507dca411f9ffffff VPADDUSB -15(R14)(R15*4), X23, K7, X12 // 62114507dca4bef1ffffff or 6211c507dca4bef1ffffff VPADDUSB Y19, Y5, K4, Y0 // 62b1552cdcc3 or 62b1d52cdcc3 VPADDUSB -17(BP)(SI*8), Y5, K4, Y0 // 62f1552cdc84f5efffffff or 62f1d52cdc84f5efffffff VPADDUSB (R15), Y5, K4, Y0 // 62d1552cdc07 or 62d1d52cdc07 VPADDUSB Z27, Z3, K4, Z11 // 6211654cdcdb or 6211e54cdcdb VPADDUSB Z15, Z3, K4, Z11 // 6251654cdcdf or 6251e54cdcdf VPADDUSB -17(BP), Z3, K4, Z11 // 6271654cdc9defffffff or 6271e54cdc9defffffff VPADDUSB -15(R14)(R15*8), Z3, K4, Z11 // 6211654cdc9cfef1ffffff or 6211e54cdc9cfef1ffffff VPADDUSB Z27, Z12, K4, Z11 // 62111d4cdcdb or 62119d4cdcdb VPADDUSB Z15, Z12, K4, Z11 // 62511d4cdcdf or 62519d4cdcdf VPADDUSB -17(BP), Z12, K4, Z11 // 62711d4cdc9defffffff or 62719d4cdc9defffffff VPADDUSB -15(R14)(R15*8), Z12, K4, Z11 // 62111d4cdc9cfef1ffffff or 62119d4cdc9cfef1ffffff VPADDUSB Z27, Z3, K4, Z25 // 6201654cdccb or 6201e54cdccb VPADDUSB Z15, Z3, K4, Z25 // 6241654cdccf or 6241e54cdccf VPADDUSB -17(BP), Z3, K4, Z25 // 6261654cdc8defffffff or 6261e54cdc8defffffff VPADDUSB -15(R14)(R15*8), Z3, K4, Z25 // 6201654cdc8cfef1ffffff or 6201e54cdc8cfef1ffffff VPADDUSB Z27, Z12, K4, Z25 // 62011d4cdccb or 62019d4cdccb VPADDUSB Z15, Z12, K4, Z25 // 62411d4cdccf or 62419d4cdccf VPADDUSB -17(BP), Z12, K4, Z25 // 62611d4cdc8defffffff or 62619d4cdc8defffffff VPADDUSB -15(R14)(R15*8), Z12, K4, Z25 // 62011d4cdc8cfef1ffffff or 62019d4cdc8cfef1ffffff VPADDUSW X2, X20, K7, X8 // 62715d07ddc2 or 6271dd07ddc2 VPADDUSW 15(DX)(BX*1), X20, K7, X8 // 62715d07dd841a0f000000 or 6271dd07dd841a0f000000 VPADDUSW -7(CX)(DX*2), X20, K7, X8 // 62715d07dd8451f9ffffff or 6271dd07dd8451f9ffffff VPADDUSW Y2, Y28, K2, Y31 // 62611d22ddfa or 62619d22ddfa VPADDUSW 7(SI)(DI*8), Y28, K2, Y31 // 62611d22ddbcfe07000000 or 62619d22ddbcfe07000000 VPADDUSW -15(R14), Y28, K2, Y31 // 62411d22ddbef1ffffff or 62419d22ddbef1ffffff VPADDUSW Z8, Z23, K5, Z23 // 62c14545ddf8 or 62c1c545ddf8 VPADDUSW Z28, Z23, K5, Z23 // 62814545ddfc or 6281c545ddfc VPADDUSW 17(SP)(BP*2), Z23, K5, Z23 // 62e14545ddbc6c11000000 or 62e1c545ddbc6c11000000 VPADDUSW -7(DI)(R8*4), Z23, K5, Z23 // 62a14545ddbc87f9ffffff or 62a1c545ddbc87f9ffffff VPADDUSW Z8, Z6, K5, Z23 // 62c14d4dddf8 or 62c1cd4dddf8 VPADDUSW Z28, Z6, K5, Z23 // 62814d4dddfc or 6281cd4dddfc VPADDUSW 17(SP)(BP*2), Z6, K5, Z23 // 62e14d4dddbc6c11000000 or 62e1cd4dddbc6c11000000 VPADDUSW -7(DI)(R8*4), Z6, K5, Z23 // 62a14d4dddbc87f9ffffff or 62a1cd4dddbc87f9ffffff VPADDUSW Z8, Z23, K5, Z5 // 62d14545dde8 or 62d1c545dde8 VPADDUSW Z28, Z23, K5, Z5 // 62914545ddec or 6291c545ddec VPADDUSW 17(SP)(BP*2), Z23, K5, Z5 // 62f14545ddac6c11000000 or 62f1c545ddac6c11000000 VPADDUSW -7(DI)(R8*4), Z23, K5, Z5 // 62b14545ddac87f9ffffff or 62b1c545ddac87f9ffffff VPADDUSW Z8, Z6, K5, Z5 // 62d14d4ddde8 or 62d1cd4ddde8 VPADDUSW Z28, Z6, K5, Z5 // 62914d4dddec or 6291cd4dddec VPADDUSW 17(SP)(BP*2), Z6, K5, Z5 // 62f14d4dddac6c11000000 or 62f1cd4dddac6c11000000 VPADDUSW -7(DI)(R8*4), Z6, K5, Z5 // 62b14d4dddac87f9ffffff or 62b1cd4dddac87f9ffffff VPADDW X19, X26, K3, X9 // 62312d03fdcb or 6231ad03fdcb VPADDW -17(BP), X26, K3, X9 // 62712d03fd8defffffff or 6271ad03fd8defffffff VPADDW -15(R14)(R15*8), X26, K3, X9 // 62112d03fd8cfef1ffffff or 6211ad03fd8cfef1ffffff VPADDW Y0, Y27, K4, Y24 // 62612524fdc0 or 6261a524fdc0 VPADDW 7(SI)(DI*1), Y27, K4, Y24 // 62612524fd843e07000000 or 6261a524fd843e07000000 VPADDW 15(DX)(BX*8), Y27, K4, Y24 // 62612524fd84da0f000000 or 6261a524fd84da0f000000 VPADDW Z12, Z16, K2, Z21 // 62c17d42fdec or 62c1fd42fdec VPADDW Z27, Z16, K2, Z21 // 62817d42fdeb or 6281fd42fdeb VPADDW 15(R8), Z16, K2, Z21 // 62c17d42fda80f000000 or 62c1fd42fda80f000000 VPADDW (BP), Z16, K2, Z21 // 62e17d42fd6d00 or 62e1fd42fd6d00 VPADDW Z12, Z13, K2, Z21 // 62c1154afdec or 62c1954afdec VPADDW Z27, Z13, K2, Z21 // 6281154afdeb or 6281954afdeb VPADDW 15(R8), Z13, K2, Z21 // 62c1154afda80f000000 or 62c1954afda80f000000 VPADDW (BP), Z13, K2, Z21 // 62e1154afd6d00 or 62e1954afd6d00 VPADDW Z12, Z16, K2, Z5 // 62d17d42fdec or 62d1fd42fdec VPADDW Z27, Z16, K2, Z5 // 62917d42fdeb or 6291fd42fdeb VPADDW 15(R8), Z16, K2, Z5 // 62d17d42fda80f000000 or 62d1fd42fda80f000000 VPADDW (BP), Z16, K2, Z5 // 62f17d42fd6d00 or 62f1fd42fd6d00 VPADDW Z12, Z13, K2, Z5 // 62d1154afdec or 62d1954afdec VPADDW Z27, Z13, K2, Z5 // 6291154afdeb or 6291954afdeb VPADDW 15(R8), Z13, K2, Z5 // 62d1154afda80f000000 or 62d1954afda80f000000 VPADDW (BP), Z13, K2, Z5 // 62f1154afd6d00 or 62f1954afd6d00 VPALIGNR $13, X16, X31, K2, X0 // 62b305020fc00d or 62b385020fc00d VPALIGNR $13, 17(SP)(BP*2), X31, K2, X0 // 62f305020f846c110000000d or 62f385020f846c110000000d VPALIGNR $13, -7(DI)(R8*4), X31, K2, X0 // 62b305020f8487f9ffffff0d or 62b385020f8487f9ffffff0d VPALIGNR $65, Y3, Y31, K3, Y11 // 627305230fdb41 or 627385230fdb41 VPALIGNR $65, -7(DI)(R8*1), Y31, K3, Y11 // 623305230f9c07f9ffffff41 or 623385230f9c07f9ffffff41 VPALIGNR $65, (SP), Y31, K3, Y11 // 627305230f1c2441 or 627385230f1c2441 VPALIGNR $67, Z25, Z6, K3, Z22 // 62834d4b0ff143 or 6283cd4b0ff143 VPALIGNR $67, Z12, Z6, K3, Z22 // 62c34d4b0ff443 or 62c3cd4b0ff443 VPALIGNR $67, 15(R8)(R14*8), Z6, K3, Z22 // 62834d4b0fb4f00f00000043 or 6283cd4b0fb4f00f00000043 VPALIGNR $67, -15(R14)(R15*2), Z6, K3, Z22 // 62834d4b0fb47ef1ffffff43 or 6283cd4b0fb47ef1ffffff43 VPALIGNR $67, Z25, Z8, K3, Z22 // 62833d4b0ff143 or 6283bd4b0ff143 VPALIGNR $67, Z12, Z8, K3, Z22 // 62c33d4b0ff443 or 62c3bd4b0ff443 VPALIGNR $67, 15(R8)(R14*8), Z8, K3, Z22 // 62833d4b0fb4f00f00000043 or 6283bd4b0fb4f00f00000043 VPALIGNR $67, -15(R14)(R15*2), Z8, K3, Z22 // 62833d4b0fb47ef1ffffff43 or 6283bd4b0fb47ef1ffffff43 VPALIGNR $67, Z25, Z6, K3, Z11 // 62134d4b0fd943 or 6213cd4b0fd943 VPALIGNR $67, Z12, Z6, K3, Z11 // 62534d4b0fdc43 or 6253cd4b0fdc43 VPALIGNR $67, 15(R8)(R14*8), Z6, K3, Z11 // 62134d4b0f9cf00f00000043 or 6213cd4b0f9cf00f00000043 VPALIGNR $67, -15(R14)(R15*2), Z6, K3, Z11 // 62134d4b0f9c7ef1ffffff43 or 6213cd4b0f9c7ef1ffffff43 VPALIGNR $67, Z25, Z8, K3, Z11 // 62133d4b0fd943 or 6213bd4b0fd943 VPALIGNR $67, Z12, Z8, K3, Z11 // 62533d4b0fdc43 or 6253bd4b0fdc43 VPALIGNR $67, 15(R8)(R14*8), Z8, K3, Z11 // 62133d4b0f9cf00f00000043 or 6213bd4b0f9cf00f00000043 VPALIGNR $67, -15(R14)(R15*2), Z8, K3, Z11 // 62133d4b0f9c7ef1ffffff43 or 6213bd4b0f9c7ef1ffffff43 VPAVGB X16, X7, K1, X19 // 62a14509e0d8 or 62a1c509e0d8 VPAVGB (SI), X7, K1, X19 // 62e14509e01e or 62e1c509e01e VPAVGB 7(SI)(DI*2), X7, K1, X19 // 62e14509e09c7e07000000 or 62e1c509e09c7e07000000 VPAVGB Y14, Y19, K3, Y23 // 62c16523e0fe or 62c1e523e0fe VPAVGB 15(R8)(R14*4), Y19, K3, Y23 // 62816523e0bcb00f000000 or 6281e523e0bcb00f000000 VPAVGB -7(CX)(DX*4), Y19, K3, Y23 // 62e16523e0bc91f9ffffff or 62e1e523e0bc91f9ffffff VPAVGB Z2, Z18, K4, Z11 // 62716d44e0da or 6271ed44e0da VPAVGB Z21, Z18, K4, Z11 // 62316d44e0dd or 6231ed44e0dd VPAVGB 7(SI)(DI*4), Z18, K4, Z11 // 62716d44e09cbe07000000 or 6271ed44e09cbe07000000 VPAVGB -7(DI)(R8*2), Z18, K4, Z11 // 62316d44e09c47f9ffffff or 6231ed44e09c47f9ffffff VPAVGB Z2, Z24, K4, Z11 // 62713d44e0da or 6271bd44e0da VPAVGB Z21, Z24, K4, Z11 // 62313d44e0dd or 6231bd44e0dd VPAVGB 7(SI)(DI*4), Z24, K4, Z11 // 62713d44e09cbe07000000 or 6271bd44e09cbe07000000 VPAVGB -7(DI)(R8*2), Z24, K4, Z11 // 62313d44e09c47f9ffffff or 6231bd44e09c47f9ffffff VPAVGB Z2, Z18, K4, Z5 // 62f16d44e0ea or 62f1ed44e0ea VPAVGB Z21, Z18, K4, Z5 // 62b16d44e0ed or 62b1ed44e0ed VPAVGB 7(SI)(DI*4), Z18, K4, Z5 // 62f16d44e0acbe07000000 or 62f1ed44e0acbe07000000 VPAVGB -7(DI)(R8*2), Z18, K4, Z5 // 62b16d44e0ac47f9ffffff or 62b1ed44e0ac47f9ffffff VPAVGB Z2, Z24, K4, Z5 // 62f13d44e0ea or 62f1bd44e0ea VPAVGB Z21, Z24, K4, Z5 // 62b13d44e0ed or 62b1bd44e0ed VPAVGB 7(SI)(DI*4), Z24, K4, Z5 // 62f13d44e0acbe07000000 or 62f1bd44e0acbe07000000 VPAVGB -7(DI)(R8*2), Z24, K4, Z5 // 62b13d44e0ac47f9ffffff or 62b1bd44e0ac47f9ffffff VPAVGW X7, X1, K5, X31 // 6261750de3ff or 6261f50de3ff VPAVGW 17(SP)(BP*8), X1, K5, X31 // 6261750de3bcec11000000 or 6261f50de3bcec11000000 VPAVGW 17(SP)(BP*4), X1, K5, X31 // 6261750de3bcac11000000 or 6261f50de3bcac11000000 VPAVGW Y16, Y5, K7, Y21 // 62a1552fe3e8 or 62a1d52fe3e8 VPAVGW (R8), Y5, K7, Y21 // 62c1552fe328 or 62c1d52fe328 VPAVGW 15(DX)(BX*2), Y5, K7, Y21 // 62e1552fe3ac5a0f000000 or 62e1d52fe3ac5a0f000000 VPAVGW Z6, Z6, K7, Z7 // 62f14d4fe3fe or 62f1cd4fe3fe VPAVGW Z22, Z6, K7, Z7 // 62b14d4fe3fe or 62b1cd4fe3fe VPAVGW 17(SP), Z6, K7, Z7 // 62f14d4fe3bc2411000000 or 62f1cd4fe3bc2411000000 VPAVGW -17(BP)(SI*4), Z6, K7, Z7 // 62f14d4fe3bcb5efffffff or 62f1cd4fe3bcb5efffffff VPAVGW Z6, Z16, K7, Z7 // 62f17d47e3fe or 62f1fd47e3fe VPAVGW Z22, Z16, K7, Z7 // 62b17d47e3fe or 62b1fd47e3fe VPAVGW 17(SP), Z16, K7, Z7 // 62f17d47e3bc2411000000 or 62f1fd47e3bc2411000000 VPAVGW -17(BP)(SI*4), Z16, K7, Z7 // 62f17d47e3bcb5efffffff or 62f1fd47e3bcb5efffffff VPAVGW Z6, Z6, K7, Z13 // 62714d4fe3ee or 6271cd4fe3ee VPAVGW Z22, Z6, K7, Z13 // 62314d4fe3ee or 6231cd4fe3ee VPAVGW 17(SP), Z6, K7, Z13 // 62714d4fe3ac2411000000 or 6271cd4fe3ac2411000000 VPAVGW -17(BP)(SI*4), Z6, K7, Z13 // 62714d4fe3acb5efffffff or 6271cd4fe3acb5efffffff VPAVGW Z6, Z16, K7, Z13 // 62717d47e3ee or 6271fd47e3ee VPAVGW Z22, Z16, K7, Z13 // 62317d47e3ee or 6231fd47e3ee VPAVGW 17(SP), Z16, K7, Z13 // 62717d47e3ac2411000000 or 6271fd47e3ac2411000000 VPAVGW -17(BP)(SI*4), Z16, K7, Z13 // 62717d47e3acb5efffffff or 6271fd47e3acb5efffffff VPBLENDMB X12, X15, K6, X9 // 6252050e66cc VPBLENDMB 7(SI)(DI*4), X15, K6, X9 // 6272050e668cbe07000000 VPBLENDMB -7(DI)(R8*2), X15, K6, X9 // 6232050e668c47f9ffffff VPBLENDMB Y20, Y21, K3, Y2 // 62b2552366d4 VPBLENDMB 17(SP)(BP*1), Y21, K3, Y2 // 62f2552366942c11000000 VPBLENDMB -7(CX)(DX*8), Y21, K3, Y2 // 62f255236694d1f9ffffff VPBLENDMB Z18, Z13, K7, Z1 // 62b2154f66ca VPBLENDMB Z8, Z13, K7, Z1 // 62d2154f66c8 VPBLENDMB 7(AX), Z13, K7, Z1 // 62f2154f668807000000 VPBLENDMB (DI), Z13, K7, Z1 // 62f2154f660f VPBLENDMB Z18, Z13, K7, Z15 // 6232154f66fa VPBLENDMB Z8, Z13, K7, Z15 // 6252154f66f8 VPBLENDMB 7(AX), Z13, K7, Z15 // 6272154f66b807000000 VPBLENDMB (DI), Z13, K7, Z15 // 6272154f663f VPBLENDMW X26, X3, K4, X8 // 6212e50c66c2 VPBLENDMW 99(R15)(R15*1), X3, K4, X8 // 6212e50c66843f63000000 VPBLENDMW (DX), X3, K4, X8 // 6272e50c6602 VPBLENDMW Y3, Y0, K2, Y6 // 62f2fd2a66f3 VPBLENDMW (R14), Y0, K2, Y6 // 62d2fd2a6636 VPBLENDMW -7(DI)(R8*8), Y0, K2, Y6 // 62b2fd2a66b4c7f9ffffff VPBLENDMW Z15, Z3, K2, Z14 // 6252e54a66f7 VPBLENDMW Z30, Z3, K2, Z14 // 6212e54a66f6 VPBLENDMW 7(SI)(DI*8), Z3, K2, Z14 // 6272e54a66b4fe07000000 VPBLENDMW -15(R14), Z3, K2, Z14 // 6252e54a66b6f1ffffff VPBLENDMW Z15, Z12, K2, Z14 // 62529d4a66f7 VPBLENDMW Z30, Z12, K2, Z14 // 62129d4a66f6 VPBLENDMW 7(SI)(DI*8), Z12, K2, Z14 // 62729d4a66b4fe07000000 VPBLENDMW -15(R14), Z12, K2, Z14 // 62529d4a66b6f1ffffff VPBLENDMW Z15, Z3, K2, Z28 // 6242e54a66e7 VPBLENDMW Z30, Z3, K2, Z28 // 6202e54a66e6 VPBLENDMW 7(SI)(DI*8), Z3, K2, Z28 // 6262e54a66a4fe07000000 VPBLENDMW -15(R14), Z3, K2, Z28 // 6242e54a66a6f1ffffff VPBLENDMW Z15, Z12, K2, Z28 // 62429d4a66e7 VPBLENDMW Z30, Z12, K2, Z28 // 62029d4a66e6 VPBLENDMW 7(SI)(DI*8), Z12, K2, Z28 // 62629d4a66a4fe07000000 VPBLENDMW -15(R14), Z12, K2, Z28 // 62429d4a66a6f1ffffff VPBROADCASTB CX, K3, X23 // 62e27d0b7af9 VPBROADCASTB SP, K3, X23 // 62e27d0b7afc VPBROADCASTB R14, K3, Y5 // 62d27d2b7aee VPBROADCASTB AX, K3, Y5 // 62f27d2b7ae8 VPBROADCASTB R9, K3, Z19 // 62c27d4b7ad9 VPBROADCASTB CX, K3, Z19 // 62e27d4b7ad9 VPBROADCASTB R9, K3, Z15 // 62527d4b7af9 VPBROADCASTB CX, K3, Z15 // 62727d4b7af9 VPBROADCASTB X28, K2, X13 // 62127d0a78ec VPBROADCASTB 99(R15)(R15*1), K2, X13 // 62127d0a786c3f63 VPBROADCASTB (DX), K2, X13 // 62727d0a782a VPBROADCASTB X24, K1, Y20 // 62827d2978e0 VPBROADCASTB -17(BP)(SI*8), K1, Y20 // 62e27d297864f5ef VPBROADCASTB (R15), K1, Y20 // 62c27d297827 VPBROADCASTB X9, K2, Z5 // 62d27d4a78e9 VPBROADCASTB 7(SI)(DI*8), K2, Z5 // 62f27d4a786cfe07 VPBROADCASTB -15(R14), K2, Z5 // 62d27d4a786ef1 VPBROADCASTB X9, K2, Z1 // 62d27d4a78c9 VPBROADCASTB 7(SI)(DI*8), K2, Z1 // 62f27d4a784cfe07 VPBROADCASTB -15(R14), K2, Z1 // 62d27d4a784ef1 VPBROADCASTW R14, K7, X20 // 62c27d0f7be6 VPBROADCASTW AX, K7, X20 // 62e27d0f7be0 VPBROADCASTW R9, K7, Y22 // 62c27d2f7bf1 VPBROADCASTW CX, K7, Y22 // 62e27d2f7bf1 VPBROADCASTW SP, K6, Z0 // 62f27d4e7bc4 VPBROADCASTW R14, K6, Z0 // 62d27d4e7bc6 VPBROADCASTW SP, K6, Z11 // 62727d4e7bdc VPBROADCASTW R14, K6, Z11 // 62527d4e7bde VPBROADCASTW X9, K3, X7 // 62d27d0b79f9 VPBROADCASTW 99(R15)(R15*1), K3, X7 // 62927d0b79bc3f63000000 VPBROADCASTW (DX), K3, X7 // 62f27d0b793a VPBROADCASTW X7, K7, Y13 // 62727d2f79ef VPBROADCASTW -17(BP)(SI*8), K7, Y13 // 62727d2f79acf5efffffff VPBROADCASTW (R15), K7, Y13 // 62527d2f792f VPBROADCASTW X14, K4, Z0 // 62d27d4c79c6 VPBROADCASTW 7(SI)(DI*8), K4, Z0 // 62f27d4c7984fe07000000 VPBROADCASTW -15(R14), K4, Z0 // 62d27d4c7986f1ffffff VPBROADCASTW X14, K4, Z25 // 62427d4c79ce VPBROADCASTW 7(SI)(DI*8), K4, Z25 // 62627d4c798cfe07000000 VPBROADCASTW -15(R14), K4, Z25 // 62427d4c798ef1ffffff VPCMPB $81, X1, X21, K4, K5 // 62f355043fe951 VPCMPB $81, 7(SI)(DI*8), X21, K4, K5 // 62f355043facfe0700000051 VPCMPB $81, -15(R14), X21, K4, K5 // 62d355043faef1ffffff51 VPCMPB $81, X1, X21, K4, K4 // 62f355043fe151 VPCMPB $81, 7(SI)(DI*8), X21, K4, K4 // 62f355043fa4fe0700000051 VPCMPB $81, -15(R14), X21, K4, K4 // 62d355043fa6f1ffffff51 VPCMPB $42, Y7, Y17, K7, K4 // 62f375273fe72a VPCMPB $42, (CX), Y17, K7, K4 // 62f375273f212a VPCMPB $42, 99(R15), Y17, K7, K4 // 62d375273fa7630000002a VPCMPB $42, Y7, Y17, K7, K6 // 62f375273ff72a VPCMPB $42, (CX), Y17, K7, K6 // 62f375273f312a VPCMPB $42, 99(R15), Y17, K7, K6 // 62d375273fb7630000002a VPCMPB $79, Z9, Z9, K2, K1 // 62d3354a3fc94f VPCMPB $79, Z28, Z9, K2, K1 // 6293354a3fcc4f VPCMPB $79, -7(DI)(R8*1), Z9, K2, K1 // 62b3354a3f8c07f9ffffff4f VPCMPB $79, (SP), Z9, K2, K1 // 62f3354a3f0c244f VPCMPB $79, Z9, Z25, K2, K1 // 62d335423fc94f VPCMPB $79, Z28, Z25, K2, K1 // 629335423fcc4f VPCMPB $79, -7(DI)(R8*1), Z25, K2, K1 // 62b335423f8c07f9ffffff4f VPCMPB $79, (SP), Z25, K2, K1 // 62f335423f0c244f VPCMPB $79, Z9, Z9, K2, K3 // 62d3354a3fd94f VPCMPB $79, Z28, Z9, K2, K3 // 6293354a3fdc4f VPCMPB $79, -7(DI)(R8*1), Z9, K2, K3 // 62b3354a3f9c07f9ffffff4f VPCMPB $79, (SP), Z9, K2, K3 // 62f3354a3f1c244f VPCMPB $79, Z9, Z25, K2, K3 // 62d335423fd94f VPCMPB $79, Z28, Z25, K2, K3 // 629335423fdc4f VPCMPB $79, -7(DI)(R8*1), Z25, K2, K3 // 62b335423f9c07f9ffffff4f VPCMPB $79, (SP), Z25, K2, K3 // 62f335423f1c244f VPCMPEQB X30, X0, K2, K4 // 62917d0a74e6 or 6291fd0a74e6 VPCMPEQB -7(DI)(R8*1), X0, K2, K4 // 62b17d0a74a407f9ffffff or 62b1fd0a74a407f9ffffff VPCMPEQB (SP), X0, K2, K4 // 62f17d0a742424 or 62f1fd0a742424 VPCMPEQB X30, X0, K2, K5 // 62917d0a74ee or 6291fd0a74ee VPCMPEQB -7(DI)(R8*1), X0, K2, K5 // 62b17d0a74ac07f9ffffff or 62b1fd0a74ac07f9ffffff VPCMPEQB (SP), X0, K2, K5 // 62f17d0a742c24 or 62f1fd0a742c24 VPCMPEQB Y1, Y8, K2, K2 // 62f13d2a74d1 or 62f1bd2a74d1 VPCMPEQB -7(CX)(DX*1), Y8, K2, K2 // 62f13d2a749411f9ffffff or 62f1bd2a749411f9ffffff VPCMPEQB -15(R14)(R15*4), Y8, K2, K2 // 62913d2a7494bef1ffffff or 6291bd2a7494bef1ffffff VPCMPEQB Y1, Y8, K2, K7 // 62f13d2a74f9 or 62f1bd2a74f9 VPCMPEQB -7(CX)(DX*1), Y8, K2, K7 // 62f13d2a74bc11f9ffffff or 62f1bd2a74bc11f9ffffff VPCMPEQB -15(R14)(R15*4), Y8, K2, K7 // 62913d2a74bcbef1ffffff or 6291bd2a74bcbef1ffffff VPCMPEQB Z31, Z17, K3, K0 // 6291754374c7 or 6291f54374c7 VPCMPEQB Z0, Z17, K3, K0 // 62f1754374c0 or 62f1f54374c0 VPCMPEQB 99(R15)(R15*8), Z17, K3, K0 // 629175437484ff63000000 or 6291f5437484ff63000000 VPCMPEQB 7(AX)(CX*8), Z17, K3, K0 // 62f175437484c807000000 or 62f1f5437484c807000000 VPCMPEQB Z31, Z23, K3, K0 // 6291454374c7 or 6291c54374c7 VPCMPEQB Z0, Z23, K3, K0 // 62f1454374c0 or 62f1c54374c0 VPCMPEQB 99(R15)(R15*8), Z23, K3, K0 // 629145437484ff63000000 or 6291c5437484ff63000000 VPCMPEQB 7(AX)(CX*8), Z23, K3, K0 // 62f145437484c807000000 or 62f1c5437484c807000000 VPCMPEQB Z31, Z17, K3, K5 // 6291754374ef or 6291f54374ef VPCMPEQB Z0, Z17, K3, K5 // 62f1754374e8 or 62f1f54374e8 VPCMPEQB 99(R15)(R15*8), Z17, K3, K5 // 6291754374acff63000000 or 6291f54374acff63000000 VPCMPEQB 7(AX)(CX*8), Z17, K3, K5 // 62f1754374acc807000000 or 62f1f54374acc807000000 VPCMPEQB Z31, Z23, K3, K5 // 6291454374ef or 6291c54374ef VPCMPEQB Z0, Z23, K3, K5 // 62f1454374e8 or 62f1c54374e8 VPCMPEQB 99(R15)(R15*8), Z23, K3, K5 // 6291454374acff63000000 or 6291c54374acff63000000 VPCMPEQB 7(AX)(CX*8), Z23, K3, K5 // 62f1454374acc807000000 or 62f1c54374acc807000000 VPCMPEQW X8, X19, K7, K0 // 62d1650775c0 or 62d1e50775c0 VPCMPEQW (AX), X19, K7, K0 // 62f165077500 or 62f1e5077500 VPCMPEQW 7(SI), X19, K7, K0 // 62f16507758607000000 or 62f1e507758607000000 VPCMPEQW X8, X19, K7, K7 // 62d1650775f8 or 62d1e50775f8 VPCMPEQW (AX), X19, K7, K7 // 62f165077538 or 62f1e5077538 VPCMPEQW 7(SI), X19, K7, K7 // 62f1650775be07000000 or 62f1e50775be07000000 VPCMPEQW Y12, Y21, K1, K5 // 62d1552175ec or 62d1d52175ec VPCMPEQW 17(SP)(BP*2), Y21, K1, K5 // 62f1552175ac6c11000000 or 62f1d52175ac6c11000000 VPCMPEQW -7(DI)(R8*4), Y21, K1, K5 // 62b1552175ac87f9ffffff or 62b1d52175ac87f9ffffff VPCMPEQW Y12, Y21, K1, K4 // 62d1552175e4 or 62d1d52175e4 VPCMPEQW 17(SP)(BP*2), Y21, K1, K4 // 62f1552175a46c11000000 or 62f1d52175a46c11000000 VPCMPEQW -7(DI)(R8*4), Y21, K1, K4 // 62b1552175a487f9ffffff or 62b1d52175a487f9ffffff VPCMPEQW Z26, Z30, K1, K4 // 62910d4175e2 or 62918d4175e2 VPCMPEQW Z22, Z30, K1, K4 // 62b10d4175e6 or 62b18d4175e6 VPCMPEQW 15(R8)(R14*4), Z30, K1, K4 // 62910d4175a4b00f000000 or 62918d4175a4b00f000000 VPCMPEQW -7(CX)(DX*4), Z30, K1, K4 // 62f10d4175a491f9ffffff or 62f18d4175a491f9ffffff VPCMPEQW Z26, Z5, K1, K4 // 6291554975e2 or 6291d54975e2 VPCMPEQW Z22, Z5, K1, K4 // 62b1554975e6 or 62b1d54975e6 VPCMPEQW 15(R8)(R14*4), Z5, K1, K4 // 6291554975a4b00f000000 or 6291d54975a4b00f000000 VPCMPEQW -7(CX)(DX*4), Z5, K1, K4 // 62f1554975a491f9ffffff or 62f1d54975a491f9ffffff VPCMPEQW Z26, Z30, K1, K6 // 62910d4175f2 or 62918d4175f2 VPCMPEQW Z22, Z30, K1, K6 // 62b10d4175f6 or 62b18d4175f6 VPCMPEQW 15(R8)(R14*4), Z30, K1, K6 // 62910d4175b4b00f000000 or 62918d4175b4b00f000000 VPCMPEQW -7(CX)(DX*4), Z30, K1, K6 // 62f10d4175b491f9ffffff or 62f18d4175b491f9ffffff VPCMPEQW Z26, Z5, K1, K6 // 6291554975f2 or 6291d54975f2 VPCMPEQW Z22, Z5, K1, K6 // 62b1554975f6 or 62b1d54975f6 VPCMPEQW 15(R8)(R14*4), Z5, K1, K6 // 6291554975b4b00f000000 or 6291d54975b4b00f000000 VPCMPEQW -7(CX)(DX*4), Z5, K1, K6 // 62f1554975b491f9ffffff or 62f1d54975b491f9ffffff VPCMPGTB X26, X8, K1, K1 // 62913d0964ca or 6291bd0964ca VPCMPGTB (BX), X8, K1, K1 // 62f13d09640b or 62f1bd09640b VPCMPGTB -17(BP)(SI*1), X8, K1, K1 // 62f13d09648c35efffffff or 62f1bd09648c35efffffff VPCMPGTB X26, X8, K1, K3 // 62913d0964da or 6291bd0964da VPCMPGTB (BX), X8, K1, K3 // 62f13d09641b or 62f1bd09641b VPCMPGTB -17(BP)(SI*1), X8, K1, K3 // 62f13d09649c35efffffff or 62f1bd09649c35efffffff VPCMPGTB Y1, Y9, K7, K6 // 62f1352f64f1 or 62f1b52f64f1 VPCMPGTB 15(R8), Y9, K7, K6 // 62d1352f64b00f000000 or 62d1b52f64b00f000000 VPCMPGTB (BP), Y9, K7, K6 // 62f1352f647500 or 62f1b52f647500 VPCMPGTB Y1, Y9, K7, K7 // 62f1352f64f9 or 62f1b52f64f9 VPCMPGTB 15(R8), Y9, K7, K7 // 62d1352f64b80f000000 or 62d1b52f64b80f000000 VPCMPGTB (BP), Y9, K7, K7 // 62f1352f647d00 or 62f1b52f647d00 VPCMPGTB Z16, Z7, K2, K6 // 62b1454a64f0 or 62b1c54a64f0 VPCMPGTB Z25, Z7, K2, K6 // 6291454a64f1 or 6291c54a64f1 VPCMPGTB (R8), Z7, K2, K6 // 62d1454a6430 or 62d1c54a6430 VPCMPGTB 15(DX)(BX*2), Z7, K2, K6 // 62f1454a64b45a0f000000 or 62f1c54a64b45a0f000000 VPCMPGTB Z16, Z21, K2, K6 // 62b1554264f0 or 62b1d54264f0 VPCMPGTB Z25, Z21, K2, K6 // 6291554264f1 or 6291d54264f1 VPCMPGTB (R8), Z21, K2, K6 // 62d155426430 or 62d1d5426430 VPCMPGTB 15(DX)(BX*2), Z21, K2, K6 // 62f1554264b45a0f000000 or 62f1d54264b45a0f000000 VPCMPGTB Z16, Z7, K2, K4 // 62b1454a64e0 or 62b1c54a64e0 VPCMPGTB Z25, Z7, K2, K4 // 6291454a64e1 or 6291c54a64e1 VPCMPGTB (R8), Z7, K2, K4 // 62d1454a6420 or 62d1c54a6420 VPCMPGTB 15(DX)(BX*2), Z7, K2, K4 // 62f1454a64a45a0f000000 or 62f1c54a64a45a0f000000 VPCMPGTB Z16, Z21, K2, K4 // 62b1554264e0 or 62b1d54264e0 VPCMPGTB Z25, Z21, K2, K4 // 6291554264e1 or 6291d54264e1 VPCMPGTB (R8), Z21, K2, K4 // 62d155426420 or 62d1d5426420 VPCMPGTB 15(DX)(BX*2), Z21, K2, K4 // 62f1554264a45a0f000000 or 62f1d54264a45a0f000000 VPCMPGTW X11, X23, K7, K3 // 62d1450765db or 62d1c50765db VPCMPGTW 17(SP)(BP*1), X23, K7, K3 // 62f14507659c2c11000000 or 62f1c507659c2c11000000 VPCMPGTW -7(CX)(DX*8), X23, K7, K3 // 62f14507659cd1f9ffffff or 62f1c507659cd1f9ffffff VPCMPGTW X11, X23, K7, K1 // 62d1450765cb or 62d1c50765cb VPCMPGTW 17(SP)(BP*1), X23, K7, K1 // 62f14507658c2c11000000 or 62f1c507658c2c11000000 VPCMPGTW -7(CX)(DX*8), X23, K7, K1 // 62f14507658cd1f9ffffff or 62f1c507658cd1f9ffffff VPCMPGTW Y21, Y12, K6, K5 // 62b11d2e65ed or 62b19d2e65ed VPCMPGTW 7(AX)(CX*4), Y12, K6, K5 // 62f11d2e65ac8807000000 or 62f19d2e65ac8807000000 VPCMPGTW 7(AX)(CX*1), Y12, K6, K5 // 62f11d2e65ac0807000000 or 62f19d2e65ac0807000000 VPCMPGTW Y21, Y12, K6, K4 // 62b11d2e65e5 or 62b19d2e65e5 VPCMPGTW 7(AX)(CX*4), Y12, K6, K4 // 62f11d2e65a48807000000 or 62f19d2e65a48807000000 VPCMPGTW 7(AX)(CX*1), Y12, K6, K4 // 62f11d2e65a40807000000 or 62f19d2e65a40807000000 VPCMPGTW Z23, Z27, K3, K7 // 62b1254365ff or 62b1a54365ff VPCMPGTW Z9, Z27, K3, K7 // 62d1254365f9 or 62d1a54365f9 VPCMPGTW 15(R8)(R14*1), Z27, K3, K7 // 6291254365bc300f000000 or 6291a54365bc300f000000 VPCMPGTW 15(R8)(R14*2), Z27, K3, K7 // 6291254365bc700f000000 or 6291a54365bc700f000000 VPCMPGTW Z23, Z25, K3, K7 // 62b1354365ff or 62b1b54365ff VPCMPGTW Z9, Z25, K3, K7 // 62d1354365f9 or 62d1b54365f9 VPCMPGTW 15(R8)(R14*1), Z25, K3, K7 // 6291354365bc300f000000 or 6291b54365bc300f000000 VPCMPGTW 15(R8)(R14*2), Z25, K3, K7 // 6291354365bc700f000000 or 6291b54365bc700f000000 VPCMPGTW Z23, Z27, K3, K6 // 62b1254365f7 or 62b1a54365f7 VPCMPGTW Z9, Z27, K3, K6 // 62d1254365f1 or 62d1a54365f1 VPCMPGTW 15(R8)(R14*1), Z27, K3, K6 // 6291254365b4300f000000 or 6291a54365b4300f000000 VPCMPGTW 15(R8)(R14*2), Z27, K3, K6 // 6291254365b4700f000000 or 6291a54365b4700f000000 VPCMPGTW Z23, Z25, K3, K6 // 62b1354365f7 or 62b1b54365f7 VPCMPGTW Z9, Z25, K3, K6 // 62d1354365f1 or 62d1b54365f1 VPCMPGTW 15(R8)(R14*1), Z25, K3, K6 // 6291354365b4300f000000 or 6291b54365b4300f000000 VPCMPGTW 15(R8)(R14*2), Z25, K3, K6 // 6291354365b4700f000000 or 6291b54365b4700f000000 VPCMPUB $121, X0, X14, K7, K4 // 62f30d0f3ee079 VPCMPUB $121, 15(R8)(R14*1), X14, K7, K4 // 62930d0f3ea4300f00000079 VPCMPUB $121, 15(R8)(R14*2), X14, K7, K4 // 62930d0f3ea4700f00000079 VPCMPUB $121, X0, X14, K7, K6 // 62f30d0f3ef079 VPCMPUB $121, 15(R8)(R14*1), X14, K7, K6 // 62930d0f3eb4300f00000079 VPCMPUB $121, 15(R8)(R14*2), X14, K7, K6 // 62930d0f3eb4700f00000079 VPCMPUB $13, Y7, Y26, K2, K1 // 62f32d223ecf0d VPCMPUB $13, 17(SP)(BP*8), Y26, K2, K1 // 62f32d223e8cec110000000d VPCMPUB $13, 17(SP)(BP*4), Y26, K2, K1 // 62f32d223e8cac110000000d VPCMPUB $13, Y7, Y26, K2, K3 // 62f32d223edf0d VPCMPUB $13, 17(SP)(BP*8), Y26, K2, K3 // 62f32d223e9cec110000000d VPCMPUB $13, 17(SP)(BP*4), Y26, K2, K3 // 62f32d223e9cac110000000d VPCMPUB $65, Z8, Z14, K5, K6 // 62d30d4d3ef041 VPCMPUB $65, Z24, Z14, K5, K6 // 62930d4d3ef041 VPCMPUB $65, 99(R15)(R15*4), Z14, K5, K6 // 62930d4d3eb4bf6300000041 VPCMPUB $65, 15(DX), Z14, K5, K6 // 62f30d4d3eb20f00000041 VPCMPUB $65, Z8, Z7, K5, K6 // 62d3454d3ef041 VPCMPUB $65, Z24, Z7, K5, K6 // 6293454d3ef041 VPCMPUB $65, 99(R15)(R15*4), Z7, K5, K6 // 6293454d3eb4bf6300000041 VPCMPUB $65, 15(DX), Z7, K5, K6 // 62f3454d3eb20f00000041 VPCMPUB $65, Z8, Z14, K5, K7 // 62d30d4d3ef841 VPCMPUB $65, Z24, Z14, K5, K7 // 62930d4d3ef841 VPCMPUB $65, 99(R15)(R15*4), Z14, K5, K7 // 62930d4d3ebcbf6300000041 VPCMPUB $65, 15(DX), Z14, K5, K7 // 62f30d4d3eba0f00000041 VPCMPUB $65, Z8, Z7, K5, K7 // 62d3454d3ef841 VPCMPUB $65, Z24, Z7, K5, K7 // 6293454d3ef841 VPCMPUB $65, 99(R15)(R15*4), Z7, K5, K7 // 6293454d3ebcbf6300000041 VPCMPUB $65, 15(DX), Z7, K5, K7 // 62f3454d3eba0f00000041 VPCMPUW $79, X25, X5, K3, K1 // 6293d50b3ec94f VPCMPUW $79, (CX), X5, K3, K1 // 62f3d50b3e094f VPCMPUW $79, 99(R15), X5, K3, K1 // 62d3d50b3e8f630000004f VPCMPUW $79, X25, X5, K3, K5 // 6293d50b3ee94f VPCMPUW $79, (CX), X5, K3, K5 // 62f3d50b3e294f VPCMPUW $79, 99(R15), X5, K3, K5 // 62d3d50b3eaf630000004f VPCMPUW $64, Y6, Y22, K2, K3 // 62f3cd223ede40 VPCMPUW $64, 7(AX), Y22, K2, K3 // 62f3cd223e980700000040 VPCMPUW $64, (DI), Y22, K2, K3 // 62f3cd223e1f40 VPCMPUW $64, Y6, Y22, K2, K1 // 62f3cd223ece40 VPCMPUW $64, 7(AX), Y22, K2, K1 // 62f3cd223e880700000040 VPCMPUW $64, (DI), Y22, K2, K1 // 62f3cd223e0f40 VPCMPUW $27, Z14, Z15, K1, K5 // 62d385493eee1b VPCMPUW $27, Z27, Z15, K1, K5 // 629385493eeb1b VPCMPUW $27, -7(CX)(DX*1), Z15, K1, K5 // 62f385493eac11f9ffffff1b VPCMPUW $27, -15(R14)(R15*4), Z15, K1, K5 // 629385493eacbef1ffffff1b VPCMPUW $27, Z14, Z12, K1, K5 // 62d39d493eee1b VPCMPUW $27, Z27, Z12, K1, K5 // 62939d493eeb1b VPCMPUW $27, -7(CX)(DX*1), Z12, K1, K5 // 62f39d493eac11f9ffffff1b VPCMPUW $27, -15(R14)(R15*4), Z12, K1, K5 // 62939d493eacbef1ffffff1b VPCMPUW $27, Z14, Z15, K1, K4 // 62d385493ee61b VPCMPUW $27, Z27, Z15, K1, K4 // 629385493ee31b VPCMPUW $27, -7(CX)(DX*1), Z15, K1, K4 // 62f385493ea411f9ffffff1b VPCMPUW $27, -15(R14)(R15*4), Z15, K1, K4 // 629385493ea4bef1ffffff1b VPCMPUW $27, Z14, Z12, K1, K4 // 62d39d493ee61b VPCMPUW $27, Z27, Z12, K1, K4 // 62939d493ee31b VPCMPUW $27, -7(CX)(DX*1), Z12, K1, K4 // 62f39d493ea411f9ffffff1b VPCMPUW $27, -15(R14)(R15*4), Z12, K1, K4 // 62939d493ea4bef1ffffff1b VPCMPW $47, X9, X0, K2, K7 // 62d3fd0a3ff92f VPCMPW $47, 99(R15)(R15*2), X0, K2, K7 // 6293fd0a3fbc7f630000002f VPCMPW $47, -7(DI), X0, K2, K7 // 62f3fd0a3fbff9ffffff2f VPCMPW $47, X9, X0, K2, K6 // 62d3fd0a3ff12f VPCMPW $47, 99(R15)(R15*2), X0, K2, K6 // 6293fd0a3fb47f630000002f VPCMPW $47, -7(DI), X0, K2, K6 // 62f3fd0a3fb7f9ffffff2f VPCMPW $82, Y7, Y21, K1, K4 // 62f3d5213fe752 VPCMPW $82, 99(R15)(R15*1), Y21, K1, K4 // 6293d5213fa43f6300000052 VPCMPW $82, (DX), Y21, K1, K4 // 62f3d5213f2252 VPCMPW $82, Y7, Y21, K1, K6 // 62f3d5213ff752 VPCMPW $82, 99(R15)(R15*1), Y21, K1, K6 // 6293d5213fb43f6300000052 VPCMPW $82, (DX), Y21, K1, K6 // 62f3d5213f3252 VPCMPW $126, Z13, Z11, K7, K0 // 62d3a54f3fc57e VPCMPW $126, Z14, Z11, K7, K0 // 62d3a54f3fc67e VPCMPW $126, 15(DX)(BX*1), Z11, K7, K0 // 62f3a54f3f841a0f0000007e VPCMPW $126, -7(CX)(DX*2), Z11, K7, K0 // 62f3a54f3f8451f9ffffff7e VPCMPW $126, Z13, Z5, K7, K0 // 62d3d54f3fc57e VPCMPW $126, Z14, Z5, K7, K0 // 62d3d54f3fc67e VPCMPW $126, 15(DX)(BX*1), Z5, K7, K0 // 62f3d54f3f841a0f0000007e VPCMPW $126, -7(CX)(DX*2), Z5, K7, K0 // 62f3d54f3f8451f9ffffff7e VPCMPW $126, Z13, Z11, K7, K7 // 62d3a54f3ffd7e VPCMPW $126, Z14, Z11, K7, K7 // 62d3a54f3ffe7e VPCMPW $126, 15(DX)(BX*1), Z11, K7, K7 // 62f3a54f3fbc1a0f0000007e VPCMPW $126, -7(CX)(DX*2), Z11, K7, K7 // 62f3a54f3fbc51f9ffffff7e VPCMPW $126, Z13, Z5, K7, K7 // 62d3d54f3ffd7e VPCMPW $126, Z14, Z5, K7, K7 // 62d3d54f3ffe7e VPCMPW $126, 15(DX)(BX*1), Z5, K7, K7 // 62f3d54f3fbc1a0f0000007e VPCMPW $126, -7(CX)(DX*2), Z5, K7, K7 // 62f3d54f3fbc51f9ffffff7e VPERMI2W X16, X20, K2, X7 // 62b2dd0275f8 VPERMI2W 7(SI)(DI*1), X20, K2, X7 // 62f2dd0275bc3e07000000 VPERMI2W 15(DX)(BX*8), X20, K2, X7 // 62f2dd0275bcda0f000000 VPERMI2W Y18, Y14, K5, Y12 // 62328d2d75e2 VPERMI2W -7(CX)(DX*1), Y14, K5, Y12 // 62728d2d75a411f9ffffff VPERMI2W -15(R14)(R15*4), Y14, K5, Y12 // 62128d2d75a4bef1ffffff VPERMI2W Z28, Z12, K3, Z1 // 62929d4b75cc VPERMI2W Z13, Z12, K3, Z1 // 62d29d4b75cd VPERMI2W 99(R15)(R15*8), Z12, K3, Z1 // 62929d4b758cff63000000 VPERMI2W 7(AX)(CX*8), Z12, K3, Z1 // 62f29d4b758cc807000000 VPERMI2W Z28, Z16, K3, Z1 // 6292fd4375cc VPERMI2W Z13, Z16, K3, Z1 // 62d2fd4375cd VPERMI2W 99(R15)(R15*8), Z16, K3, Z1 // 6292fd43758cff63000000 VPERMI2W 7(AX)(CX*8), Z16, K3, Z1 // 62f2fd43758cc807000000 VPERMI2W Z28, Z12, K3, Z3 // 62929d4b75dc VPERMI2W Z13, Z12, K3, Z3 // 62d29d4b75dd VPERMI2W 99(R15)(R15*8), Z12, K3, Z3 // 62929d4b759cff63000000 VPERMI2W 7(AX)(CX*8), Z12, K3, Z3 // 62f29d4b759cc807000000 VPERMI2W Z28, Z16, K3, Z3 // 6292fd4375dc VPERMI2W Z13, Z16, K3, Z3 // 62d2fd4375dd VPERMI2W 99(R15)(R15*8), Z16, K3, Z3 // 6292fd43759cff63000000 VPERMI2W 7(AX)(CX*8), Z16, K3, Z3 // 62f2fd43759cc807000000 VPERMT2W X0, X0, K3, X14 // 6272fd0b7df0 VPERMT2W 15(R8)(R14*1), X0, K3, X14 // 6212fd0b7db4300f000000 VPERMT2W 15(R8)(R14*2), X0, K3, X14 // 6212fd0b7db4700f000000 VPERMT2W Y8, Y27, K2, Y22 // 62c2a5227df0 VPERMT2W 7(SI)(DI*8), Y27, K2, Y22 // 62e2a5227db4fe07000000 VPERMT2W -15(R14), Y27, K2, Y22 // 62c2a5227db6f1ffffff VPERMT2W Z22, Z8, K1, Z14 // 6232bd497df6 VPERMT2W Z25, Z8, K1, Z14 // 6212bd497df1 VPERMT2W 17(SP)(BP*2), Z8, K1, Z14 // 6272bd497db46c11000000 VPERMT2W -7(DI)(R8*4), Z8, K1, Z14 // 6232bd497db487f9ffffff VPERMT2W Z22, Z24, K1, Z14 // 6232bd417df6 VPERMT2W Z25, Z24, K1, Z14 // 6212bd417df1 VPERMT2W 17(SP)(BP*2), Z24, K1, Z14 // 6272bd417db46c11000000 VPERMT2W -7(DI)(R8*4), Z24, K1, Z14 // 6232bd417db487f9ffffff VPERMT2W Z22, Z8, K1, Z7 // 62b2bd497dfe VPERMT2W Z25, Z8, K1, Z7 // 6292bd497df9 VPERMT2W 17(SP)(BP*2), Z8, K1, Z7 // 62f2bd497dbc6c11000000 VPERMT2W -7(DI)(R8*4), Z8, K1, Z7 // 62b2bd497dbc87f9ffffff VPERMT2W Z22, Z24, K1, Z7 // 62b2bd417dfe VPERMT2W Z25, Z24, K1, Z7 // 6292bd417df9 VPERMT2W 17(SP)(BP*2), Z24, K1, Z7 // 62f2bd417dbc6c11000000 VPERMT2W -7(DI)(R8*4), Z24, K1, Z7 // 62b2bd417dbc87f9ffffff VPERMW X17, X11, K2, X25 // 6222a50a8dc9 VPERMW (R14), X11, K2, X25 // 6242a50a8d0e VPERMW -7(DI)(R8*8), X11, K2, X25 // 6222a50a8d8cc7f9ffffff VPERMW Y9, Y22, K1, Y9 // 6252cd218dc9 VPERMW 7(SI)(DI*1), Y22, K1, Y9 // 6272cd218d8c3e07000000 VPERMW 15(DX)(BX*8), Y22, K1, Y9 // 6272cd218d8cda0f000000 VPERMW Z0, Z6, K7, Z1 // 62f2cd4f8dc8 VPERMW Z8, Z6, K7, Z1 // 62d2cd4f8dc8 VPERMW 15(R8), Z6, K7, Z1 // 62d2cd4f8d880f000000 VPERMW (BP), Z6, K7, Z1 // 62f2cd4f8d4d00 VPERMW Z0, Z2, K7, Z1 // 62f2ed4f8dc8 VPERMW Z8, Z2, K7, Z1 // 62d2ed4f8dc8 VPERMW 15(R8), Z2, K7, Z1 // 62d2ed4f8d880f000000 VPERMW (BP), Z2, K7, Z1 // 62f2ed4f8d4d00 VPERMW Z0, Z6, K7, Z16 // 62e2cd4f8dc0 VPERMW Z8, Z6, K7, Z16 // 62c2cd4f8dc0 VPERMW 15(R8), Z6, K7, Z16 // 62c2cd4f8d800f000000 VPERMW (BP), Z6, K7, Z16 // 62e2cd4f8d4500 VPERMW Z0, Z2, K7, Z16 // 62e2ed4f8dc0 VPERMW Z8, Z2, K7, Z16 // 62c2ed4f8dc0 VPERMW 15(R8), Z2, K7, Z16 // 62c2ed4f8d800f000000 VPERMW (BP), Z2, K7, Z16 // 62e2ed4f8d4500 VPEXTRB $79, X26, AX // 62637d0814d04f or 6263fd0814d04f VPEXTRB $79, X26, R9 // 62437d0814d14f or 6243fd0814d14f VPEXTRB $79, X26, 7(SI)(DI*1) // 62637d0814543e074f or 6263fd0814543e074f VPEXTRB $79, X26, 15(DX)(BX*8) // 62637d081454da0f4f or 6263fd081454da0f4f VPMADDUBSW X21, X16, K2, X0 // 62b27d0204c5 or 62b2fd0204c5 VPMADDUBSW 15(R8)(R14*8), X16, K2, X0 // 62927d020484f00f000000 or 6292fd020484f00f000000 VPMADDUBSW -15(R14)(R15*2), X16, K2, X0 // 62927d0204847ef1ffffff or 6292fd0204847ef1ffffff VPMADDUBSW Y3, Y31, K4, Y11 // 6272052404db or 6272852404db VPMADDUBSW -17(BP)(SI*2), Y31, K4, Y11 // 62720524049c75efffffff or 62728524049c75efffffff VPMADDUBSW 7(AX)(CX*2), Y31, K4, Y11 // 62720524049c4807000000 or 62728524049c4807000000 VPMADDUBSW Z6, Z22, K1, Z12 // 62724d4104e6 or 6272cd4104e6 VPMADDUBSW Z8, Z22, K1, Z12 // 62524d4104e0 or 6252cd4104e0 VPMADDUBSW 99(R15)(R15*1), Z22, K1, Z12 // 62124d4104a43f63000000 or 6212cd4104a43f63000000 VPMADDUBSW (DX), Z22, K1, Z12 // 62724d410422 or 6272cd410422 VPMADDUBSW Z6, Z11, K1, Z12 // 6272254904e6 or 6272a54904e6 VPMADDUBSW Z8, Z11, K1, Z12 // 6252254904e0 or 6252a54904e0 VPMADDUBSW 99(R15)(R15*1), Z11, K1, Z12 // 6212254904a43f63000000 or 6212a54904a43f63000000 VPMADDUBSW (DX), Z11, K1, Z12 // 627225490422 or 6272a5490422 VPMADDUBSW Z6, Z22, K1, Z27 // 62624d4104de or 6262cd4104de VPMADDUBSW Z8, Z22, K1, Z27 // 62424d4104d8 or 6242cd4104d8 VPMADDUBSW 99(R15)(R15*1), Z22, K1, Z27 // 62024d41049c3f63000000 or 6202cd41049c3f63000000 VPMADDUBSW (DX), Z22, K1, Z27 // 62624d41041a or 6262cd41041a VPMADDUBSW Z6, Z11, K1, Z27 // 6262254904de or 6262a54904de VPMADDUBSW Z8, Z11, K1, Z27 // 6242254904d8 or 6242a54904d8 VPMADDUBSW 99(R15)(R15*1), Z11, K1, Z27 // 62022549049c3f63000000 or 6202a549049c3f63000000 VPMADDUBSW (DX), Z11, K1, Z27 // 62622549041a or 6262a549041a VPMADDWD X22, X28, K3, X0 // 62b11d03f5c6 or 62b19d03f5c6 VPMADDWD -15(R14)(R15*1), X28, K3, X0 // 62911d03f5843ef1ffffff or 62919d03f5843ef1ffffff VPMADDWD -15(BX), X28, K3, X0 // 62f11d03f583f1ffffff or 62f19d03f583f1ffffff VPMADDWD Y13, Y2, K4, Y14 // 62516d2cf5f5 or 6251ed2cf5f5 VPMADDWD 15(R8)(R14*1), Y2, K4, Y14 // 62116d2cf5b4300f000000 or 6211ed2cf5b4300f000000 VPMADDWD 15(R8)(R14*2), Y2, K4, Y14 // 62116d2cf5b4700f000000 or 6211ed2cf5b4700f000000 VPMADDWD Z9, Z12, K5, Z25 // 62411d4df5c9 or 62419d4df5c9 VPMADDWD Z12, Z12, K5, Z25 // 62411d4df5cc or 62419d4df5cc VPMADDWD -17(BP)(SI*8), Z12, K5, Z25 // 62611d4df58cf5efffffff or 62619d4df58cf5efffffff VPMADDWD (R15), Z12, K5, Z25 // 62411d4df50f or 62419d4df50f VPMADDWD Z9, Z17, K5, Z25 // 62417545f5c9 or 6241f545f5c9 VPMADDWD Z12, Z17, K5, Z25 // 62417545f5cc or 6241f545f5cc VPMADDWD -17(BP)(SI*8), Z17, K5, Z25 // 62617545f58cf5efffffff or 6261f545f58cf5efffffff VPMADDWD (R15), Z17, K5, Z25 // 62417545f50f or 6241f545f50f VPMADDWD Z9, Z12, K5, Z12 // 62511d4df5e1 or 62519d4df5e1 VPMADDWD Z12, Z12, K5, Z12 // 62511d4df5e4 or 62519d4df5e4 VPMADDWD -17(BP)(SI*8), Z12, K5, Z12 // 62711d4df5a4f5efffffff or 62719d4df5a4f5efffffff VPMADDWD (R15), Z12, K5, Z12 // 62511d4df527 or 62519d4df527 VPMADDWD Z9, Z17, K5, Z12 // 62517545f5e1 or 6251f545f5e1 VPMADDWD Z12, Z17, K5, Z12 // 62517545f5e4 or 6251f545f5e4 VPMADDWD -17(BP)(SI*8), Z17, K5, Z12 // 62717545f5a4f5efffffff or 6271f545f5a4f5efffffff VPMADDWD (R15), Z17, K5, Z12 // 62517545f527 or 6251f545f527 VPMAXSB X7, X19, K7, X7 // 62f265073cff or 62f2e5073cff VPMAXSB 7(AX)(CX*4), X19, K7, X7 // 62f265073cbc8807000000 or 62f2e5073cbc8807000000 VPMAXSB 7(AX)(CX*1), X19, K7, X7 // 62f265073cbc0807000000 or 62f2e5073cbc0807000000 VPMAXSB Y22, Y15, K7, Y27 // 6222052f3cde or 6222852f3cde VPMAXSB (R14), Y15, K7, Y27 // 6242052f3c1e or 6242852f3c1e VPMAXSB -7(DI)(R8*8), Y15, K7, Y27 // 6222052f3c9cc7f9ffffff or 6222852f3c9cc7f9ffffff VPMAXSB Z8, Z3, K6, Z6 // 62d2654e3cf0 or 62d2e54e3cf0 VPMAXSB Z2, Z3, K6, Z6 // 62f2654e3cf2 or 62f2e54e3cf2 VPMAXSB 7(SI)(DI*8), Z3, K6, Z6 // 62f2654e3cb4fe07000000 or 62f2e54e3cb4fe07000000 VPMAXSB -15(R14), Z3, K6, Z6 // 62d2654e3cb6f1ffffff or 62d2e54e3cb6f1ffffff VPMAXSB Z8, Z21, K6, Z6 // 62d255463cf0 or 62d2d5463cf0 VPMAXSB Z2, Z21, K6, Z6 // 62f255463cf2 or 62f2d5463cf2 VPMAXSB 7(SI)(DI*8), Z21, K6, Z6 // 62f255463cb4fe07000000 or 62f2d5463cb4fe07000000 VPMAXSB -15(R14), Z21, K6, Z6 // 62d255463cb6f1ffffff or 62d2d5463cb6f1ffffff VPMAXSB Z8, Z3, K6, Z25 // 6242654e3cc8 or 6242e54e3cc8 VPMAXSB Z2, Z3, K6, Z25 // 6262654e3cca or 6262e54e3cca VPMAXSB 7(SI)(DI*8), Z3, K6, Z25 // 6262654e3c8cfe07000000 or 6262e54e3c8cfe07000000 VPMAXSB -15(R14), Z3, K6, Z25 // 6242654e3c8ef1ffffff or 6242e54e3c8ef1ffffff VPMAXSB Z8, Z21, K6, Z25 // 624255463cc8 or 6242d5463cc8 VPMAXSB Z2, Z21, K6, Z25 // 626255463cca or 6262d5463cca VPMAXSB 7(SI)(DI*8), Z21, K6, Z25 // 626255463c8cfe07000000 or 6262d5463c8cfe07000000 VPMAXSB -15(R14), Z21, K6, Z25 // 624255463c8ef1ffffff or 6242d5463c8ef1ffffff VPMAXSW X12, X0, K5, X12 // 62517d0deee4 or 6251fd0deee4 VPMAXSW 7(SI)(DI*4), X0, K5, X12 // 62717d0deea4be07000000 or 6271fd0deea4be07000000 VPMAXSW -7(DI)(R8*2), X0, K5, X12 // 62317d0deea447f9ffffff or 6231fd0deea447f9ffffff VPMAXSW Y14, Y19, K3, Y23 // 62c16523eefe or 62c1e523eefe VPMAXSW 99(R15)(R15*2), Y19, K3, Y23 // 62816523eebc7f63000000 or 6281e523eebc7f63000000 VPMAXSW -7(DI), Y19, K3, Y23 // 62e16523eebff9ffffff or 62e1e523eebff9ffffff VPMAXSW Z18, Z11, K4, Z12 // 6231254ceee2 or 6231a54ceee2 VPMAXSW Z24, Z11, K4, Z12 // 6211254ceee0 or 6211a54ceee0 VPMAXSW -7(CX), Z11, K4, Z12 // 6271254ceea1f9ffffff or 6271a54ceea1f9ffffff VPMAXSW 15(DX)(BX*4), Z11, K4, Z12 // 6271254ceea49a0f000000 or 6271a54ceea49a0f000000 VPMAXSW Z18, Z5, K4, Z12 // 6231554ceee2 or 6231d54ceee2 VPMAXSW Z24, Z5, K4, Z12 // 6211554ceee0 or 6211d54ceee0 VPMAXSW -7(CX), Z5, K4, Z12 // 6271554ceea1f9ffffff or 6271d54ceea1f9ffffff VPMAXSW 15(DX)(BX*4), Z5, K4, Z12 // 6271554ceea49a0f000000 or 6271d54ceea49a0f000000 VPMAXSW Z18, Z11, K4, Z22 // 62a1254ceef2 or 62a1a54ceef2 VPMAXSW Z24, Z11, K4, Z22 // 6281254ceef0 or 6281a54ceef0 VPMAXSW -7(CX), Z11, K4, Z22 // 62e1254ceeb1f9ffffff or 62e1a54ceeb1f9ffffff VPMAXSW 15(DX)(BX*4), Z11, K4, Z22 // 62e1254ceeb49a0f000000 or 62e1a54ceeb49a0f000000 VPMAXSW Z18, Z5, K4, Z22 // 62a1554ceef2 or 62a1d54ceef2 VPMAXSW Z24, Z5, K4, Z22 // 6281554ceef0 or 6281d54ceef0 VPMAXSW -7(CX), Z5, K4, Z22 // 62e1554ceeb1f9ffffff or 62e1d54ceeb1f9ffffff VPMAXSW 15(DX)(BX*4), Z5, K4, Z22 // 62e1554ceeb49a0f000000 or 62e1d54ceeb49a0f000000 VPMAXUB X17, X5, K2, X14 // 6231550adef1 or 6231d50adef1 VPMAXUB 17(SP), X5, K2, X14 // 6271550adeb42411000000 or 6271d50adeb42411000000 VPMAXUB -17(BP)(SI*4), X5, K2, X14 // 6271550adeb4b5efffffff or 6271d50adeb4b5efffffff VPMAXUB Y16, Y5, K2, Y21 // 62a1552adee8 or 62a1d52adee8 VPMAXUB -7(CX)(DX*1), Y5, K2, Y21 // 62e1552adeac11f9ffffff or 62e1d52adeac11f9ffffff VPMAXUB -15(R14)(R15*4), Y5, K2, Y21 // 6281552adeacbef1ffffff or 6281d52adeacbef1ffffff VPMAXUB Z6, Z7, K3, Z2 // 62f1454bded6 or 62f1c54bded6 VPMAXUB Z16, Z7, K3, Z2 // 62b1454bded0 or 62b1c54bded0 VPMAXUB 99(R15)(R15*8), Z7, K3, Z2 // 6291454bde94ff63000000 or 6291c54bde94ff63000000 VPMAXUB 7(AX)(CX*8), Z7, K3, Z2 // 62f1454bde94c807000000 or 62f1c54bde94c807000000 VPMAXUB Z6, Z13, K3, Z2 // 62f1154bded6 or 62f1954bded6 VPMAXUB Z16, Z13, K3, Z2 // 62b1154bded0 or 62b1954bded0 VPMAXUB 99(R15)(R15*8), Z13, K3, Z2 // 6291154bde94ff63000000 or 6291954bde94ff63000000 VPMAXUB 7(AX)(CX*8), Z13, K3, Z2 // 62f1154bde94c807000000 or 62f1954bde94c807000000 VPMAXUB Z6, Z7, K3, Z21 // 62e1454bdeee or 62e1c54bdeee VPMAXUB Z16, Z7, K3, Z21 // 62a1454bdee8 or 62a1c54bdee8 VPMAXUB 99(R15)(R15*8), Z7, K3, Z21 // 6281454bdeacff63000000 or 6281c54bdeacff63000000 VPMAXUB 7(AX)(CX*8), Z7, K3, Z21 // 62e1454bdeacc807000000 or 62e1c54bdeacc807000000 VPMAXUB Z6, Z13, K3, Z21 // 62e1154bdeee or 62e1954bdeee VPMAXUB Z16, Z13, K3, Z21 // 62a1154bdee8 or 62a1954bdee8 VPMAXUB 99(R15)(R15*8), Z13, K3, Z21 // 6281154bdeacff63000000 or 6281954bdeacff63000000 VPMAXUB 7(AX)(CX*8), Z13, K3, Z21 // 62e1154bdeacc807000000 or 62e1954bdeacc807000000 VPMAXUW X9, X24, K7, X28 // 62423d073ee1 or 6242bd073ee1 VPMAXUW -17(BP)(SI*8), X24, K7, X28 // 62623d073ea4f5efffffff or 6262bd073ea4f5efffffff VPMAXUW (R15), X24, K7, X28 // 62423d073e27 or 6242bd073e27 VPMAXUW Y7, Y19, K1, Y11 // 627265213edf or 6272e5213edf VPMAXUW 17(SP)(BP*2), Y19, K1, Y11 // 627265213e9c6c11000000 or 6272e5213e9c6c11000000 VPMAXUW -7(DI)(R8*4), Y19, K1, Y11 // 623265213e9c87f9ffffff or 6232e5213e9c87f9ffffff VPMAXUW Z12, Z1, K1, Z20 // 62c275493ee4 or 62c2f5493ee4 VPMAXUW Z16, Z1, K1, Z20 // 62a275493ee0 or 62a2f5493ee0 VPMAXUW 15(R8)(R14*4), Z1, K1, Z20 // 628275493ea4b00f000000 or 6282f5493ea4b00f000000 VPMAXUW -7(CX)(DX*4), Z1, K1, Z20 // 62e275493ea491f9ffffff or 62e2f5493ea491f9ffffff VPMAXUW Z12, Z3, K1, Z20 // 62c265493ee4 or 62c2e5493ee4 VPMAXUW Z16, Z3, K1, Z20 // 62a265493ee0 or 62a2e5493ee0 VPMAXUW 15(R8)(R14*4), Z3, K1, Z20 // 628265493ea4b00f000000 or 6282e5493ea4b00f000000 VPMAXUW -7(CX)(DX*4), Z3, K1, Z20 // 62e265493ea491f9ffffff or 62e2e5493ea491f9ffffff VPMAXUW Z12, Z1, K1, Z9 // 625275493ecc or 6252f5493ecc VPMAXUW Z16, Z1, K1, Z9 // 623275493ec8 or 6232f5493ec8 VPMAXUW 15(R8)(R14*4), Z1, K1, Z9 // 621275493e8cb00f000000 or 6212f5493e8cb00f000000 VPMAXUW -7(CX)(DX*4), Z1, K1, Z9 // 627275493e8c91f9ffffff or 6272f5493e8c91f9ffffff VPMAXUW Z12, Z3, K1, Z9 // 625265493ecc or 6252e5493ecc VPMAXUW Z16, Z3, K1, Z9 // 623265493ec8 or 6232e5493ec8 VPMAXUW 15(R8)(R14*4), Z3, K1, Z9 // 621265493e8cb00f000000 or 6212e5493e8cb00f000000 VPMAXUW -7(CX)(DX*4), Z3, K1, Z9 // 627265493e8c91f9ffffff or 6272e5493e8c91f9ffffff VPMINSB X18, X26, K1, X15 // 62322d0138fa or 6232ad0138fa VPMINSB 7(SI)(DI*8), X26, K1, X15 // 62722d0138bcfe07000000 or 6272ad0138bcfe07000000 VPMINSB -15(R14), X26, K1, X15 // 62522d0138bef1ffffff or 6252ad0138bef1ffffff VPMINSB Y3, Y0, K7, Y6 // 62f27d2f38f3 or 62f2fd2f38f3 VPMINSB 15(R8), Y0, K7, Y6 // 62d27d2f38b00f000000 or 62d2fd2f38b00f000000 VPMINSB (BP), Y0, K7, Y6 // 62f27d2f387500 or 62f2fd2f387500 VPMINSB Z3, Z14, K2, Z28 // 62620d4a38e3 or 62628d4a38e3 VPMINSB Z12, Z14, K2, Z28 // 62420d4a38e4 or 62428d4a38e4 VPMINSB (R8), Z14, K2, Z28 // 62420d4a3820 or 62428d4a3820 VPMINSB 15(DX)(BX*2), Z14, K2, Z28 // 62620d4a38a45a0f000000 or 62628d4a38a45a0f000000 VPMINSB Z3, Z28, K2, Z28 // 62621d4238e3 or 62629d4238e3 VPMINSB Z12, Z28, K2, Z28 // 62421d4238e4 or 62429d4238e4 VPMINSB (R8), Z28, K2, Z28 // 62421d423820 or 62429d423820 VPMINSB 15(DX)(BX*2), Z28, K2, Z28 // 62621d4238a45a0f000000 or 62629d4238a45a0f000000 VPMINSB Z3, Z14, K2, Z13 // 62720d4a38eb or 62728d4a38eb VPMINSB Z12, Z14, K2, Z13 // 62520d4a38ec or 62528d4a38ec VPMINSB (R8), Z14, K2, Z13 // 62520d4a3828 or 62528d4a3828 VPMINSB 15(DX)(BX*2), Z14, K2, Z13 // 62720d4a38ac5a0f000000 or 62728d4a38ac5a0f000000 VPMINSB Z3, Z28, K2, Z13 // 62721d4238eb or 62729d4238eb VPMINSB Z12, Z28, K2, Z13 // 62521d4238ec or 62529d4238ec VPMINSB (R8), Z28, K2, Z13 // 62521d423828 or 62529d423828 VPMINSB 15(DX)(BX*2), Z28, K2, Z13 // 62721d4238ac5a0f000000 or 62729d4238ac5a0f000000 VPMINSW X24, X0, K7, X0 // 62917d0feac0 or 6291fd0feac0 VPMINSW -7(CX), X0, K7, X0 // 62f17d0fea81f9ffffff or 62f1fd0fea81f9ffffff VPMINSW 15(DX)(BX*4), X0, K7, X0 // 62f17d0fea849a0f000000 or 62f1fd0fea849a0f000000 VPMINSW Y22, Y0, K6, Y7 // 62b17d2eeafe or 62b1fd2eeafe VPMINSW 7(AX)(CX*4), Y0, K6, Y7 // 62f17d2eeabc8807000000 or 62f1fd2eeabc8807000000 VPMINSW 7(AX)(CX*1), Y0, K6, Y7 // 62f17d2eeabc0807000000 or 62f1fd2eeabc0807000000 VPMINSW Z23, Z20, K3, Z16 // 62a15d43eac7 or 62a1dd43eac7 VPMINSW Z19, Z20, K3, Z16 // 62a15d43eac3 or 62a1dd43eac3 VPMINSW 15(R8)(R14*1), Z20, K3, Z16 // 62815d43ea84300f000000 or 6281dd43ea84300f000000 VPMINSW 15(R8)(R14*2), Z20, K3, Z16 // 62815d43ea84700f000000 or 6281dd43ea84700f000000 VPMINSW Z23, Z0, K3, Z16 // 62a17d4beac7 or 62a1fd4beac7 VPMINSW Z19, Z0, K3, Z16 // 62a17d4beac3 or 62a1fd4beac3 VPMINSW 15(R8)(R14*1), Z0, K3, Z16 // 62817d4bea84300f000000 or 6281fd4bea84300f000000 VPMINSW 15(R8)(R14*2), Z0, K3, Z16 // 62817d4bea84700f000000 or 6281fd4bea84700f000000 VPMINSW Z23, Z20, K3, Z9 // 62315d43eacf or 6231dd43eacf VPMINSW Z19, Z20, K3, Z9 // 62315d43eacb or 6231dd43eacb VPMINSW 15(R8)(R14*1), Z20, K3, Z9 // 62115d43ea8c300f000000 or 6211dd43ea8c300f000000 VPMINSW 15(R8)(R14*2), Z20, K3, Z9 // 62115d43ea8c700f000000 or 6211dd43ea8c700f000000 VPMINSW Z23, Z0, K3, Z9 // 62317d4beacf or 6231fd4beacf VPMINSW Z19, Z0, K3, Z9 // 62317d4beacb or 6231fd4beacb VPMINSW 15(R8)(R14*1), Z0, K3, Z9 // 62117d4bea8c300f000000 or 6211fd4bea8c300f000000 VPMINSW 15(R8)(R14*2), Z0, K3, Z9 // 62117d4bea8c700f000000 or 6211fd4bea8c700f000000 VPMINUB X9, X7, K7, X20 // 62c1450fdae1 or 62c1c50fdae1 VPMINUB 99(R15)(R15*8), X7, K7, X20 // 6281450fdaa4ff63000000 or 6281c50fdaa4ff63000000 VPMINUB 7(AX)(CX*8), X7, K7, X20 // 62e1450fdaa4c807000000 or 62e1c50fdaa4c807000000 VPMINUB Y1, Y12, K4, Y13 // 62711d2cdae9 or 62719d2cdae9 VPMINUB (SI), Y12, K4, Y13 // 62711d2cda2e or 62719d2cda2e VPMINUB 7(SI)(DI*2), Y12, K4, Y13 // 62711d2cdaac7e07000000 or 62719d2cdaac7e07000000 VPMINUB Z24, Z0, K4, Z0 // 62917d4cdac0 or 6291fd4cdac0 VPMINUB Z12, Z0, K4, Z0 // 62d17d4cdac4 or 62d1fd4cdac4 VPMINUB (R14), Z0, K4, Z0 // 62d17d4cda06 or 62d1fd4cda06 VPMINUB -7(DI)(R8*8), Z0, K4, Z0 // 62b17d4cda84c7f9ffffff or 62b1fd4cda84c7f9ffffff VPMINUB Z24, Z25, K4, Z0 // 62913544dac0 or 6291b544dac0 VPMINUB Z12, Z25, K4, Z0 // 62d13544dac4 or 62d1b544dac4 VPMINUB (R14), Z25, K4, Z0 // 62d13544da06 or 62d1b544da06 VPMINUB -7(DI)(R8*8), Z25, K4, Z0 // 62b13544da84c7f9ffffff or 62b1b544da84c7f9ffffff VPMINUB Z24, Z0, K4, Z11 // 62117d4cdad8 or 6211fd4cdad8 VPMINUB Z12, Z0, K4, Z11 // 62517d4cdadc or 6251fd4cdadc VPMINUB (R14), Z0, K4, Z11 // 62517d4cda1e or 6251fd4cda1e VPMINUB -7(DI)(R8*8), Z0, K4, Z11 // 62317d4cda9cc7f9ffffff or 6231fd4cda9cc7f9ffffff VPMINUB Z24, Z25, K4, Z11 // 62113544dad8 or 6211b544dad8 VPMINUB Z12, Z25, K4, Z11 // 62513544dadc or 6251b544dadc VPMINUB (R14), Z25, K4, Z11 // 62513544da1e or 6251b544da1e VPMINUB -7(DI)(R8*8), Z25, K4, Z11 // 62313544da9cc7f9ffffff or 6231b544da9cc7f9ffffff VPMINUW X13, X11, K2, X1 // 62d2250a3acd or 62d2a50a3acd VPMINUW 15(R8)(R14*4), X11, K2, X1 // 6292250a3a8cb00f000000 or 6292a50a3a8cb00f000000 VPMINUW -7(CX)(DX*4), X11, K2, X1 // 62f2250a3a8c91f9ffffff or 62f2a50a3a8c91f9ffffff VPMINUW Y13, Y28, K3, Y1 // 62d21d233acd or 62d29d233acd VPMINUW 17(SP), Y28, K3, Y1 // 62f21d233a8c2411000000 or 62f29d233a8c2411000000 VPMINUW -17(BP)(SI*4), Y28, K3, Y1 // 62f21d233a8cb5efffffff or 62f29d233a8cb5efffffff VPMINUW Z21, Z31, K3, Z17 // 62a205433acd or 62a285433acd VPMINUW Z9, Z31, K3, Z17 // 62c205433ac9 or 62c285433ac9 VPMINUW 99(R15)(R15*2), Z31, K3, Z17 // 628205433a8c7f63000000 or 628285433a8c7f63000000 VPMINUW -7(DI), Z31, K3, Z17 // 62e205433a8ff9ffffff or 62e285433a8ff9ffffff VPMINUW Z21, Z0, K3, Z17 // 62a27d4b3acd or 62a2fd4b3acd VPMINUW Z9, Z0, K3, Z17 // 62c27d4b3ac9 or 62c2fd4b3ac9 VPMINUW 99(R15)(R15*2), Z0, K3, Z17 // 62827d4b3a8c7f63000000 or 6282fd4b3a8c7f63000000 VPMINUW -7(DI), Z0, K3, Z17 // 62e27d4b3a8ff9ffffff or 62e2fd4b3a8ff9ffffff VPMINUW Z21, Z31, K3, Z23 // 62a205433afd or 62a285433afd VPMINUW Z9, Z31, K3, Z23 // 62c205433af9 or 62c285433af9 VPMINUW 99(R15)(R15*2), Z31, K3, Z23 // 628205433abc7f63000000 or 628285433abc7f63000000 VPMINUW -7(DI), Z31, K3, Z23 // 62e205433abff9ffffff or 62e285433abff9ffffff VPMINUW Z21, Z0, K3, Z23 // 62a27d4b3afd or 62a2fd4b3afd VPMINUW Z9, Z0, K3, Z23 // 62c27d4b3af9 or 62c2fd4b3af9 VPMINUW 99(R15)(R15*2), Z0, K3, Z23 // 62827d4b3abc7f63000000 or 6282fd4b3abc7f63000000 VPMINUW -7(DI), Z0, K3, Z23 // 62e27d4b3abff9ffffff or 62e2fd4b3abff9ffffff VPMOVB2M X0, K5 // 62f27e0829e8 VPMOVB2M X0, K4 // 62f27e0829e0 VPMOVB2M Y7, K4 // 62f27e2829e7 VPMOVB2M Y7, K6 // 62f27e2829f7 VPMOVB2M Z6, K1 // 62f27e4829ce VPMOVB2M Z9, K1 // 62d27e4829c9 VPMOVB2M Z6, K3 // 62f27e4829de VPMOVB2M Z9, K3 // 62d27e4829d9 VPMOVM2B K4, X26 // 62627e0828d4 VPMOVM2B K5, X26 // 62627e0828d5 VPMOVM2B K2, Y1 // 62f27e2828ca VPMOVM2B K7, Y1 // 62f27e2828cf VPMOVM2B K0, Z26 // 62627e4828d0 VPMOVM2B K5, Z26 // 62627e4828d5 VPMOVM2B K0, Z22 // 62e27e4828f0 VPMOVM2B K5, Z22 // 62e27e4828f5 VPMOVM2W K0, X16 // 62e2fe0828c0 VPMOVM2W K7, X16 // 62e2fe0828c7 VPMOVM2W K5, Y2 // 62f2fe2828d5 VPMOVM2W K4, Y2 // 62f2fe2828d4 VPMOVM2W K4, Z14 // 6272fe4828f4 VPMOVM2W K6, Z14 // 6272fe4828f6 VPMOVM2W K4, Z13 // 6272fe4828ec VPMOVM2W K6, Z13 // 6272fe4828ee VPMOVSWB X18, K3, X0 // 62e27e0b20d0 VPMOVSWB X18, K3, -7(CX) // 62e27e0b2091f9ffffff VPMOVSWB X18, K3, 15(DX)(BX*4) // 62e27e0b20949a0f000000 VPMOVSWB Y6, K3, X8 // 62d27e2b20f0 VPMOVSWB Y6, K3, -7(CX)(DX*1) // 62f27e2b20b411f9ffffff VPMOVSWB Y6, K3, -15(R14)(R15*4) // 62927e2b20b4bef1ffffff VPMOVSWB Z22, K3, Y21 // 62a27e4b20f5 VPMOVSWB Z25, K3, Y21 // 62227e4b20cd VPMOVSWB Z22, K3, 7(SI)(DI*1) // 62e27e4b20b43e07000000 VPMOVSWB Z25, K3, 7(SI)(DI*1) // 62627e4b208c3e07000000 VPMOVSWB Z22, K3, 15(DX)(BX*8) // 62e27e4b20b4da0f000000 VPMOVSWB Z25, K3, 15(DX)(BX*8) // 62627e4b208cda0f000000 VPMOVSXBW X13, K1, Y28 // 62427d2920e5 or 6242fd2920e5 VPMOVSXBW -17(BP), K1, Y28 // 62627d2920a5efffffff or 6262fd2920a5efffffff VPMOVSXBW -15(R14)(R15*8), K1, Y28 // 62027d2920a4fef1ffffff or 6202fd2920a4fef1ffffff VPMOVSXBW X24, K1, X8 // 62127d0920c0 or 6212fd0920c0 VPMOVSXBW (BX), K1, X8 // 62727d092003 or 6272fd092003 VPMOVSXBW -17(BP)(SI*1), K1, X8 // 62727d09208435efffffff or 6272fd09208435efffffff VPMOVSXBW Y20, K7, Z0 // 62b27d4f20c4 or 62b2fd4f20c4 VPMOVSXBW -7(DI)(R8*1), K7, Z0 // 62b27d4f208407f9ffffff or 62b2fd4f208407f9ffffff VPMOVSXBW (SP), K7, Z0 // 62f27d4f200424 or 62f2fd4f200424 VPMOVSXBW Y20, K7, Z8 // 62327d4f20c4 or 6232fd4f20c4 VPMOVSXBW -7(DI)(R8*1), K7, Z8 // 62327d4f208407f9ffffff or 6232fd4f208407f9ffffff VPMOVSXBW (SP), K7, Z8 // 62727d4f200424 or 6272fd4f200424 VPMOVUSWB X6, K1, X6 // 62f27e0910f6 VPMOVUSWB X6, K1, 99(R15)(R15*2) // 62927e0910b47f63000000 VPMOVUSWB X6, K1, -7(DI) // 62f27e0910b7f9ffffff VPMOVUSWB Y15, K2, X22 // 62327e2a10fe VPMOVUSWB Y15, K2, 7(SI)(DI*4) // 62727e2a10bcbe07000000 VPMOVUSWB Y15, K2, -7(DI)(R8*2) // 62327e2a10bc47f9ffffff VPMOVUSWB Z28, K1, Y1 // 62627e4910e1 VPMOVUSWB Z6, K1, Y1 // 62f27e4910f1 VPMOVUSWB Z28, K1, 15(R8)(R14*4) // 62027e4910a4b00f000000 VPMOVUSWB Z6, K1, 15(R8)(R14*4) // 62927e4910b4b00f000000 VPMOVUSWB Z28, K1, -7(CX)(DX*4) // 62627e4910a491f9ffffff VPMOVUSWB Z6, K1, -7(CX)(DX*4) // 62f27e4910b491f9ffffff VPMOVW2M X12, K4 // 62d2fe0829e4 VPMOVW2M X12, K6 // 62d2fe0829f4 VPMOVW2M Y27, K4 // 6292fe2829e3 VPMOVW2M Y27, K5 // 6292fe2829eb VPMOVW2M Z13, K2 // 62d2fe4829d5 VPMOVW2M Z21, K2 // 62b2fe4829d5 VPMOVW2M Z13, K7 // 62d2fe4829fd VPMOVW2M Z21, K7 // 62b2fe4829fd VPMOVWB X28, K7, X16 // 62227e0f30e0 VPMOVWB X28, K7, -7(CX)(DX*1) // 62627e0f30a411f9ffffff VPMOVWB X28, K7, -15(R14)(R15*4) // 62027e0f30a4bef1ffffff VPMOVWB Y19, K1, X8 // 62c27e2930d8 VPMOVWB Y19, K1, 17(SP) // 62e27e29309c2411000000 VPMOVWB Y19, K1, -17(BP)(SI*4) // 62e27e29309cb5efffffff VPMOVWB Z26, K1, Y5 // 62627e4930d5 VPMOVWB Z3, K1, Y5 // 62f27e4930dd VPMOVWB Z26, K1, (R8) // 62427e493010 VPMOVWB Z3, K1, (R8) // 62d27e493018 VPMOVWB Z26, K1, 15(DX)(BX*2) // 62627e4930945a0f000000 VPMOVWB Z3, K1, 15(DX)(BX*2) // 62f27e49309c5a0f000000 VPMOVZXBW X0, K4, Y21 // 62e27d2c30e8 or 62e2fd2c30e8 VPMOVZXBW 99(R15)(R15*1), K4, Y21 // 62827d2c30ac3f63000000 or 6282fd2c30ac3f63000000 VPMOVZXBW (DX), K4, Y21 // 62e27d2c302a or 62e2fd2c302a VPMOVZXBW X11, K5, X25 // 62427d0d30cb or 6242fd0d30cb VPMOVZXBW 17(SP)(BP*2), K5, X25 // 62627d0d308c6c11000000 or 6262fd0d308c6c11000000 VPMOVZXBW -7(DI)(R8*4), K5, X25 // 62227d0d308c87f9ffffff or 6222fd0d308c87f9ffffff VPMOVZXBW Y7, K7, Z11 // 62727d4f30df or 6272fd4f30df VPMOVZXBW 17(SP)(BP*1), K7, Z11 // 62727d4f309c2c11000000 or 6272fd4f309c2c11000000 VPMOVZXBW -7(CX)(DX*8), K7, Z11 // 62727d4f309cd1f9ffffff or 6272fd4f309cd1f9ffffff VPMOVZXBW Y7, K7, Z25 // 62627d4f30cf or 6262fd4f30cf VPMOVZXBW 17(SP)(BP*1), K7, Z25 // 62627d4f308c2c11000000 or 6262fd4f308c2c11000000 VPMOVZXBW -7(CX)(DX*8), K7, Z25 // 62627d4f308cd1f9ffffff or 6262fd4f308cd1f9ffffff VPMULHRSW X30, X15, K2, X11 // 6212050a0bde or 6212850a0bde VPMULHRSW -7(CX), X15, K2, X11 // 6272050a0b99f9ffffff or 6272850a0b99f9ffffff VPMULHRSW 15(DX)(BX*4), X15, K2, X11 // 6272050a0b9c9a0f000000 or 6272850a0b9c9a0f000000 VPMULHRSW Y16, Y21, K3, Y24 // 622255230bc0 or 6222d5230bc0 VPMULHRSW 99(R15)(R15*4), Y21, K3, Y24 // 620255230b84bf63000000 or 6202d5230b84bf63000000 VPMULHRSW 15(DX), Y21, K3, Y24 // 626255230b820f000000 or 6262d5230b820f000000 VPMULHRSW Z22, Z12, K3, Z16 // 62a21d4b0bc6 or 62a29d4b0bc6 VPMULHRSW Z11, Z12, K3, Z16 // 62c21d4b0bc3 or 62c29d4b0bc3 VPMULHRSW 15(DX)(BX*1), Z12, K3, Z16 // 62e21d4b0b841a0f000000 or 62e29d4b0b841a0f000000 VPMULHRSW -7(CX)(DX*2), Z12, K3, Z16 // 62e21d4b0b8451f9ffffff or 62e29d4b0b8451f9ffffff VPMULHRSW Z22, Z27, K3, Z16 // 62a225430bc6 or 62a2a5430bc6 VPMULHRSW Z11, Z27, K3, Z16 // 62c225430bc3 or 62c2a5430bc3 VPMULHRSW 15(DX)(BX*1), Z27, K3, Z16 // 62e225430b841a0f000000 or 62e2a5430b841a0f000000 VPMULHRSW -7(CX)(DX*2), Z27, K3, Z16 // 62e225430b8451f9ffffff or 62e2a5430b8451f9ffffff VPMULHRSW Z22, Z12, K3, Z13 // 62321d4b0bee or 62329d4b0bee VPMULHRSW Z11, Z12, K3, Z13 // 62521d4b0beb or 62529d4b0beb VPMULHRSW 15(DX)(BX*1), Z12, K3, Z13 // 62721d4b0bac1a0f000000 or 62729d4b0bac1a0f000000 VPMULHRSW -7(CX)(DX*2), Z12, K3, Z13 // 62721d4b0bac51f9ffffff or 62729d4b0bac51f9ffffff VPMULHRSW Z22, Z27, K3, Z13 // 623225430bee or 6232a5430bee VPMULHRSW Z11, Z27, K3, Z13 // 625225430beb or 6252a5430beb VPMULHRSW 15(DX)(BX*1), Z27, K3, Z13 // 627225430bac1a0f000000 or 6272a5430bac1a0f000000 VPMULHRSW -7(CX)(DX*2), Z27, K3, Z13 // 627225430bac51f9ffffff or 6272a5430bac51f9ffffff VPMULHUW X12, X6, K3, X13 // 62514d0be4ec or 6251cd0be4ec VPMULHUW 99(R15)(R15*8), X6, K3, X13 // 62114d0be4acff63000000 or 6211cd0be4acff63000000 VPMULHUW 7(AX)(CX*8), X6, K3, X13 // 62714d0be4acc807000000 or 6271cd0be4acc807000000 VPMULHUW Y9, Y13, K2, Y9 // 6251152ae4c9 or 6251952ae4c9 VPMULHUW (CX), Y13, K2, Y9 // 6271152ae409 or 6271952ae409 VPMULHUW 99(R15), Y13, K2, Y9 // 6251152ae48f63000000 or 6251952ae48f63000000 VPMULHUW Z12, Z25, K1, Z6 // 62d13541e4f4 or 62d1b541e4f4 VPMULHUW Z17, Z25, K1, Z6 // 62b13541e4f1 or 62b1b541e4f1 VPMULHUW -17(BP), Z25, K1, Z6 // 62f13541e4b5efffffff or 62f1b541e4b5efffffff VPMULHUW -15(R14)(R15*8), Z25, K1, Z6 // 62913541e4b4fef1ffffff or 6291b541e4b4fef1ffffff VPMULHUW Z12, Z12, K1, Z6 // 62d11d49e4f4 or 62d19d49e4f4 VPMULHUW Z17, Z12, K1, Z6 // 62b11d49e4f1 or 62b19d49e4f1 VPMULHUW -17(BP), Z12, K1, Z6 // 62f11d49e4b5efffffff or 62f19d49e4b5efffffff VPMULHUW -15(R14)(R15*8), Z12, K1, Z6 // 62911d49e4b4fef1ffffff or 62919d49e4b4fef1ffffff VPMULHUW Z12, Z25, K1, Z8 // 62513541e4c4 or 6251b541e4c4 VPMULHUW Z17, Z25, K1, Z8 // 62313541e4c1 or 6231b541e4c1 VPMULHUW -17(BP), Z25, K1, Z8 // 62713541e485efffffff or 6271b541e485efffffff VPMULHUW -15(R14)(R15*8), Z25, K1, Z8 // 62113541e484fef1ffffff or 6211b541e484fef1ffffff VPMULHUW Z12, Z12, K1, Z8 // 62511d49e4c4 or 62519d49e4c4 VPMULHUW Z17, Z12, K1, Z8 // 62311d49e4c1 or 62319d49e4c1 VPMULHUW -17(BP), Z12, K1, Z8 // 62711d49e485efffffff or 62719d49e485efffffff VPMULHUW -15(R14)(R15*8), Z12, K1, Z8 // 62111d49e484fef1ffffff or 62119d49e484fef1ffffff VPMULHW X8, X30, K2, X23 // 62c10d02e5f8 or 62c18d02e5f8 VPMULHW (AX), X30, K2, X23 // 62e10d02e538 or 62e18d02e538 VPMULHW 7(SI), X30, K2, X23 // 62e10d02e5be07000000 or 62e18d02e5be07000000 VPMULHW Y7, Y3, K1, Y6 // 62f16529e5f7 or 62f1e529e5f7 VPMULHW 99(R15)(R15*2), Y3, K1, Y6 // 62916529e5b47f63000000 or 6291e529e5b47f63000000 VPMULHW -7(DI), Y3, K1, Y6 // 62f16529e5b7f9ffffff or 62f1e529e5b7f9ffffff VPMULHW Z3, Z6, K7, Z9 // 62714d4fe5cb or 6271cd4fe5cb VPMULHW Z21, Z6, K7, Z9 // 62314d4fe5cd or 6231cd4fe5cd VPMULHW 17(SP)(BP*2), Z6, K7, Z9 // 62714d4fe58c6c11000000 or 6271cd4fe58c6c11000000 VPMULHW -7(DI)(R8*4), Z6, K7, Z9 // 62314d4fe58c87f9ffffff or 6231cd4fe58c87f9ffffff VPMULHW Z3, Z25, K7, Z9 // 62713547e5cb or 6271b547e5cb VPMULHW Z21, Z25, K7, Z9 // 62313547e5cd or 6231b547e5cd VPMULHW 17(SP)(BP*2), Z25, K7, Z9 // 62713547e58c6c11000000 or 6271b547e58c6c11000000 VPMULHW -7(DI)(R8*4), Z25, K7, Z9 // 62313547e58c87f9ffffff or 6231b547e58c87f9ffffff VPMULHW Z3, Z6, K7, Z12 // 62714d4fe5e3 or 6271cd4fe5e3 VPMULHW Z21, Z6, K7, Z12 // 62314d4fe5e5 or 6231cd4fe5e5 VPMULHW 17(SP)(BP*2), Z6, K7, Z12 // 62714d4fe5a46c11000000 or 6271cd4fe5a46c11000000 VPMULHW -7(DI)(R8*4), Z6, K7, Z12 // 62314d4fe5a487f9ffffff or 6231cd4fe5a487f9ffffff VPMULHW Z3, Z25, K7, Z12 // 62713547e5e3 or 6271b547e5e3 VPMULHW Z21, Z25, K7, Z12 // 62313547e5e5 or 6231b547e5e5 VPMULHW 17(SP)(BP*2), Z25, K7, Z12 // 62713547e5a46c11000000 or 6271b547e5a46c11000000 VPMULHW -7(DI)(R8*4), Z25, K7, Z12 // 62313547e5a487f9ffffff or 6231b547e5a487f9ffffff VPMULLW X7, X16, K1, X31 // 62617d01d5ff or 6261fd01d5ff VPMULLW (R8), X16, K1, X31 // 62417d01d538 or 6241fd01d538 VPMULLW 15(DX)(BX*2), X16, K1, X31 // 62617d01d5bc5a0f000000 or 6261fd01d5bc5a0f000000 VPMULLW Y18, Y31, K3, Y18 // 62a10523d5d2 or 62a18523d5d2 VPMULLW -17(BP), Y31, K3, Y18 // 62e10523d595efffffff or 62e18523d595efffffff VPMULLW -15(R14)(R15*8), Y31, K3, Y18 // 62810523d594fef1ffffff or 62818523d594fef1ffffff VPMULLW Z11, Z12, K4, Z9 // 62511d4cd5cb or 62519d4cd5cb VPMULLW Z5, Z12, K4, Z9 // 62711d4cd5cd or 62719d4cd5cd VPMULLW -15(R14)(R15*1), Z12, K4, Z9 // 62111d4cd58c3ef1ffffff or 62119d4cd58c3ef1ffffff VPMULLW -15(BX), Z12, K4, Z9 // 62711d4cd58bf1ffffff or 62719d4cd58bf1ffffff VPMULLW Z11, Z22, K4, Z9 // 62514d44d5cb or 6251cd44d5cb VPMULLW Z5, Z22, K4, Z9 // 62714d44d5cd or 6271cd44d5cd VPMULLW -15(R14)(R15*1), Z22, K4, Z9 // 62114d44d58c3ef1ffffff or 6211cd44d58c3ef1ffffff VPMULLW -15(BX), Z22, K4, Z9 // 62714d44d58bf1ffffff or 6271cd44d58bf1ffffff VPMULLW Z11, Z12, K4, Z19 // 62c11d4cd5db or 62c19d4cd5db VPMULLW Z5, Z12, K4, Z19 // 62e11d4cd5dd or 62e19d4cd5dd VPMULLW -15(R14)(R15*1), Z12, K4, Z19 // 62811d4cd59c3ef1ffffff or 62819d4cd59c3ef1ffffff VPMULLW -15(BX), Z12, K4, Z19 // 62e11d4cd59bf1ffffff or 62e19d4cd59bf1ffffff VPMULLW Z11, Z22, K4, Z19 // 62c14d44d5db or 62c1cd44d5db VPMULLW Z5, Z22, K4, Z19 // 62e14d44d5dd or 62e1cd44d5dd VPMULLW -15(R14)(R15*1), Z22, K4, Z19 // 62814d44d59c3ef1ffffff or 6281cd44d59c3ef1ffffff VPMULLW -15(BX), Z22, K4, Z19 // 62e14d44d59bf1ffffff or 62e1cd44d59bf1ffffff VPSADBW X7, X3, X31 // 62616508f6ff or 6261e508f6ff VPSADBW 17(SP)(BP*8), X3, X31 // 62616508f6bcec11000000 or 6261e508f6bcec11000000 VPSADBW 17(SP)(BP*4), X3, X31 // 62616508f6bcac11000000 or 6261e508f6bcac11000000 VPSADBW Y14, Y9, Y22 // 62c13528f6f6 or 62c1b528f6f6 VPSADBW 99(R15)(R15*8), Y9, Y22 // 62813528f6b4ff63000000 or 6281b528f6b4ff63000000 VPSADBW 7(AX)(CX*8), Y9, Y22 // 62e13528f6b4c807000000 or 62e1b528f6b4c807000000 VPSADBW Z7, Z26, Z30 // 62612d40f6f7 or 6261ad40f6f7 VPSADBW Z21, Z26, Z30 // 62212d40f6f5 or 6221ad40f6f5 VPSADBW (R8), Z26, Z30 // 62412d40f630 or 6241ad40f630 VPSADBW 15(DX)(BX*2), Z26, Z30 // 62612d40f6b45a0f000000 or 6261ad40f6b45a0f000000 VPSADBW Z7, Z22, Z30 // 62614d40f6f7 or 6261cd40f6f7 VPSADBW Z21, Z22, Z30 // 62214d40f6f5 or 6221cd40f6f5 VPSADBW (R8), Z22, Z30 // 62414d40f630 or 6241cd40f630 VPSADBW 15(DX)(BX*2), Z22, Z30 // 62614d40f6b45a0f000000 or 6261cd40f6b45a0f000000 VPSADBW Z7, Z26, Z5 // 62f12d40f6ef or 62f1ad40f6ef VPSADBW Z21, Z26, Z5 // 62b12d40f6ed or 62b1ad40f6ed VPSADBW (R8), Z26, Z5 // 62d12d40f628 or 62d1ad40f628 VPSADBW 15(DX)(BX*2), Z26, Z5 // 62f12d40f6ac5a0f000000 or 62f1ad40f6ac5a0f000000 VPSADBW Z7, Z22, Z5 // 62f14d40f6ef or 62f1cd40f6ef VPSADBW Z21, Z22, Z5 // 62b14d40f6ed or 62b1cd40f6ed VPSADBW (R8), Z22, Z5 // 62d14d40f628 or 62d1cd40f628 VPSADBW 15(DX)(BX*2), Z22, Z5 // 62f14d40f6ac5a0f000000 or 62f1cd40f6ac5a0f000000 VPSHUFB X13, X9, K5, X0 // 62d2350d00c5 or 62d2b50d00c5 VPSHUFB 15(R8)(R14*4), X9, K5, X0 // 6292350d0084b00f000000 or 6292b50d0084b00f000000 VPSHUFB -7(CX)(DX*4), X9, K5, X0 // 62f2350d008491f9ffffff or 62f2b50d008491f9ffffff VPSHUFB Y2, Y16, K7, Y5 // 62f27d2700ea or 62f2fd2700ea VPSHUFB 15(DX)(BX*1), Y16, K7, Y5 // 62f27d2700ac1a0f000000 or 62f2fd2700ac1a0f000000 VPSHUFB -7(CX)(DX*2), Y16, K7, Y5 // 62f27d2700ac51f9ffffff or 62f2fd2700ac51f9ffffff VPSHUFB Z9, Z12, K7, Z25 // 62421d4f00c9 or 62429d4f00c9 VPSHUFB Z12, Z12, K7, Z25 // 62421d4f00cc or 62429d4f00cc VPSHUFB 15(R8)(R14*8), Z12, K7, Z25 // 62021d4f008cf00f000000 or 62029d4f008cf00f000000 VPSHUFB -15(R14)(R15*2), Z12, K7, Z25 // 62021d4f008c7ef1ffffff or 62029d4f008c7ef1ffffff VPSHUFB Z9, Z17, K7, Z25 // 6242754700c9 or 6242f54700c9 VPSHUFB Z12, Z17, K7, Z25 // 6242754700cc or 6242f54700cc VPSHUFB 15(R8)(R14*8), Z17, K7, Z25 // 62027547008cf00f000000 or 6202f547008cf00f000000 VPSHUFB -15(R14)(R15*2), Z17, K7, Z25 // 62027547008c7ef1ffffff or 6202f547008c7ef1ffffff VPSHUFB Z9, Z12, K7, Z12 // 62521d4f00e1 or 62529d4f00e1 VPSHUFB Z12, Z12, K7, Z12 // 62521d4f00e4 or 62529d4f00e4 VPSHUFB 15(R8)(R14*8), Z12, K7, Z12 // 62121d4f00a4f00f000000 or 62129d4f00a4f00f000000 VPSHUFB -15(R14)(R15*2), Z12, K7, Z12 // 62121d4f00a47ef1ffffff or 62129d4f00a47ef1ffffff VPSHUFB Z9, Z17, K7, Z12 // 6252754700e1 or 6252f54700e1 VPSHUFB Z12, Z17, K7, Z12 // 6252754700e4 or 6252f54700e4 VPSHUFB 15(R8)(R14*8), Z17, K7, Z12 // 6212754700a4f00f000000 or 6212f54700a4f00f000000 VPSHUFB -15(R14)(R15*2), Z17, K7, Z12 // 6212754700a47ef1ffffff or 6212f54700a47ef1ffffff VPSHUFHW $13, X11, K2, X31 // 62417e0a70fb0d or 6241fe0a70fb0d VPSHUFHW $13, -17(BP)(SI*2), K2, X31 // 62617e0a70bc75efffffff0d or 6261fe0a70bc75efffffff0d VPSHUFHW $13, 7(AX)(CX*2), K2, X31 // 62617e0a70bc48070000000d or 6261fe0a70bc48070000000d VPSHUFHW $65, Y11, K5, Y6 // 62d17e2d70f341 or 62d1fe2d70f341 VPSHUFHW $65, 15(R8), K5, Y6 // 62d17e2d70b00f00000041 or 62d1fe2d70b00f00000041 VPSHUFHW $65, (BP), K5, Y6 // 62f17e2d70750041 or 62f1fe2d70750041 VPSHUFHW $67, Z0, K3, Z7 // 62f17e4b70f843 or 62f1fe4b70f843 VPSHUFHW $67, Z6, K3, Z7 // 62f17e4b70fe43 or 62f1fe4b70fe43 VPSHUFHW $67, (SI), K3, Z7 // 62f17e4b703e43 or 62f1fe4b703e43 VPSHUFHW $67, 7(SI)(DI*2), K3, Z7 // 62f17e4b70bc7e0700000043 or 62f1fe4b70bc7e0700000043 VPSHUFHW $67, Z0, K3, Z9 // 62717e4b70c843 or 6271fe4b70c843 VPSHUFHW $67, Z6, K3, Z9 // 62717e4b70ce43 or 6271fe4b70ce43 VPSHUFHW $67, (SI), K3, Z9 // 62717e4b700e43 or 6271fe4b700e43 VPSHUFHW $67, 7(SI)(DI*2), K3, Z9 // 62717e4b708c7e0700000043 or 6271fe4b708c7e0700000043 VPSHUFLW $127, X5, K4, X22 // 62e17f0c70f57f or 62e1ff0c70f57f VPSHUFLW $127, 15(R8)(R14*1), K4, X22 // 62817f0c70b4300f0000007f or 6281ff0c70b4300f0000007f VPSHUFLW $127, 15(R8)(R14*2), K4, X22 // 62817f0c70b4700f0000007f or 6281ff0c70b4700f0000007f VPSHUFLW $0, Y7, K2, Y19 // 62e17f2a70df00 or 62e1ff2a70df00 VPSHUFLW $0, 15(R8)(R14*8), K2, Y19 // 62817f2a709cf00f00000000 or 6281ff2a709cf00f00000000 VPSHUFLW $0, -15(R14)(R15*2), K2, Y19 // 62817f2a709c7ef1ffffff00 or 6281ff2a709c7ef1ffffff00 VPSHUFLW $97, Z3, K2, Z20 // 62e17f4a70e361 or 62e1ff4a70e361 VPSHUFLW $97, Z30, K2, Z20 // 62817f4a70e661 or 6281ff4a70e661 VPSHUFLW $97, 17(SP)(BP*8), K2, Z20 // 62e17f4a70a4ec1100000061 or 62e1ff4a70a4ec1100000061 VPSHUFLW $97, 17(SP)(BP*4), K2, Z20 // 62e17f4a70a4ac1100000061 or 62e1ff4a70a4ac1100000061 VPSHUFLW $97, Z3, K2, Z28 // 62617f4a70e361 or 6261ff4a70e361 VPSHUFLW $97, Z30, K2, Z28 // 62017f4a70e661 or 6201ff4a70e661 VPSHUFLW $97, 17(SP)(BP*8), K2, Z28 // 62617f4a70a4ec1100000061 or 6261ff4a70a4ec1100000061 VPSHUFLW $97, 17(SP)(BP*4), K2, Z28 // 62617f4a70a4ac1100000061 or 6261ff4a70a4ac1100000061 VPSLLDQ $64, X8, X18 // 62d16d0073f840 or 62d1ed0073f840 VPSLLDQ $64, -7(CX)(DX*1), X18 // 62f16d0073bc11f9ffffff40 or 62f1ed0073bc11f9ffffff40 VPSLLDQ $64, -15(R14)(R15*4), X18 // 62916d0073bcbef1ffffff40 or 6291ed0073bcbef1ffffff40 VPSLLDQ $27, Y12, Y20 // 62d15d2073fc1b or 62d1dd2073fc1b VPSLLDQ $27, 7(AX)(CX*4), Y20 // 62f15d2073bc88070000001b or 62f1dd2073bc88070000001b VPSLLDQ $27, 7(AX)(CX*1), Y20 // 62f15d2073bc08070000001b or 62f1dd2073bc08070000001b VPSLLDQ $47, Z7, Z2 // 62f16d4873ff2f or 62f1ed4873ff2f VPSLLDQ $47, Z13, Z2 // 62d16d4873fd2f or 62d1ed4873fd2f VPSLLDQ $47, 17(SP), Z2 // 62f16d4873bc24110000002f or 62f1ed4873bc24110000002f VPSLLDQ $47, -17(BP)(SI*4), Z2 // 62f16d4873bcb5efffffff2f or 62f1ed4873bcb5efffffff2f VPSLLDQ $47, Z7, Z21 // 62f1554073ff2f or 62f1d54073ff2f VPSLLDQ $47, Z13, Z21 // 62d1554073fd2f or 62d1d54073fd2f VPSLLDQ $47, 17(SP), Z21 // 62f1554073bc24110000002f or 62f1d54073bc24110000002f VPSLLDQ $47, -17(BP)(SI*4), Z21 // 62f1554073bcb5efffffff2f or 62f1d54073bcb5efffffff2f VPSLLVW X11, X1, K7, X22 // 62c2f50f12f3 VPSLLVW 7(AX)(CX*4), X1, K7, X22 // 62e2f50f12b48807000000 VPSLLVW 7(AX)(CX*1), X1, K7, X22 // 62e2f50f12b40807000000 VPSLLVW Y9, Y7, K7, Y17 // 62c2c52f12c9 VPSLLVW 17(SP), Y7, K7, Y17 // 62e2c52f128c2411000000 VPSLLVW -17(BP)(SI*4), Y7, K7, Y17 // 62e2c52f128cb5efffffff VPSLLVW Z3, Z14, K6, Z28 // 62628d4e12e3 VPSLLVW Z12, Z14, K6, Z28 // 62428d4e12e4 VPSLLVW 7(SI)(DI*8), Z14, K6, Z28 // 62628d4e12a4fe07000000 VPSLLVW -15(R14), Z14, K6, Z28 // 62428d4e12a6f1ffffff VPSLLVW Z3, Z28, K6, Z28 // 62629d4612e3 VPSLLVW Z12, Z28, K6, Z28 // 62429d4612e4 VPSLLVW 7(SI)(DI*8), Z28, K6, Z28 // 62629d4612a4fe07000000 VPSLLVW -15(R14), Z28, K6, Z28 // 62429d4612a6f1ffffff VPSLLVW Z3, Z14, K6, Z13 // 62728d4e12eb VPSLLVW Z12, Z14, K6, Z13 // 62528d4e12ec VPSLLVW 7(SI)(DI*8), Z14, K6, Z13 // 62728d4e12acfe07000000 VPSLLVW -15(R14), Z14, K6, Z13 // 62528d4e12aef1ffffff VPSLLVW Z3, Z28, K6, Z13 // 62729d4612eb VPSLLVW Z12, Z28, K6, Z13 // 62529d4612ec VPSLLVW 7(SI)(DI*8), Z28, K6, Z13 // 62729d4612acfe07000000 VPSLLVW -15(R14), Z28, K6, Z13 // 62529d4612aef1ffffff VPSLLW $121, X7, K3, X6 // 62f14d0b71f779 or 62f1cd0b71f779 VPSLLW $121, (SI), K3, X6 // 62f14d0b713679 or 62f1cd0b713679 VPSLLW $121, 7(SI)(DI*2), K3, X6 // 62f14d0b71b47e0700000079 or 62f1cd0b71b47e0700000079 VPSLLW $13, Y8, K7, Y31 // 62d1052771f00d or 62d1852771f00d VPSLLW $13, 7(AX), K7, Y31 // 62f1052771b0070000000d or 62f1852771b0070000000d VPSLLW $13, (DI), K7, Y31 // 62f1052771370d or 62f1852771370d VPSLLW $65, Z19, K4, Z15 // 62b1054c71f341 or 62b1854c71f341 VPSLLW $65, Z15, K4, Z15 // 62d1054c71f741 or 62d1854c71f741 VPSLLW $65, 7(SI)(DI*1), K4, Z15 // 62f1054c71b43e0700000041 or 62f1854c71b43e0700000041 VPSLLW $65, 15(DX)(BX*8), K4, Z15 // 62f1054c71b4da0f00000041 or 62f1854c71b4da0f00000041 VPSLLW $65, Z19, K4, Z30 // 62b10d4471f341 or 62b18d4471f341 VPSLLW $65, Z15, K4, Z30 // 62d10d4471f741 or 62d18d4471f741 VPSLLW $65, 7(SI)(DI*1), K4, Z30 // 62f10d4471b43e0700000041 or 62f18d4471b43e0700000041 VPSLLW $65, 15(DX)(BX*8), K4, Z30 // 62f10d4471b4da0f00000041 or 62f18d4471b4da0f00000041 VPSLLW X3, X31, K4, X8 // 62710504f1c3 or 62718504f1c3 VPSLLW 17(SP)(BP*8), X31, K4, X8 // 62710504f184ec11000000 or 62718504f184ec11000000 VPSLLW 17(SP)(BP*4), X31, K4, X8 // 62710504f184ac11000000 or 62718504f184ac11000000 VPSLLW X28, Y28, K7, Y1 // 62911d27f1cc or 62919d27f1cc VPSLLW 7(SI)(DI*4), Y28, K7, Y1 // 62f11d27f18cbe07000000 or 62f19d27f18cbe07000000 VPSLLW -7(DI)(R8*2), Y28, K7, Y1 // 62b11d27f18c47f9ffffff or 62b19d27f18c47f9ffffff VPSLLW X20, Z3, K2, Z5 // 62b1654af1ec or 62b1e54af1ec VPSLLW 17(SP), Z3, K2, Z5 // 62f1654af1ac2411000000 or 62f1e54af1ac2411000000 VPSLLW -17(BP)(SI*4), Z3, K2, Z5 // 62f1654af1acb5efffffff or 62f1e54af1acb5efffffff VPSLLW X20, Z5, K2, Z5 // 62b1554af1ec or 62b1d54af1ec VPSLLW 17(SP), Z5, K2, Z5 // 62f1554af1ac2411000000 or 62f1d54af1ac2411000000 VPSLLW -17(BP)(SI*4), Z5, K2, Z5 // 62f1554af1acb5efffffff or 62f1d54af1acb5efffffff VPSLLW X20, Z3, K2, Z1 // 62b1654af1cc or 62b1e54af1cc VPSLLW 17(SP), Z3, K2, Z1 // 62f1654af18c2411000000 or 62f1e54af18c2411000000 VPSLLW -17(BP)(SI*4), Z3, K2, Z1 // 62f1654af18cb5efffffff or 62f1e54af18cb5efffffff VPSLLW X20, Z5, K2, Z1 // 62b1554af1cc or 62b1d54af1cc VPSLLW 17(SP), Z5, K2, Z1 // 62f1554af18c2411000000 or 62f1d54af18c2411000000 VPSLLW -17(BP)(SI*4), Z5, K2, Z1 // 62f1554af18cb5efffffff or 62f1d54af18cb5efffffff VPSRAVW X8, X28, K4, X16 // 62c29d0411c0 VPSRAVW 15(R8)(R14*4), X28, K4, X16 // 62829d041184b00f000000 VPSRAVW -7(CX)(DX*4), X28, K4, X16 // 62e29d04118491f9ffffff VPSRAVW Y7, Y26, K1, Y30 // 6262ad2111f7 VPSRAVW -7(DI)(R8*1), Y26, K1, Y30 // 6222ad2111b407f9ffffff VPSRAVW (SP), Y26, K1, Y30 // 6262ad21113424 VPSRAVW Z21, Z31, K3, Z17 // 62a2854311cd VPSRAVW Z9, Z31, K3, Z17 // 62c2854311c9 VPSRAVW (BX), Z31, K3, Z17 // 62e28543110b VPSRAVW -17(BP)(SI*1), Z31, K3, Z17 // 62e28543118c35efffffff VPSRAVW Z21, Z0, K3, Z17 // 62a2fd4b11cd VPSRAVW Z9, Z0, K3, Z17 // 62c2fd4b11c9 VPSRAVW (BX), Z0, K3, Z17 // 62e2fd4b110b VPSRAVW -17(BP)(SI*1), Z0, K3, Z17 // 62e2fd4b118c35efffffff VPSRAVW Z21, Z31, K3, Z23 // 62a2854311fd VPSRAVW Z9, Z31, K3, Z23 // 62c2854311f9 VPSRAVW (BX), Z31, K3, Z23 // 62e28543113b VPSRAVW -17(BP)(SI*1), Z31, K3, Z23 // 62e2854311bc35efffffff VPSRAVW Z21, Z0, K3, Z23 // 62a2fd4b11fd VPSRAVW Z9, Z0, K3, Z23 // 62c2fd4b11f9 VPSRAVW (BX), Z0, K3, Z23 // 62e2fd4b113b VPSRAVW -17(BP)(SI*1), Z0, K3, Z23 // 62e2fd4b11bc35efffffff VPSRAW $79, X11, K4, X15 // 62d1050c71e34f or 62d1850c71e34f VPSRAW $79, (R8), K4, X15 // 62d1050c71204f or 62d1850c71204f VPSRAW $79, 15(DX)(BX*2), K4, X15 // 62f1050c71a45a0f0000004f or 62f1850c71a45a0f0000004f VPSRAW $64, Y1, K5, Y16 // 62f17d2571e140 or 62f1fd2571e140 VPSRAW $64, -7(CX), K5, Y16 // 62f17d2571a1f9ffffff40 or 62f1fd2571a1f9ffffff40 VPSRAW $64, 15(DX)(BX*4), K5, Y16 // 62f17d2571a49a0f00000040 or 62f1fd2571a49a0f00000040 VPSRAW $27, Z1, K7, Z6 // 62f14d4f71e11b or 62f1cd4f71e11b VPSRAW $27, Z9, K7, Z6 // 62d14d4f71e11b or 62d1cd4f71e11b VPSRAW $27, 15(R8)(R14*4), K7, Z6 // 62914d4f71a4b00f0000001b or 6291cd4f71a4b00f0000001b VPSRAW $27, -7(CX)(DX*4), K7, Z6 // 62f14d4f71a491f9ffffff1b or 62f1cd4f71a491f9ffffff1b VPSRAW $27, Z1, K7, Z9 // 62f1354f71e11b or 62f1b54f71e11b VPSRAW $27, Z9, K7, Z9 // 62d1354f71e11b or 62d1b54f71e11b VPSRAW $27, 15(R8)(R14*4), K7, Z9 // 6291354f71a4b00f0000001b or 6291b54f71a4b00f0000001b VPSRAW $27, -7(CX)(DX*4), K7, Z9 // 62f1354f71a491f9ffffff1b or 62f1b54f71a491f9ffffff1b VPSRAW X13, X19, K7, X1 // 62d16507e1cd or 62d1e507e1cd VPSRAW 17(SP)(BP*1), X19, K7, X1 // 62f16507e18c2c11000000 or 62f1e507e18c2c11000000 VPSRAW -7(CX)(DX*8), X19, K7, X1 // 62f16507e18cd1f9ffffff or 62f1e507e18cd1f9ffffff VPSRAW X2, Y31, K6, Y30 // 62610526e1f2 or 62618526e1f2 VPSRAW -17(BP)(SI*2), Y31, K6, Y30 // 62610526e1b475efffffff or 62618526e1b475efffffff VPSRAW 7(AX)(CX*2), Y31, K6, Y30 // 62610526e1b44807000000 or 62618526e1b44807000000 VPSRAW X14, Z30, K3, Z20 // 62c10d43e1e6 or 62c18d43e1e6 VPSRAW 15(R8)(R14*1), Z30, K3, Z20 // 62810d43e1a4300f000000 or 62818d43e1a4300f000000 VPSRAW 15(R8)(R14*2), Z30, K3, Z20 // 62810d43e1a4700f000000 or 62818d43e1a4700f000000 VPSRAW X14, Z5, K3, Z20 // 62c1554be1e6 or 62c1d54be1e6 VPSRAW 15(R8)(R14*1), Z5, K3, Z20 // 6281554be1a4300f000000 or 6281d54be1a4300f000000 VPSRAW 15(R8)(R14*2), Z5, K3, Z20 // 6281554be1a4700f000000 or 6281d54be1a4700f000000 VPSRAW X14, Z30, K3, Z9 // 62510d43e1ce or 62518d43e1ce VPSRAW 15(R8)(R14*1), Z30, K3, Z9 // 62110d43e18c300f000000 or 62118d43e18c300f000000 VPSRAW 15(R8)(R14*2), Z30, K3, Z9 // 62110d43e18c700f000000 or 62118d43e18c700f000000 VPSRAW X14, Z5, K3, Z9 // 6251554be1ce or 6251d54be1ce VPSRAW 15(R8)(R14*1), Z5, K3, Z9 // 6211554be18c300f000000 or 6211d54be18c300f000000 VPSRAW 15(R8)(R14*2), Z5, K3, Z9 // 6211554be18c700f000000 or 6211d54be18c700f000000 VPSRLDQ $94, -7(CX)(DX*1), X9 // 62f13508739c11f9ffffff5e or 62f1b508739c11f9ffffff5e VPSRLDQ $94, -15(R14)(R15*4), X9 // 62913508739cbef1ffffff5e or 6291b508739cbef1ffffff5e VPSRLDQ $121, Y28, Y0 // 62917d2873dc79 or 6291fd2873dc79 VPSRLDQ $121, (AX), Y0 // 62f17d28731879 or 62f1fd28731879 VPSRLDQ $121, 7(SI), Y0 // 62f17d28739e0700000079 or 62f1fd28739e0700000079 VPSRLDQ $13, Z21, Z12 // 62b11d4873dd0d or 62b19d4873dd0d VPSRLDQ $13, Z9, Z12 // 62d11d4873d90d or 62d19d4873d90d VPSRLDQ $13, 17(SP)(BP*1), Z12 // 62f11d48739c2c110000000d or 62f19d48739c2c110000000d VPSRLDQ $13, -7(CX)(DX*8), Z12 // 62f11d48739cd1f9ffffff0d or 62f19d48739cd1f9ffffff0d VPSRLDQ $13, Z21, Z13 // 62b1154873dd0d or 62b1954873dd0d VPSRLDQ $13, Z9, Z13 // 62d1154873d90d or 62d1954873d90d VPSRLDQ $13, 17(SP)(BP*1), Z13 // 62f11548739c2c110000000d or 62f19548739c2c110000000d VPSRLDQ $13, -7(CX)(DX*8), Z13 // 62f11548739cd1f9ffffff0d or 62f19548739cd1f9ffffff0d VPSRLVW X30, X23, K1, X12 // 6212c50110e6 VPSRLVW 7(AX)(CX*4), X23, K1, X12 // 6272c50110a48807000000 VPSRLVW 7(AX)(CX*1), X23, K1, X12 // 6272c50110a40807000000 VPSRLVW Y3, Y22, K1, Y12 // 6272cd2110e3 VPSRLVW 17(SP)(BP*1), Y22, K1, Y12 // 6272cd2110a42c11000000 VPSRLVW -7(CX)(DX*8), Y22, K1, Y12 // 6272cd2110a4d1f9ffffff VPSRLVW Z14, Z15, K1, Z0 // 62d2854910c6 VPSRLVW Z27, Z15, K1, Z0 // 6292854910c3 VPSRLVW 99(R15)(R15*4), Z15, K1, Z0 // 629285491084bf63000000 VPSRLVW 15(DX), Z15, K1, Z0 // 62f2854910820f000000 VPSRLVW Z14, Z12, K1, Z0 // 62d29d4910c6 VPSRLVW Z27, Z12, K1, Z0 // 62929d4910c3 VPSRLVW 99(R15)(R15*4), Z12, K1, Z0 // 62929d491084bf63000000 VPSRLVW 15(DX), Z12, K1, Z0 // 62f29d4910820f000000 VPSRLVW Z14, Z15, K1, Z8 // 6252854910c6 VPSRLVW Z27, Z15, K1, Z8 // 6212854910c3 VPSRLVW 99(R15)(R15*4), Z15, K1, Z8 // 621285491084bf63000000 VPSRLVW 15(DX), Z15, K1, Z8 // 6272854910820f000000 VPSRLVW Z14, Z12, K1, Z8 // 62529d4910c6 VPSRLVW Z27, Z12, K1, Z8 // 62129d4910c3 VPSRLVW 99(R15)(R15*4), Z12, K1, Z8 // 62129d491084bf63000000 VPSRLVW 15(DX), Z12, K1, Z8 // 62729d4910820f000000 VPSRLW $0, X20, K7, X8 // 62b13d0f71d400 or 62b1bd0f71d400 VPSRLW $0, (SI), K7, X8 // 62f13d0f711600 or 62f1bd0f711600 VPSRLW $0, 7(SI)(DI*2), K7, X8 // 62f13d0f71947e0700000000 or 62f1bd0f71947e0700000000 VPSRLW $97, Y1, K2, Y15 // 62f1052a71d161 or 62f1852a71d161 VPSRLW $97, -17(BP)(SI*2), K2, Y15 // 62f1052a719475efffffff61 or 62f1852a719475efffffff61 VPSRLW $97, 7(AX)(CX*2), K2, Y15 // 62f1052a7194480700000061 or 62f1852a7194480700000061 VPSRLW $81, Z13, K4, Z11 // 62d1254c71d551 or 62d1a54c71d551 VPSRLW $81, Z14, K4, Z11 // 62d1254c71d651 or 62d1a54c71d651 VPSRLW $81, (CX), K4, Z11 // 62f1254c711151 or 62f1a54c711151 VPSRLW $81, 99(R15), K4, Z11 // 62d1254c71976300000051 or 62d1a54c71976300000051 VPSRLW $81, Z13, K4, Z5 // 62d1554c71d551 or 62d1d54c71d551 VPSRLW $81, Z14, K4, Z5 // 62d1554c71d651 or 62d1d54c71d651 VPSRLW $81, (CX), K4, Z5 // 62f1554c711151 or 62f1d54c711151 VPSRLW $81, 99(R15), K4, Z5 // 62d1554c71976300000051 or 62d1d54c71976300000051 VPSRLW X26, X9, K1, X2 // 62913509d1d2 or 6291b509d1d2 VPSRLW 17(SP)(BP*8), X9, K1, X2 // 62f13509d194ec11000000 or 62f1b509d194ec11000000 VPSRLW 17(SP)(BP*4), X9, K1, X2 // 62f13509d194ac11000000 or 62f1b509d194ac11000000 VPSRLW X19, Y19, K3, Y27 // 62216523d1db or 6221e523d1db VPSRLW 7(SI)(DI*4), Y19, K3, Y27 // 62616523d19cbe07000000 or 6261e523d19cbe07000000 VPSRLW -7(DI)(R8*2), Y19, K3, Y27 // 62216523d19c47f9ffffff or 6221e523d19c47f9ffffff VPSRLW X0, Z2, K4, Z5 // 62f16d4cd1e8 or 62f1ed4cd1e8 VPSRLW 17(SP), Z2, K4, Z5 // 62f16d4cd1ac2411000000 or 62f1ed4cd1ac2411000000 VPSRLW -17(BP)(SI*4), Z2, K4, Z5 // 62f16d4cd1acb5efffffff or 62f1ed4cd1acb5efffffff VPSRLW X0, Z2, K4, Z23 // 62e16d4cd1f8 or 62e1ed4cd1f8 VPSRLW 17(SP), Z2, K4, Z23 // 62e16d4cd1bc2411000000 or 62e1ed4cd1bc2411000000 VPSRLW -17(BP)(SI*4), Z2, K4, Z23 // 62e16d4cd1bcb5efffffff or 62e1ed4cd1bcb5efffffff VPSUBB X7, X16, K5, X31 // 62617d05f8ff or 6261fd05f8ff VPSUBB 7(AX), X16, K5, X31 // 62617d05f8b807000000 or 6261fd05f8b807000000 VPSUBB (DI), X16, K5, X31 // 62617d05f83f or 6261fd05f83f VPSUBB Y13, Y17, K7, Y5 // 62d17527f8ed or 62d1f527f8ed VPSUBB 15(R8)(R14*1), Y17, K7, Y5 // 62917527f8ac300f000000 or 6291f527f8ac300f000000 VPSUBB 15(R8)(R14*2), Y17, K7, Y5 // 62917527f8ac700f000000 or 6291f527f8ac700f000000 VPSUBB Z28, Z26, K7, Z6 // 62912d47f8f4 or 6291ad47f8f4 VPSUBB Z6, Z26, K7, Z6 // 62f12d47f8f6 or 62f1ad47f8f6 VPSUBB 99(R15)(R15*2), Z26, K7, Z6 // 62912d47f8b47f63000000 or 6291ad47f8b47f63000000 VPSUBB -7(DI), Z26, K7, Z6 // 62f12d47f8b7f9ffffff or 62f1ad47f8b7f9ffffff VPSUBB Z28, Z14, K7, Z6 // 62910d4ff8f4 or 62918d4ff8f4 VPSUBB Z6, Z14, K7, Z6 // 62f10d4ff8f6 or 62f18d4ff8f6 VPSUBB 99(R15)(R15*2), Z14, K7, Z6 // 62910d4ff8b47f63000000 or 62918d4ff8b47f63000000 VPSUBB -7(DI), Z14, K7, Z6 // 62f10d4ff8b7f9ffffff or 62f18d4ff8b7f9ffffff VPSUBB Z28, Z26, K7, Z14 // 62112d47f8f4 or 6211ad47f8f4 VPSUBB Z6, Z26, K7, Z14 // 62712d47f8f6 or 6271ad47f8f6 VPSUBB 99(R15)(R15*2), Z26, K7, Z14 // 62112d47f8b47f63000000 or 6211ad47f8b47f63000000 VPSUBB -7(DI), Z26, K7, Z14 // 62712d47f8b7f9ffffff or 6271ad47f8b7f9ffffff VPSUBB Z28, Z14, K7, Z14 // 62110d4ff8f4 or 62118d4ff8f4 VPSUBB Z6, Z14, K7, Z14 // 62710d4ff8f6 or 62718d4ff8f6 VPSUBB 99(R15)(R15*2), Z14, K7, Z14 // 62110d4ff8b47f63000000 or 62118d4ff8b47f63000000 VPSUBB -7(DI), Z14, K7, Z14 // 62710d4ff8b7f9ffffff or 62718d4ff8b7f9ffffff VPSUBSB X28, X0, K2, X21 // 62817d0ae8ec or 6281fd0ae8ec VPSUBSB 7(SI)(DI*8), X0, K2, X21 // 62e17d0ae8acfe07000000 or 62e1fd0ae8acfe07000000 VPSUBSB -15(R14), X0, K2, X21 // 62c17d0ae8aef1ffffff or 62c1fd0ae8aef1ffffff VPSUBSB Y24, Y11, K5, Y8 // 6211252de8c0 or 6211a52de8c0 VPSUBSB (CX), Y11, K5, Y8 // 6271252de801 or 6271a52de801 VPSUBSB 99(R15), Y11, K5, Y8 // 6251252de88763000000 or 6251a52de88763000000 VPSUBSB Z23, Z23, K3, Z27 // 62214543e8df or 6221c543e8df VPSUBSB Z6, Z23, K3, Z27 // 62614543e8de or 6261c543e8de VPSUBSB -17(BP), Z23, K3, Z27 // 62614543e89defffffff or 6261c543e89defffffff VPSUBSB -15(R14)(R15*8), Z23, K3, Z27 // 62014543e89cfef1ffffff or 6201c543e89cfef1ffffff VPSUBSB Z23, Z5, K3, Z27 // 6221554be8df or 6221d54be8df VPSUBSB Z6, Z5, K3, Z27 // 6261554be8de or 6261d54be8de VPSUBSB -17(BP), Z5, K3, Z27 // 6261554be89defffffff or 6261d54be89defffffff VPSUBSB -15(R14)(R15*8), Z5, K3, Z27 // 6201554be89cfef1ffffff or 6201d54be89cfef1ffffff VPSUBSB Z23, Z23, K3, Z15 // 62314543e8ff or 6231c543e8ff VPSUBSB Z6, Z23, K3, Z15 // 62714543e8fe or 6271c543e8fe VPSUBSB -17(BP), Z23, K3, Z15 // 62714543e8bdefffffff or 6271c543e8bdefffffff VPSUBSB -15(R14)(R15*8), Z23, K3, Z15 // 62114543e8bcfef1ffffff or 6211c543e8bcfef1ffffff VPSUBSB Z23, Z5, K3, Z15 // 6231554be8ff or 6231d54be8ff VPSUBSB Z6, Z5, K3, Z15 // 6271554be8fe or 6271d54be8fe VPSUBSB -17(BP), Z5, K3, Z15 // 6271554be8bdefffffff or 6271d54be8bdefffffff VPSUBSB -15(R14)(R15*8), Z5, K3, Z15 // 6211554be8bcfef1ffffff or 6211d54be8bcfef1ffffff VPSUBSW X19, X7, K4, X22 // 62a1450ce9f3 or 62a1c50ce9f3 VPSUBSW 7(SI)(DI*1), X7, K4, X22 // 62e1450ce9b43e07000000 or 62e1c50ce9b43e07000000 VPSUBSW 15(DX)(BX*8), X7, K4, X22 // 62e1450ce9b4da0f000000 or 62e1c50ce9b4da0f000000 VPSUBSW Y21, Y24, K2, Y5 // 62b13d22e9ed or 62b1bd22e9ed VPSUBSW 99(R15)(R15*2), Y24, K2, Y5 // 62913d22e9ac7f63000000 or 6291bd22e9ac7f63000000 VPSUBSW -7(DI), Y24, K2, Y5 // 62f13d22e9aff9ffffff or 62f1bd22e9aff9ffffff VPSUBSW Z16, Z21, K2, Z8 // 62315542e9c0 or 6231d542e9c0 VPSUBSW Z13, Z21, K2, Z8 // 62515542e9c5 or 6251d542e9c5 VPSUBSW 17(SP)(BP*2), Z21, K2, Z8 // 62715542e9846c11000000 or 6271d542e9846c11000000 VPSUBSW -7(DI)(R8*4), Z21, K2, Z8 // 62315542e98487f9ffffff or 6231d542e98487f9ffffff VPSUBSW Z16, Z5, K2, Z8 // 6231554ae9c0 or 6231d54ae9c0 VPSUBSW Z13, Z5, K2, Z8 // 6251554ae9c5 or 6251d54ae9c5 VPSUBSW 17(SP)(BP*2), Z5, K2, Z8 // 6271554ae9846c11000000 or 6271d54ae9846c11000000 VPSUBSW -7(DI)(R8*4), Z5, K2, Z8 // 6231554ae98487f9ffffff or 6231d54ae98487f9ffffff VPSUBSW Z16, Z21, K2, Z28 // 62215542e9e0 or 6221d542e9e0 VPSUBSW Z13, Z21, K2, Z28 // 62415542e9e5 or 6241d542e9e5 VPSUBSW 17(SP)(BP*2), Z21, K2, Z28 // 62615542e9a46c11000000 or 6261d542e9a46c11000000 VPSUBSW -7(DI)(R8*4), Z21, K2, Z28 // 62215542e9a487f9ffffff or 6221d542e9a487f9ffffff VPSUBSW Z16, Z5, K2, Z28 // 6221554ae9e0 or 6221d54ae9e0 VPSUBSW Z13, Z5, K2, Z28 // 6241554ae9e5 or 6241d54ae9e5 VPSUBSW 17(SP)(BP*2), Z5, K2, Z28 // 6261554ae9a46c11000000 or 6261d54ae9a46c11000000 VPSUBSW -7(DI)(R8*4), Z5, K2, Z28 // 6221554ae9a487f9ffffff or 6221d54ae9a487f9ffffff VPSUBUSB X31, X16, K3, X7 // 62917d03d8ff or 6291fd03d8ff VPSUBUSB -7(DI)(R8*1), X16, K3, X7 // 62b17d03d8bc07f9ffffff or 62b1fd03d8bc07f9ffffff VPSUBUSB (SP), X16, K3, X7 // 62f17d03d83c24 or 62f1fd03d83c24 VPSUBUSB Y13, Y9, K3, Y16 // 62c1352bd8c5 or 62c1b52bd8c5 VPSUBUSB -7(CX)(DX*1), Y9, K3, Y16 // 62e1352bd88411f9ffffff or 62e1b52bd88411f9ffffff VPSUBUSB -15(R14)(R15*4), Y9, K3, Y16 // 6281352bd884bef1ffffff or 6281b52bd884bef1ffffff VPSUBUSB Z6, Z22, K3, Z12 // 62714d43d8e6 or 6271cd43d8e6 VPSUBUSB Z8, Z22, K3, Z12 // 62514d43d8e0 or 6251cd43d8e0 VPSUBUSB 15(R8), Z22, K3, Z12 // 62514d43d8a00f000000 or 6251cd43d8a00f000000 VPSUBUSB (BP), Z22, K3, Z12 // 62714d43d86500 or 6271cd43d86500 VPSUBUSB Z6, Z11, K3, Z12 // 6271254bd8e6 or 6271a54bd8e6 VPSUBUSB Z8, Z11, K3, Z12 // 6251254bd8e0 or 6251a54bd8e0 VPSUBUSB 15(R8), Z11, K3, Z12 // 6251254bd8a00f000000 or 6251a54bd8a00f000000 VPSUBUSB (BP), Z11, K3, Z12 // 6271254bd86500 or 6271a54bd86500 VPSUBUSB Z6, Z22, K3, Z27 // 62614d43d8de or 6261cd43d8de VPSUBUSB Z8, Z22, K3, Z27 // 62414d43d8d8 or 6241cd43d8d8 VPSUBUSB 15(R8), Z22, K3, Z27 // 62414d43d8980f000000 or 6241cd43d8980f000000 VPSUBUSB (BP), Z22, K3, Z27 // 62614d43d85d00 or 6261cd43d85d00 VPSUBUSB Z6, Z11, K3, Z27 // 6261254bd8de or 6261a54bd8de VPSUBUSB Z8, Z11, K3, Z27 // 6241254bd8d8 or 6241a54bd8d8 VPSUBUSB 15(R8), Z11, K3, Z27 // 6241254bd8980f000000 or 6241a54bd8980f000000 VPSUBUSB (BP), Z11, K3, Z27 // 6261254bd85d00 or 6261a54bd85d00 VPSUBUSW X9, X7, K2, X1 // 62d1450ad9c9 or 62d1c50ad9c9 VPSUBUSW -7(CX), X7, K2, X1 // 62f1450ad989f9ffffff or 62f1c50ad989f9ffffff VPSUBUSW 15(DX)(BX*4), X7, K2, X1 // 62f1450ad98c9a0f000000 or 62f1c50ad98c9a0f000000 VPSUBUSW Y3, Y6, K1, Y9 // 62714d29d9cb or 6271cd29d9cb VPSUBUSW 15(DX)(BX*1), Y6, K1, Y9 // 62714d29d98c1a0f000000 or 6271cd29d98c1a0f000000 VPSUBUSW -7(CX)(DX*2), Y6, K1, Y9 // 62714d29d98c51f9ffffff or 6271cd29d98c51f9ffffff VPSUBUSW Z9, Z12, K2, Z25 // 62411d4ad9c9 or 62419d4ad9c9 VPSUBUSW Z12, Z12, K2, Z25 // 62411d4ad9cc or 62419d4ad9cc VPSUBUSW 15(R8)(R14*8), Z12, K2, Z25 // 62011d4ad98cf00f000000 or 62019d4ad98cf00f000000 VPSUBUSW -15(R14)(R15*2), Z12, K2, Z25 // 62011d4ad98c7ef1ffffff or 62019d4ad98c7ef1ffffff VPSUBUSW Z9, Z17, K2, Z25 // 62417542d9c9 or 6241f542d9c9 VPSUBUSW Z12, Z17, K2, Z25 // 62417542d9cc or 6241f542d9cc VPSUBUSW 15(R8)(R14*8), Z17, K2, Z25 // 62017542d98cf00f000000 or 6201f542d98cf00f000000 VPSUBUSW -15(R14)(R15*2), Z17, K2, Z25 // 62017542d98c7ef1ffffff or 6201f542d98c7ef1ffffff VPSUBUSW Z9, Z12, K2, Z12 // 62511d4ad9e1 or 62519d4ad9e1 VPSUBUSW Z12, Z12, K2, Z12 // 62511d4ad9e4 or 62519d4ad9e4 VPSUBUSW 15(R8)(R14*8), Z12, K2, Z12 // 62111d4ad9a4f00f000000 or 62119d4ad9a4f00f000000 VPSUBUSW -15(R14)(R15*2), Z12, K2, Z12 // 62111d4ad9a47ef1ffffff or 62119d4ad9a47ef1ffffff VPSUBUSW Z9, Z17, K2, Z12 // 62517542d9e1 or 6251f542d9e1 VPSUBUSW Z12, Z17, K2, Z12 // 62517542d9e4 or 6251f542d9e4 VPSUBUSW 15(R8)(R14*8), Z17, K2, Z12 // 62117542d9a4f00f000000 or 6211f542d9a4f00f000000 VPSUBUSW -15(R14)(R15*2), Z17, K2, Z12 // 62117542d9a47ef1ffffff or 6211f542d9a47ef1ffffff VPSUBW X0, X12, K1, X15 // 62711d09f9f8 or 62719d09f9f8 VPSUBW 99(R15)(R15*8), X12, K1, X15 // 62111d09f9bcff63000000 or 62119d09f9bcff63000000 VPSUBW 7(AX)(CX*8), X12, K1, X15 // 62711d09f9bcc807000000 or 62719d09f9bcc807000000 VPSUBW Y26, Y6, K7, Y7 // 62914d2ff9fa or 6291cd2ff9fa VPSUBW -17(BP), Y6, K7, Y7 // 62f14d2ff9bdefffffff or 62f1cd2ff9bdefffffff VPSUBW -15(R14)(R15*8), Y6, K7, Y7 // 62914d2ff9bcfef1ffffff or 6291cd2ff9bcfef1ffffff VPSUBW Z8, Z3, K1, Z6 // 62d16549f9f0 or 62d1e549f9f0 VPSUBW Z2, Z3, K1, Z6 // 62f16549f9f2 or 62f1e549f9f2 VPSUBW -15(R14)(R15*1), Z3, K1, Z6 // 62916549f9b43ef1ffffff or 6291e549f9b43ef1ffffff VPSUBW -15(BX), Z3, K1, Z6 // 62f16549f9b3f1ffffff or 62f1e549f9b3f1ffffff VPSUBW Z8, Z21, K1, Z6 // 62d15541f9f0 or 62d1d541f9f0 VPSUBW Z2, Z21, K1, Z6 // 62f15541f9f2 or 62f1d541f9f2 VPSUBW -15(R14)(R15*1), Z21, K1, Z6 // 62915541f9b43ef1ffffff or 6291d541f9b43ef1ffffff VPSUBW -15(BX), Z21, K1, Z6 // 62f15541f9b3f1ffffff or 62f1d541f9b3f1ffffff VPSUBW Z8, Z3, K1, Z25 // 62416549f9c8 or 6241e549f9c8 VPSUBW Z2, Z3, K1, Z25 // 62616549f9ca or 6261e549f9ca VPSUBW -15(R14)(R15*1), Z3, K1, Z25 // 62016549f98c3ef1ffffff or 6201e549f98c3ef1ffffff VPSUBW -15(BX), Z3, K1, Z25 // 62616549f98bf1ffffff or 6261e549f98bf1ffffff VPSUBW Z8, Z21, K1, Z25 // 62415541f9c8 or 6241d541f9c8 VPSUBW Z2, Z21, K1, Z25 // 62615541f9ca or 6261d541f9ca VPSUBW -15(R14)(R15*1), Z21, K1, Z25 // 62015541f98c3ef1ffffff or 6201d541f98c3ef1ffffff VPSUBW -15(BX), Z21, K1, Z25 // 62615541f98bf1ffffff or 6261d541f98bf1ffffff VPTESTMB X26, X3, K3, K3 // 6292650b26da VPTESTMB 15(R8)(R14*4), X3, K3, K3 // 6292650b269cb00f000000 VPTESTMB -7(CX)(DX*4), X3, K3, K3 // 62f2650b269c91f9ffffff VPTESTMB X26, X3, K3, K1 // 6292650b26ca VPTESTMB 15(R8)(R14*4), X3, K3, K1 // 6292650b268cb00f000000 VPTESTMB -7(CX)(DX*4), X3, K3, K1 // 62f2650b268c91f9ffffff VPTESTMB Y3, Y18, K4, K5 // 62f26d2426eb VPTESTMB 15(R8)(R14*8), Y18, K4, K5 // 62926d2426acf00f000000 VPTESTMB -15(R14)(R15*2), Y18, K4, K5 // 62926d2426ac7ef1ffffff VPTESTMB Y3, Y18, K4, K4 // 62f26d2426e3 VPTESTMB 15(R8)(R14*8), Y18, K4, K4 // 62926d2426a4f00f000000 VPTESTMB -15(R14)(R15*2), Y18, K4, K4 // 62926d2426a47ef1ffffff VPTESTMB Z11, Z12, K5, K7 // 62d21d4d26fb VPTESTMB Z5, Z12, K5, K7 // 62f21d4d26fd VPTESTMB 17(SP)(BP*8), Z12, K5, K7 // 62f21d4d26bcec11000000 VPTESTMB 17(SP)(BP*4), Z12, K5, K7 // 62f21d4d26bcac11000000 VPTESTMB Z11, Z22, K5, K7 // 62d24d4526fb VPTESTMB Z5, Z22, K5, K7 // 62f24d4526fd VPTESTMB 17(SP)(BP*8), Z22, K5, K7 // 62f24d4526bcec11000000 VPTESTMB 17(SP)(BP*4), Z22, K5, K7 // 62f24d4526bcac11000000 VPTESTMB Z11, Z12, K5, K6 // 62d21d4d26f3 VPTESTMB Z5, Z12, K5, K6 // 62f21d4d26f5 VPTESTMB 17(SP)(BP*8), Z12, K5, K6 // 62f21d4d26b4ec11000000 VPTESTMB 17(SP)(BP*4), Z12, K5, K6 // 62f21d4d26b4ac11000000 VPTESTMB Z11, Z22, K5, K6 // 62d24d4526f3 VPTESTMB Z5, Z22, K5, K6 // 62f24d4526f5 VPTESTMB 17(SP)(BP*8), Z22, K5, K6 // 62f24d4526b4ec11000000 VPTESTMB 17(SP)(BP*4), Z22, K5, K6 // 62f24d4526b4ac11000000 VPTESTMW X15, X9, K4, K6 // 62d2b50c26f7 VPTESTMW -17(BP)(SI*2), X9, K4, K6 // 62f2b50c26b475efffffff VPTESTMW 7(AX)(CX*2), X9, K4, K6 // 62f2b50c26b44807000000 VPTESTMW X15, X9, K4, K4 // 62d2b50c26e7 VPTESTMW -17(BP)(SI*2), X9, K4, K4 // 62f2b50c26a475efffffff VPTESTMW 7(AX)(CX*2), X9, K4, K4 // 62f2b50c26a44807000000 VPTESTMW Y8, Y14, K7, K4 // 62d28d2f26e0 VPTESTMW (SI), Y14, K7, K4 // 62f28d2f2626 VPTESTMW 7(SI)(DI*2), Y14, K7, K4 // 62f28d2f26a47e07000000 VPTESTMW Y8, Y14, K7, K6 // 62d28d2f26f0 VPTESTMW (SI), Y14, K7, K6 // 62f28d2f2636 VPTESTMW 7(SI)(DI*2), Y14, K7, K6 // 62f28d2f26b47e07000000 VPTESTMW Z1, Z6, K2, K4 // 62f2cd4a26e1 VPTESTMW Z15, Z6, K2, K4 // 62d2cd4a26e7 VPTESTMW 7(AX), Z6, K2, K4 // 62f2cd4a26a007000000 VPTESTMW (DI), Z6, K2, K4 // 62f2cd4a2627 VPTESTMW Z1, Z22, K2, K4 // 62f2cd4226e1 VPTESTMW Z15, Z22, K2, K4 // 62d2cd4226e7 VPTESTMW 7(AX), Z22, K2, K4 // 62f2cd4226a007000000 VPTESTMW (DI), Z22, K2, K4 // 62f2cd422627 VPTESTMW Z1, Z6, K2, K5 // 62f2cd4a26e9 VPTESTMW Z15, Z6, K2, K5 // 62d2cd4a26ef VPTESTMW 7(AX), Z6, K2, K5 // 62f2cd4a26a807000000 VPTESTMW (DI), Z6, K2, K5 // 62f2cd4a262f VPTESTMW Z1, Z22, K2, K5 // 62f2cd4226e9 VPTESTMW Z15, Z22, K2, K5 // 62d2cd4226ef VPTESTMW 7(AX), Z22, K2, K5 // 62f2cd4226a807000000 VPTESTMW (DI), Z22, K2, K5 // 62f2cd42262f VPTESTNMB X18, X26, K5, K2 // 62b22e0526d2 VPTESTNMB 15(R8)(R14*1), X26, K5, K2 // 62922e052694300f000000 VPTESTNMB 15(R8)(R14*2), X26, K5, K2 // 62922e052694700f000000 VPTESTNMB X18, X26, K5, K7 // 62b22e0526fa VPTESTNMB 15(R8)(R14*1), X26, K5, K7 // 62922e0526bc300f000000 VPTESTNMB 15(R8)(R14*2), X26, K5, K7 // 62922e0526bc700f000000 VPTESTNMB Y11, Y20, K3, K0 // 62d25e2326c3 VPTESTNMB 17(SP)(BP*8), Y20, K3, K0 // 62f25e232684ec11000000 VPTESTNMB 17(SP)(BP*4), Y20, K3, K0 // 62f25e232684ac11000000 VPTESTNMB Y11, Y20, K3, K5 // 62d25e2326eb VPTESTNMB 17(SP)(BP*8), Y20, K3, K5 // 62f25e2326acec11000000 VPTESTNMB 17(SP)(BP*4), Y20, K3, K5 // 62f25e2326acac11000000 VPTESTNMB Z18, Z13, K4, K6 // 62b2164c26f2 VPTESTNMB Z8, Z13, K4, K6 // 62d2164c26f0 VPTESTNMB 99(R15)(R15*1), Z13, K4, K6 // 6292164c26b43f63000000 VPTESTNMB (DX), Z13, K4, K6 // 62f2164c2632 VPTESTNMB Z18, Z13, K4, K5 // 62b2164c26ea VPTESTNMB Z8, Z13, K4, K5 // 62d2164c26e8 VPTESTNMB 99(R15)(R15*1), Z13, K4, K5 // 6292164c26ac3f63000000 VPTESTNMB (DX), Z13, K4, K5 // 62f2164c262a VPTESTNMW X7, X3, K1, K5 // 62f2e60926ef VPTESTNMW (CX), X3, K1, K5 // 62f2e6092629 VPTESTNMW 99(R15), X3, K1, K5 // 62d2e60926af63000000 VPTESTNMW X7, X3, K1, K4 // 62f2e60926e7 VPTESTNMW (CX), X3, K1, K4 // 62f2e6092621 VPTESTNMW 99(R15), X3, K1, K4 // 62d2e60926a763000000 VPTESTNMW Y20, Y20, K2, K4 // 62b2de2226e4 VPTESTNMW 7(AX), Y20, K2, K4 // 62f2de2226a007000000 VPTESTNMW (DI), Y20, K2, K4 // 62f2de222627 VPTESTNMW Y20, Y20, K2, K6 // 62b2de2226f4 VPTESTNMW 7(AX), Y20, K2, K6 // 62f2de2226b007000000 VPTESTNMW (DI), Y20, K2, K6 // 62f2de222637 VPTESTNMW Z28, Z12, K1, K1 // 62929e4926cc VPTESTNMW Z13, Z12, K1, K1 // 62d29e4926cd VPTESTNMW 7(SI)(DI*1), Z12, K1, K1 // 62f29e49268c3e07000000 VPTESTNMW 15(DX)(BX*8), Z12, K1, K1 // 62f29e49268cda0f000000 VPTESTNMW Z28, Z16, K1, K1 // 6292fe4126cc VPTESTNMW Z13, Z16, K1, K1 // 62d2fe4126cd VPTESTNMW 7(SI)(DI*1), Z16, K1, K1 // 62f2fe41268c3e07000000 VPTESTNMW 15(DX)(BX*8), Z16, K1, K1 // 62f2fe41268cda0f000000 VPTESTNMW Z28, Z12, K1, K3 // 62929e4926dc VPTESTNMW Z13, Z12, K1, K3 // 62d29e4926dd VPTESTNMW 7(SI)(DI*1), Z12, K1, K3 // 62f29e49269c3e07000000 VPTESTNMW 15(DX)(BX*8), Z12, K1, K3 // 62f29e49269cda0f000000 VPTESTNMW Z28, Z16, K1, K3 // 6292fe4126dc VPTESTNMW Z13, Z16, K1, K3 // 62d2fe4126dd VPTESTNMW 7(SI)(DI*1), Z16, K1, K3 // 62f2fe41269c3e07000000 VPTESTNMW 15(DX)(BX*8), Z16, K1, K3 // 62f2fe41269cda0f000000 VPUNPCKHBW X24, X0, K7, X0 // 62917d0f68c0 or 6291fd0f68c0 VPUNPCKHBW 99(R15)(R15*2), X0, K7, X0 // 62917d0f68847f63000000 or 6291fd0f68847f63000000 VPUNPCKHBW -7(DI), X0, K7, X0 // 62f17d0f6887f9ffffff or 62f1fd0f6887f9ffffff VPUNPCKHBW Y28, Y28, K1, Y9 // 62111d2168cc or 62119d2168cc VPUNPCKHBW 99(R15)(R15*1), Y28, K1, Y9 // 62111d21688c3f63000000 or 62119d21688c3f63000000 VPUNPCKHBW (DX), Y28, K1, Y9 // 62711d21680a or 62719d21680a VPUNPCKHBW Z15, Z3, K1, Z14 // 6251654968f7 or 6251e54968f7 VPUNPCKHBW Z30, Z3, K1, Z14 // 6211654968f6 or 6211e54968f6 VPUNPCKHBW -7(DI)(R8*1), Z3, K1, Z14 // 6231654968b407f9ffffff or 6231e54968b407f9ffffff VPUNPCKHBW (SP), Z3, K1, Z14 // 62716549683424 or 6271e549683424 VPUNPCKHBW Z15, Z12, K1, Z14 // 62511d4968f7 or 62519d4968f7 VPUNPCKHBW Z30, Z12, K1, Z14 // 62111d4968f6 or 62119d4968f6 VPUNPCKHBW -7(DI)(R8*1), Z12, K1, Z14 // 62311d4968b407f9ffffff or 62319d4968b407f9ffffff VPUNPCKHBW (SP), Z12, K1, Z14 // 62711d49683424 or 62719d49683424 VPUNPCKHBW Z15, Z3, K1, Z28 // 6241654968e7 or 6241e54968e7 VPUNPCKHBW Z30, Z3, K1, Z28 // 6201654968e6 or 6201e54968e6 VPUNPCKHBW -7(DI)(R8*1), Z3, K1, Z28 // 6221654968a407f9ffffff or 6221e54968a407f9ffffff VPUNPCKHBW (SP), Z3, K1, Z28 // 62616549682424 or 6261e549682424 VPUNPCKHBW Z15, Z12, K1, Z28 // 62411d4968e7 or 62419d4968e7 VPUNPCKHBW Z30, Z12, K1, Z28 // 62011d4968e6 or 62019d4968e6 VPUNPCKHBW -7(DI)(R8*1), Z12, K1, Z28 // 62211d4968a407f9ffffff or 62219d4968a407f9ffffff VPUNPCKHBW (SP), Z12, K1, Z28 // 62611d49682424 or 62619d49682424 VPUNPCKHWD X21, X3, K4, X31 // 6221650c69fd or 6221e50c69fd VPUNPCKHWD -17(BP), X3, K4, X31 // 6261650c69bdefffffff or 6261e50c69bdefffffff VPUNPCKHWD -15(R14)(R15*8), X3, K4, X31 // 6201650c69bcfef1ffffff or 6201e50c69bcfef1ffffff VPUNPCKHWD Y26, Y6, K5, Y12 // 62114d2d69e2 or 6211cd2d69e2 VPUNPCKHWD 7(SI)(DI*1), Y6, K5, Y12 // 62714d2d69a43e07000000 or 6271cd2d69a43e07000000 VPUNPCKHWD 15(DX)(BX*8), Y6, K5, Y12 // 62714d2d69a4da0f000000 or 6271cd2d69a4da0f000000 VPUNPCKHWD Z0, Z23, K7, Z20 // 62e1454769e0 or 62e1c54769e0 VPUNPCKHWD Z11, Z23, K7, Z20 // 62c1454769e3 or 62c1c54769e3 VPUNPCKHWD (AX), Z23, K7, Z20 // 62e145476920 or 62e1c5476920 VPUNPCKHWD 7(SI), Z23, K7, Z20 // 62e1454769a607000000 or 62e1c54769a607000000 VPUNPCKHWD Z0, Z19, K7, Z20 // 62e1654769e0 or 62e1e54769e0 VPUNPCKHWD Z11, Z19, K7, Z20 // 62c1654769e3 or 62c1e54769e3 VPUNPCKHWD (AX), Z19, K7, Z20 // 62e165476920 or 62e1e5476920 VPUNPCKHWD 7(SI), Z19, K7, Z20 // 62e1654769a607000000 or 62e1e54769a607000000 VPUNPCKHWD Z0, Z23, K7, Z0 // 62f1454769c0 or 62f1c54769c0 VPUNPCKHWD Z11, Z23, K7, Z0 // 62d1454769c3 or 62d1c54769c3 VPUNPCKHWD (AX), Z23, K7, Z0 // 62f145476900 or 62f1c5476900 VPUNPCKHWD 7(SI), Z23, K7, Z0 // 62f14547698607000000 or 62f1c547698607000000 VPUNPCKHWD Z0, Z19, K7, Z0 // 62f1654769c0 or 62f1e54769c0 VPUNPCKHWD Z11, Z19, K7, Z0 // 62d1654769c3 or 62d1e54769c3 VPUNPCKHWD (AX), Z19, K7, Z0 // 62f165476900 or 62f1e5476900 VPUNPCKHWD 7(SI), Z19, K7, Z0 // 62f16547698607000000 or 62f1e547698607000000 VPUNPCKLBW X13, X11, K7, X1 // 62d1250f60cd or 62d1a50f60cd VPUNPCKLBW 17(SP)(BP*2), X11, K7, X1 // 62f1250f608c6c11000000 or 62f1a50f608c6c11000000 VPUNPCKLBW -7(DI)(R8*4), X11, K7, X1 // 62b1250f608c87f9ffffff or 62b1a50f608c87f9ffffff VPUNPCKLBW Y28, Y8, K6, Y3 // 62913d2e60dc or 6291bd2e60dc VPUNPCKLBW -7(DI)(R8*1), Y8, K6, Y3 // 62b13d2e609c07f9ffffff or 62b1bd2e609c07f9ffffff VPUNPCKLBW (SP), Y8, K6, Y3 // 62f13d2e601c24 or 62f1bd2e601c24 VPUNPCKLBW Z0, Z24, K3, Z0 // 62f13d4360c0 or 62f1bd4360c0 VPUNPCKLBW Z26, Z24, K3, Z0 // 62913d4360c2 or 6291bd4360c2 VPUNPCKLBW (BX), Z24, K3, Z0 // 62f13d436003 or 62f1bd436003 VPUNPCKLBW -17(BP)(SI*1), Z24, K3, Z0 // 62f13d43608435efffffff or 62f1bd43608435efffffff VPUNPCKLBW Z0, Z12, K3, Z0 // 62f11d4b60c0 or 62f19d4b60c0 VPUNPCKLBW Z26, Z12, K3, Z0 // 62911d4b60c2 or 62919d4b60c2 VPUNPCKLBW (BX), Z12, K3, Z0 // 62f11d4b6003 or 62f19d4b6003 VPUNPCKLBW -17(BP)(SI*1), Z12, K3, Z0 // 62f11d4b608435efffffff or 62f19d4b608435efffffff VPUNPCKLBW Z0, Z24, K3, Z25 // 62613d4360c8 or 6261bd4360c8 VPUNPCKLBW Z26, Z24, K3, Z25 // 62013d4360ca or 6201bd4360ca VPUNPCKLBW (BX), Z24, K3, Z25 // 62613d43600b or 6261bd43600b VPUNPCKLBW -17(BP)(SI*1), Z24, K3, Z25 // 62613d43608c35efffffff or 6261bd43608c35efffffff VPUNPCKLBW Z0, Z12, K3, Z25 // 62611d4b60c8 or 62619d4b60c8 VPUNPCKLBW Z26, Z12, K3, Z25 // 62011d4b60ca or 62019d4b60ca VPUNPCKLBW (BX), Z12, K3, Z25 // 62611d4b600b or 62619d4b600b VPUNPCKLBW -17(BP)(SI*1), Z12, K3, Z25 // 62611d4b608c35efffffff or 62619d4b608c35efffffff VPUNPCKLWD X8, X8, K3, X19 // 62c13d0b61d8 or 62c1bd0b61d8 VPUNPCKLWD -15(R14)(R15*1), X8, K3, X19 // 62813d0b619c3ef1ffffff or 6281bd0b619c3ef1ffffff VPUNPCKLWD -15(BX), X8, K3, X19 // 62e13d0b619bf1ffffff or 62e1bd0b619bf1ffffff VPUNPCKLWD Y8, Y27, K4, Y22 // 62c1252461f0 or 62c1a52461f0 VPUNPCKLWD (AX), Y27, K4, Y22 // 62e125246130 or 62e1a5246130 VPUNPCKLWD 7(SI), Y27, K4, Y22 // 62e1252461b607000000 or 62e1a52461b607000000 VPUNPCKLWD Z6, Z21, K2, Z31 // 6261554261fe or 6261d54261fe VPUNPCKLWD Z9, Z21, K2, Z31 // 6241554261f9 or 6241d54261f9 VPUNPCKLWD 17(SP)(BP*1), Z21, K2, Z31 // 6261554261bc2c11000000 or 6261d54261bc2c11000000 VPUNPCKLWD -7(CX)(DX*8), Z21, K2, Z31 // 6261554261bcd1f9ffffff or 6261d54261bcd1f9ffffff VPUNPCKLWD Z6, Z9, K2, Z31 // 6261354a61fe or 6261b54a61fe VPUNPCKLWD Z9, Z9, K2, Z31 // 6241354a61f9 or 6241b54a61f9 VPUNPCKLWD 17(SP)(BP*1), Z9, K2, Z31 // 6261354a61bc2c11000000 or 6261b54a61bc2c11000000 VPUNPCKLWD -7(CX)(DX*8), Z9, K2, Z31 // 6261354a61bcd1f9ffffff or 6261b54a61bcd1f9ffffff VPUNPCKLWD Z6, Z21, K2, Z0 // 62f1554261c6 or 62f1d54261c6 VPUNPCKLWD Z9, Z21, K2, Z0 // 62d1554261c1 or 62d1d54261c1 VPUNPCKLWD 17(SP)(BP*1), Z21, K2, Z0 // 62f1554261842c11000000 or 62f1d54261842c11000000 VPUNPCKLWD -7(CX)(DX*8), Z21, K2, Z0 // 62f155426184d1f9ffffff or 62f1d5426184d1f9ffffff VPUNPCKLWD Z6, Z9, K2, Z0 // 62f1354a61c6 or 62f1b54a61c6 VPUNPCKLWD Z9, Z9, K2, Z0 // 62d1354a61c1 or 62d1b54a61c1 VPUNPCKLWD 17(SP)(BP*1), Z9, K2, Z0 // 62f1354a61842c11000000 or 62f1b54a61842c11000000 VPUNPCKLWD -7(CX)(DX*8), Z9, K2, Z0 // 62f1354a6184d1f9ffffff or 62f1b54a6184d1f9ffffff RET
go/src/cmd/asm/internal/asm/testdata/avx512enc/avx512bw.s/0
{ "file_path": "go/src/cmd/asm/internal/asm/testdata/avx512enc/avx512bw.s", "repo_id": "go", "token_count": 113238 }
66
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This contains the majority of valid opcode combinations // available in cmd/internal/obj/ppc64/asm9.go with // their valid instruction encodings. #include "../../../../../runtime/textflag.h" // In case of index mode instructions, usage of // (Rx)(R0) is equivalent to (Rx+R0) // In case of base+displacement mode instructions if // the offset is 0, usage of (Rx) is equivalent to 0(Rx) TEXT asmtest(SB),DUPOK|NOSPLIT,$0 // move constants MOVD $1, R3 // 38600001 MOVD $-1, R4 // 3880ffff MOVD $65535, R5 // 6005ffff MOVD $65536, R6 // 3cc00001 MOVD $-32767, R5 // 38a08001 MOVD $-32768, R6 // 38c08000 MOVD $1234567, R5 // 6405001260a5d687 or 0600001238a0d687 MOVW $1, R3 // 38600001 MOVW $-1, R4 // 3880ffff MOVW $65535, R5 // 6005ffff MOVW $65536, R6 // 3cc00001 MOVW $-32767, R5 // 38a08001 MOVW $-32768, R6 // 38c08000 MOVW $1234567, R5 // 6405001260a5d687 or 0600001238a0d687 // Hex constant 0x80000001 MOVW $2147483649, R5 // 6405800060a50001 or 0600800038a00001 MOVD $2147483649, R5 // 6405800060a50001 or 0600800038a00001 // Hex constant 0xFFFFFFFF80000001 MOVD $-2147483647, R5 // 3ca0800060a50001 or 0603800038a00001 // Hex constant 0xFFFFFFFE00000002 (load of constant on < power10, pli on >= power10 MOVD $-8589934590, R5 // 3ca00000e8a50000 or 0602000038a00002 // For backwards compatibility, MOVW $const,Rx and MOVWZ $const,Rx assemble identically // and accept the same constants. MOVW $2147483648, R5 // 64058000 MOVWZ $-2147483648, R5 // 3ca08000 // TODO: These are preprocessed by the assembler into MOVD $const>>shift, R5; SLD $shift, R5. // This only captures the MOVD. Should the SLD be appended to the encoding by the test? // Hex constant 0x20004000000 MOVD $2199090364416, R5 // 60058001 // Hex constant 0xFFFFFE0004000000 MOVD $-2198956146688, R5 // 38a08001 // TODO: On GOPPC64={power8,power9}, this is preprocessed into MOVD $-1, R5; RLDC R5, $33, $63, R5. // This only captures the MOVD. Should the RLDC be appended to the encoding by the test? // Hex constant 0xFFFFFFFE00000001 MOVD $-8589934591, R5 // 38a0ffff or 0602000038a00001 // For #66955. Verify this opcode turns into a load and assembles. MOVD $-6795364578871345152, R5 // 3ca00000e8a50000 or 04100000e4a00000 MOVD 8(R3), R4 // e8830008 MOVD (R3)(R4), R5 // 7ca4182a MOVD (R3)(R0), R5 // 7ca0182a MOVD (R3), R5 // e8a30000 MOVW 4(R3), R4 // e8830006 MOVW (R3)(R4), R5 // 7ca41aaa MOVW (R3)(R0), R5 // 7ca01aaa MOVW (R3), R5 // e8a30002 MOVWZ 4(R3), R4 // 80830004 MOVWZ (R3)(R4), R5 // 7ca4182e MOVWZ (R3)(R0), R5 // 7ca0182e MOVWZ (R3), R5 // 80a30000 MOVH 4(R3), R4 // a8830004 MOVH (R3)(R4), R5 // 7ca41aae MOVH (R3)(R0), R5 // 7ca01aae MOVH (R3), R5 // a8a30000 MOVHZ 2(R3), R4 // a0830002 MOVHZ (R3)(R4), R5 // 7ca41a2e MOVHZ (R3)(R0), R5 // 7ca01a2e MOVHZ (R3), R5 // a0a30000 MOVB 1(R3), R4 // 888300017c840774 MOVB (R3)(R4), R5 // 7ca418ae7ca50774 MOVB (R3)(R0), R5 // 7ca018ae7ca50774 MOVB (R3), R5 // 88a300007ca50774 MOVBZ 1(R3), R4 // 88830001 MOVBZ (R3)(R4), R5 // 7ca418ae MOVBZ (R3)(R0), R5 // 7ca018ae MOVBZ (R3), R5 // 88a30000 MOVDBR (R3)(R4), R5 // 7ca41c28 MOVDBR (R3)(R0), R5 // 7ca01c28 MOVDBR (R3), R5 // 7ca01c28 MOVWBR (R3)(R4), R5 // 7ca41c2c MOVWBR (R3)(R0), R5 // 7ca01c2c MOVWBR (R3), R5 // 7ca01c2c MOVHBR (R3)(R4), R5 // 7ca41e2c MOVHBR (R3)(R0), R5 // 7ca01e2c MOVHBR (R3), R5 // 7ca01e2c OR $0, R0, R0 MOVD $foo+4009806848(FP), R5 // 3ca1ef0138a5cc40 or 0600ef0038a1cc40 MOVD $foo(SB), R5 // 3ca0000038a50000 or 0610000038a00000 MOVDU 8(R3), R4 // e8830009 MOVDU (R3)(R4), R5 // 7ca4186a MOVDU (R3)(R0), R5 // 7ca0186a MOVDU (R3), R5 // e8a30001 MOVWU (R3)(R4), R5 // 7ca41aea MOVWU (R3)(R0), R5 // 7ca01aea MOVWZU 4(R3), R4 // 84830004 MOVWZU (R3)(R4), R5 // 7ca4186e MOVWZU (R3)(R0), R5 // 7ca0186e MOVWZU (R3), R5 // 84a30000 MOVHU 2(R3), R4 // ac830002 MOVHU (R3)(R4), R5 // 7ca41aee MOVHU (R3)(R0), R5 // 7ca01aee MOVHU (R3), R5 // aca30000 MOVHZU 2(R3), R4 // a4830002 MOVHZU (R3)(R4), R5 // 7ca41a6e MOVHZU (R3)(R0), R5 // 7ca01a6e MOVHZU (R3), R5 // a4a30000 MOVBU 1(R3), R4 // 8c8300017c840774 MOVBU (R3)(R4), R5 // 7ca418ee7ca50774 MOVBU (R3)(R0), R5 // 7ca018ee7ca50774 MOVBU (R3), R5 // 8ca300007ca50774 MOVBZU 1(R3), R4 // 8c830001 MOVBZU (R3)(R4), R5 // 7ca418ee MOVBZU (R3)(R0), R5 // 7ca018ee MOVBZU (R3), R5 // 8ca30000 MOVD R4, 8(R3) // f8830008 MOVD R5, (R3)(R4) // 7ca4192a MOVD R5, (R3)(R0) // 7ca0192a MOVD R5, (R3) // f8a30000 MOVW R4, 4(R3) // 90830004 MOVW R5, (R3)(R4) // 7ca4192e MOVW R5, (R3)(R0) // 7ca0192e MOVW R5, (R3) // 90a30000 MOVH R4, 2(R3) // b0830002 MOVH R5, (R3)(R4) // 7ca41b2e MOVH R5, (R3)(R0) // 7ca01b2e MOVH R5, (R3) // b0a30000 MOVB R4, 1(R3) // 98830001 MOVB R5, (R3)(R4) // 7ca419ae MOVB R5, (R3)(R0) // 7ca019ae MOVB R5, (R3) // 98a30000 MOVDBR R5, (R3)(R4) // 7ca41d28 MOVDBR R5, (R3)(R0) // 7ca01d28 MOVDBR R5, (R3) // 7ca01d28 MOVWBR R5, (R3)(R4) // 7ca41d2c MOVWBR R5, (R3)(R0) // 7ca01d2c MOVWBR R5, (R3) // 7ca01d2c MOVHBR R5, (R3)(R4) // 7ca41f2c MOVHBR R5, (R3)(R0) // 7ca01f2c MOVHBR R5, (R3) // 7ca01f2c MOVDU R4, 8(R3) // f8830009 MOVDU R5, (R3)(R4) // 7ca4196a MOVDU R5, (R3)(R0) // 7ca0196a MOVDU R5, (R3) // f8a30001 MOVWU R4, 4(R3) // 94830004 MOVWU R5, (R3)(R4) // 7ca4196e MOVWU R5, (R3)(R0) // 7ca0196e MOVHU R4, 2(R3) // b4830002 MOVHU R5, (R3)(R4) // 7ca41b6e MOVHU R5, (R3)(R0) // 7ca01b6e MOVHU R5, (R3) // b4a30000 MOVBU R4, 1(R3) // 9c830001 MOVBU R5, (R3)(R4) // 7ca419ee MOVBU R5, (R3)(R0) // 7ca019ee MOVBU R5, (R3) // 9ca30000 MOVB $0, R4 // 38800000 MOVBZ $0, R4 // 38800000 MOVH $0, R4 // 38800000 MOVHZ $0, R4 // 38800000 MOVW $0, R4 // 38800000 MOVWZ $0, R4 // 38800000 MOVD $0, R4 // 38800000 MOVD $0, R0 // 38000000 ADD $1, R3 // 38630001 ADD $1, R3, R4 // 38830001 ADD $-1, R4 // 3884ffff ADD $-1, R4, R5 // 38a4ffff ADD $65535, R5 // 601fffff7cbf2a14 or 0600000038a5ffff ADD $65535, R5, R6 // 601fffff7cdf2a14 or 0600000038c5ffff ADD $65536, R6 // 3cc60001 ADD $65536, R6, R7 // 3ce60001 ADD $-32767, R5 // 38a58001 ADD $-32767, R5, R4 // 38858001 ADD $-32768, R6 // 38c68000 ADD $-32768, R6, R5 // 38a68000 // Hex constant 0xFFFFFFFE00000000 ADD $-8589934592, R5 // 3fe0fffe600000007bff83e4600000007cbf2a14 or 0602000038a50000 // Hex constant 0xFFFFFFFE00010001 ADD $-8589869055, R5 // 3fe0fffe63ff00017bff83e463ff00017cbf2a14 or 0602000138a50001 //TODO: this compiles to add r5,r6,r0. It should be addi r5,r6,0. // this is OK since r0 == $0, but the latter is preferred. ADD $0, R6, R5 // 7ca60214 //TODO: the assembler rewrites these into ADDIS $19, R5, Rx and ADD $-10617, Rx, Rx, but the test only sees the first ADDIS ADD $1234567, R5 // 3ca50013 or 0600001238a5d687 ADD $1234567, R5, R6 // 3cc50013 or 0600001238c5d687 ADDEX R3, R5, $3, R6 // 7cc32f54 ADDEX R3, $3, R5, R6 // 7cc32f54 ADDIS $8, R3 // 3c630008 ADD $524288, R3 // 3c630008 ADDIS $1000, R3, R4 // 3c8303e8 ANDCC $1, R3 // 70630001 ANDCC $1, R3, R4 // 70640001 ANDCC $-1, R4 // 3be0ffff7fe42039 ANDCC $-1, R4, R5 // 3be0ffff7fe52039 ANDCC $65535, R5 // 70a5ffff ANDCC $65535, R5, R6 // 70a6ffff ANDCC $65536, R6 // 74c60001 ANDCC $65536, R6, R7 // 74c70001 ANDCC $-32767, R5 // 3be080017fe52839 ANDCC $-32767, R5, R4 // 3be080017fe42839 ANDCC $-32768, R6 // 3be080007fe63039 ANDCC $-32768, R5, R6 // 3be080007fe62839 ANDCC $1234567, R5 // 641f001263ffd6877fe52839 ANDCC $1234567, R5, R6 // 641f001263ffd6877fe62839 ANDISCC $1, R3 // 74630001 ANDISCC $1000, R3, R4 // 746403e8 ANDCC $65536000, R3, R4 // 746403e8 OR $1, R3 // 60630001 OR $1, R3, R4 // 60640001 OR $-1, R4 // 3be0ffff7fe42378 OR $-1, R4, R5 // 3be0ffff7fe52378 OR $65535, R5 // 60a5ffff OR $65535, R5, R6 // 60a6ffff OR $65536, R6 // 64c60001 OR $65536, R6, R7 // 64c70001 OR $-32767, R5 // 3be080017fe52b78 OR $-32767, R5, R6 // 3be080017fe62b78 OR $-32768, R6 // 3be080007fe63378 OR $-32768, R6, R7 // 3be080007fe73378 OR $1234567, R5 // 64a5001260a5d687 OR $1234567, R5, R3 // 64a300126063d687 OR $2147483648, R5, R3 // 64a38000 OR $2147483649, R5, R3 // 64a3800060630001 ORIS $255, R3, R4 // 646400ff OR $16711680, R3, R4 // 646400ff XOR $1, R3 // 68630001 XOR $1, R3, R4 // 68640001 XOR $-1, R4 // 3be0ffff7fe42278 XOR $-1, R4, R5 // 3be0ffff7fe52278 XOR $65535, R5 // 68a5ffff XOR $65535, R5, R6 // 68a6ffff XOR $65536, R6 // 6cc60001 XOR $65536, R6, R7 // 6cc70001 XOR $-32767, R5 // 3be080017fe52a78 XOR $-32767, R5, R6 // 3be080017fe62a78 XOR $-32768, R6 // 3be080007fe63278 XOR $-32768, R6, R7 // 3be080007fe73278 XOR $1234567, R5 // 6ca5001268a5d687 XOR $1234567, R5, R3 // 6ca300126863d687 XORIS $15, R3, R4 // 6c64000f XOR $983040, R3, R4 // 6c64000f // TODO: cleanup inconsistency of printing CMPx opcodes with explicit CR arguments. CMP R3, R4 // 7c232000 CMP R3, R0 // 7c230000 CMP R3, R0, CR1 // CMP R3,CR1,R0 // 7ca30000 CMPU R3, R4 // 7c232040 CMPU R3, R0 // 7c230040 CMPU R3, R0, CR2 // CMPU R3,CR2,R0 // 7d230040 CMPW R3, R4 // 7c032000 CMPW R3, R0 // 7c030000 CMPW R3, R0, CR3 // CMPW R3,CR3,R0 // 7d830000 CMPWU R3, R4 // 7c032040 CMPWU R3, R0 // 7c030040 CMPWU R3, R0, CR4 // CMPWU R3,CR4,R0 // 7e030040 CMP R3, $0 // 2c230000 CMPU R3, $0 // 28230000 CMPW R3, $0 // 2c030000 CMPWU R3, $0 // 28030000 CMP R3, $0, CR0 // CMP R3,CR0,$0 // 2c230000 CMPU R3, $0, CR1 // CMPU R3,CR1,$0 // 28a30000 CMPW R3, $0, CR2 // CMPW R3,CR2,$0 // 2d030000 CMPW R3, $-32768, CR2 // CMPW R3,CR2,$-32768 // 2d038000 CMPWU R3, $0, CR3 // CMPWU R3,CR3,$0 // 29830000 CMPWU R3, $0x8008, CR3 // CMPWU R3,CR3,$32776 // 29838008 CMPEQB R3,R4,CR6 // 7f0321c0 CMPB R3,R4,R4 // 7c6423f8 ADD R3, R4 // 7c841a14 ADD R3, R4, R5 // 7ca41a14 ADDC R3, R4 // 7c841814 ADDC R3, R4, R5 // 7ca41814 ADDCC R3, R4, R5 // 7ca41a15 ADDE R3, R4 // 7c841914 ADDECC R3, R4 // 7c841915 ADDEV R3, R4 // 7c841d14 ADDEVCC R3, R4 // 7c841d15 ADDV R3, R4 // 7c841e14 ADDVCC R3, R4 // 7c841e15 ADDCCC R3, R4, R5 // 7ca41815 ADDCCC $65536, R4, R5 // 641f0001600000007cbf2015 ADDCCC $65537, R4, R5 // 641f000163ff00017cbf2015 ADDME R3, R4 // 7c8301d4 ADDMECC R3, R4 // 7c8301d5 ADDMEV R3, R4 // 7c8305d4 ADDMEVCC R3, R4 // 7c8305d5 ADDCV R3, R4 // 7c841c14 ADDCVCC R3, R4 // 7c841c15 ADDZE R3, R4 // 7c830194 ADDZECC R3, R4 // 7c830195 ADDZEV R3, R4 // 7c830594 ADDZEVCC R3, R4 // 7c830595 SUBME R3, R4 // 7c8301d0 SUBMECC R3, R4 // 7c8301d1 SUBMEV R3, R4 // 7c8305d0 SUBZE R3, R4 // 7c830190 SUBZECC R3, R4 // 7c830191 SUBZEV R3, R4 // 7c830590 SUBZEVCC R3, R4 // 7c830591 AND R3, R4 // 7c841838 AND R3, R4, R5 // 7c851838 ANDN R3, R4, R5 // 7c851878 ANDCC R3, R4, R5 // 7c851839 ANDNCC R3, R4, R5 // 7c851879 OR R3, R4 // 7c841b78 OR R3, R4, R5 // 7c851b78 ORN R3, R4, R5 // 7c851b38 ORCC R3, R4, R5 // 7c851b79 ORNCC R3, R4, R5 // 7c851b39 XOR R3, R4 // 7c841a78 XOR R3, R4, R5 // 7c851a78 XORCC R3, R4, R5 // 7c851a79 NAND R3, R4, R5 // 7c851bb8 NANDCC R3, R4, R5 // 7c851bb9 EQV R3, R4, R5 // 7c851a38 EQVCC R3, R4, R5 // 7c851a39 NOR R3, R4, R5 // 7c8518f8 NORCC R3, R4, R5 // 7c8518f9 SUB R3, R4 // 7c832050 SUB R3, R4, R5 // 7ca32050 SUBC R3, R4 // 7c832010 SUBC R3, R4, R5 // 7ca32010 SUBCC R3, R4, R5 // 7ca32051 SUBVCC R3, R4, R5 // 7ca32451 SUBCCC R3, R4, R5 // 7ca32011 SUBCV R3, R4, R5 // 7ca32410 SUBCVCC R3, R4, R5 // 7ca32411 SUBMEVCC R3, R4 // 7c8305d1 SUBV R3, R4, R5 // 7ca32450 SUBE R3, R4, R5 // 7ca32110 SUBECC R3, R4, R5 // 7ca32111 SUBEV R3, R4, R5 // 7ca32510 SUBEVCC R3, R4, R5 // 7ca32511 SUBC R3, $65536, R4 // 3fe00001600000007c83f810 SUBC R3, $65537, R4 // 3fe0000163ff00017c83f810 MULLW R3, R4 // 7c8419d6 MULLW R3, R4, R5 // 7ca419d6 MULLW $10, R3 // 1c63000a MULLW $10000000, R3 // 641f009863ff96807c7f19d6 MULLWCC R3, R4, R5 // 7ca419d7 MULHW R3, R4, R5 // 7ca41896 MULHWU R3, R4, R5 // 7ca41816 MULLD R3, R4 // 7c8419d2 MULLD R4, R4, R5 // 7ca421d2 MULLD $20, R4 // 1c840014 MULLD $200000000, R4 // 641f0beb63ffc2007c9f21d2 MULLDCC R3, R4, R5 // 7ca419d3 MULHD R3, R4, R5 // 7ca41892 MULHDCC R3, R4, R5 // 7ca41893 MULHDU R3, R4, R5 // 7ca41812 MULHDUCC R3, R4, R5 // 7ca41813 MULLWV R3, R4 // 7c841dd6 MULLWV R3, R4, R5 // 7ca41dd6 MULLWVCC R3, R4, R5 // 7ca41dd7 MULHWUCC R3, R4, R5 // 7ca41817 MULLDV R3, R4, R5 // 7ca41dd2 MULLDVCC R3, R4, R5 // 7ca41dd3 DIVD R3,R4 // 7c841bd2 DIVD R3, R4, R5 // 7ca41bd2 DIVW R3, R4 // 7c841bd6 DIVW R3, R4, R5 // 7ca41bd6 DIVDCC R3,R4, R5 // 7ca41bd3 DIVWCC R3,R4, R5 // 7ca41bd7 DIVDU R3, R4, R5 // 7ca41b92 DIVWU R3, R4, R5 // 7ca41b96 DIVDV R3, R4, R5 // 7ca41fd2 DIVWV R3, R4, R5 // 7ca41fd6 DIVDUCC R3, R4, R5 // 7ca41b93 DIVWUCC R3, R4, R5 // 7ca41b97 DIVDVCC R3, R4, R5 // 7ca41fd3 DIVWVCC R3, R4, R5 // 7ca41fd7 DIVDUV R3, R4, R5 // 7ca41f92 DIVDUVCC R3, R4, R5 // 7ca41f93 DIVWUVCC R3, R4, R5 // 7ca41f97 DIVWUV R3, R4, R5 // 7ca41f96 DIVDE R3, R4, R5 // 7ca41b52 DIVDECC R3, R4, R5 // 7ca41b53 DIVDEU R3, R4, R5 // 7ca41b12 DIVDEUCC R3, R4, R5 // 7ca41b13 REM R3, R4, R5 // 7fe41bd67fff19d67cbf2050 REMU R3, R4, R5 // 7fe41b967fff19d67bff00287cbf2050 REMD R3, R4, R5 // 7fe41bd27fff19d27cbf2050 REMDU R3, R4, R5 // 7fe41b927fff19d27cbf2050 MADDHD R3,R4,R5,R6 // 10c32170 MADDHDU R3,R4,R5,R6 // 10c32171 MODUD R3, R4, R5 // 7ca41a12 MODUW R3, R4, R5 // 7ca41a16 MODSD R3, R4, R5 // 7ca41e12 MODSW R3, R4, R5 // 7ca41e16 SLW $8, R3, R4 // 5464402e SLW R3, R4, R5 // 7c851830 SLWCC R3, R4 // 7c841831 SLD $16, R3, R4 // 786483e4 SLD R3, R4, R5 // 7c851836 SLDCC R3, R4 // 7c841837 SRW $8, R3, R4 // 5464c23e SRW R3, R4, R5 // 7c851c30 SRWCC R3, R4 // 7c841c31 SRAW $8, R3, R4 // 7c644670 SRAW R3, R4, R5 // 7c851e30 SRAWCC R3, R4 // 7c841e31 SRD $16, R3, R4 // 78648402 SRD R3, R4, R5 // 7c851c36 SRDCC R3, R4 // 7c841c37 SRAD $16, R3, R4 // 7c648674 SRAD R3, R4, R5 // 7c851e34 SRDCC R3, R4 // 7c841c37 ROTLW $16, R3, R4 // 5464803e ROTLW R3, R4, R5 // 5c85183e ROTL $16, R3, R4 // 78648000 EXTSWSLI $3, R4, R5 // 7c851ef4 EXTSWSLICC $16, R3, R4 // 7c6486f5 EXTSB R3, R4 // 7c640774 EXTSBCC R3, R4 // 7c640775 EXTSH R3, R4 // 7c640734 EXTSHCC R3, R4 // 7c640735 EXTSW R3, R4 // 7c6407b4 EXTSWCC R3, R4 // 7c6407b5 RLWMI $7, R3, $4026531855, R6 // 50663f06 RLWMI $7, R3, $1, R6 // 50663ffe RLWMI $7, R3, $2147483648, R6 // 50663800 RLWMI $7, R3, $65535, R6 // 50663c3e RLWMI $7, R3, $16, $31, R6 // 50663c3e RLWMICC $7, R3, $65535, R6 // 50663c3f RLWMICC $7, R3, $16, $31, R6 // 50663c3f RLWNM $3, R4, $7, R6 // 54861f7e RLWNM $0, R4, $7, R6 // 5486077e RLWNM R0, R4, $7, R6 // 5c86077e RLWNM $3, R4, $29, $31, R6 // 54861f7e RLWNM $0, R4, $29, $31, R6 // 5486077e RLWNM R0, R4, $29, $31, R6 // 5c86077e RLWNM R3, R4, $7, R6 // 5c861f7e RLWNM R3, R4, $29, $31, R6 // 5c861f7e RLWNMCC $3, R4, $7, R6 // 54861f7f RLWNMCC $3, R4, $29, $31, R6 // 54861f7f RLWNMCC R3, R4, $7, R6 // 5c861f7f RLWNMCC R3, R4, $29, $31, R6 // 5c861f7f RLDMI $0, R4, $7, R6 // 7886076c RLDMICC $0, R4, $7, R6 // 7886076d RLDIMI $0, R4, $7, R6 // 788601cc RLDIMICC $0, R4, $7, R6 // 788601cd RLDC $0, R4, $15, R6 // 78860728 RLDC R3, $32, $12, R4 // 7864030a RLDC R3, $8, $32, R4 // 78644028 RLDCCC R3, $32, $12, R4 // 7864030b RLDCCC R3, $8, $32, R4 // 78644029 RLDCCC $0, R4, $15, R6 // 78860729 RLDCL $0, R4, $7, R6 // 78860770 RLDCLCC $0, R4, $15, R6 // 78860721 RLDCR $0, R4, $-16, R6 // 788606f2 RLDCRCC $0, R4, $-16, R6 // 788606f3 RLDICL $0, R4, $15, R6 // 788603c0 RLDICLCC $0, R4, $15, R6 // 788603c1 RLDICR $0, R4, $15, R6 // 788603c4 RLDICRCC $0, R4, $15, R6 // 788603c5 RLDIC $0, R4, $15, R6 // 788603c8 RLDICCC $0, R4, $15, R6 // 788603c9 CLRLSLWI $16, R5, $8, R4 // 54a4422e CLRLSLDI $24, R4, $2, R3 // 78831588 RLDCR $1, R1, $-16, R1 // 78210ee4 RLDCRCC $1, R1, $-16, R1 // 78210ee5 CNTLZW R3,R4 // 7c640034 CNTLZWCC R3,R4 // 7c640035 CNTLZD R3, R4 // 7c640074 CNTLZDCC R3, R4 // 7c640075 CNTTZW R3,R4 // 7c640434 CNTTZWCC R3,R4 // 7c640435 CNTTZD R3,R4 // 7c640474 CNTTZDCC R3,R4 // 7c640475 NEG R3, R4 // 7c8300d0 NEGCC R3, R4 // 7c8300d1 NEGV R3, R4 // 7c8304d0 NEGVCC R3, R4 // 7c8304d1 BEQ 0(PC) // 41820000 BEQ CR1,0(PC) // 41860000 BGE 0(PC) // 40800000 BGE CR2,0(PC) // 40880000 BGT 4(PC) // 41810010 BGT CR3,4(PC) // 418d0010 BLE 0(PC) // 40810000 BLE CR4,0(PC) // 40910000 BLT 0(PC) // 41800000 BLT CR5,0(PC) // 41940000 BNE 0(PC) // 40820000 BLT CR6,0(PC) // 41980000 BVC 0(PC) // 40830000 BVS 0(PC) // 41830000 JMP 8(PC) // 48000010 NOP NOP R2 NOP F2 NOP $4 CRAND CR0GT, CR0EQ, CR0SO // 4c620a02 CRANDN CR0GT, CR0EQ, CR0SO // 4c620902 CREQV CR0GT, CR0EQ, CR0SO // 4c620a42 CRNAND CR0GT, CR0EQ, CR0SO // 4c6209c2 CRNOR CR0GT, CR0EQ, CR0SO // 4c620842 CROR CR0GT, CR0EQ, CR0SO // 4c620b82 CRORN CR0GT, CR0EQ, CR0SO // 4c620b42 CRXOR CR0GT, CR0EQ, CR0SO // 4c620982 ISEL $0, R3, R4, R5 // 7ca3201e ISEL $1, R3, R4, R5 // 7ca3205e ISEL $2, R3, R4, R5 // 7ca3209e ISEL $3, R3, R4, R5 // 7ca320de ISEL $4, R3, R4, R5 // 7ca3211e ISEL $31, R3, R4, R5 // 7ca327de ISEL CR0LT, R3, R4, R5 // 7ca3201e ISEL CR0GT, R3, R4, R5 // 7ca3205e ISEL CR0EQ, R3, R4, R5 // 7ca3209e ISEL CR0SO, R3, R4, R5 // 7ca320de ISEL CR1LT, R3, R4, R5 // 7ca3211e ISEL CR7SO, R3, R4, R5 // 7ca327de POPCNTB R3, R4 // 7c6400f4 POPCNTW R3, R4 // 7c6402f4 POPCNTD R3, R4 // 7c6403f4 PASTECC R3, R4 // 7c23270d COPY R3, R4 // 7c23260c // load-and-reserve LBAR (R4)(R3*1),$1,R5 // 7ca32069 LBAR (R4)(R0),$1,R5 // 7ca02069 LBAR (R4),$0,R5 // 7ca02068 LBAR (R3),R5 // 7ca01868 LHAR (R4)(R3*1),$1,R5 // 7ca320e9 LHAR (R4)(R0),$1,R5 // 7ca020e9 LHAR (R4),$0,R5 // 7ca020e8 LHAR (R3),R5 // 7ca018e8 LWAR (R4)(R3*1),$1,R5 // 7ca32029 LWAR (R4)(R0),$1,R5 // 7ca02029 LWAR (R4),$0,R5 // 7ca02028 LWAR (R3),R5 // 7ca01828 LDAR (R4)(R3*1),$1,R5 // 7ca320a9 LDAR (R4)(R0),$1,R5 // 7ca020a9 LDAR (R4),$0,R5 // 7ca020a8 LDAR (R3),R5 // 7ca018a8 LSW (R3)(R4), R5 // 7ca41c2a LSW (R3)(R0), R5 // 7ca01c2a LSW (R3), R5 // 7ca01c2a STBCCC R3, (R4)(R5) // 7c65256d STBCCC R3, (R4)(R0) // 7c60256d STBCCC R3, (R4) // 7c60256d STWCCC R3, (R4)(R5) // 7c65212d STWCCC R3, (R4)(R0) // 7c60212d STWCCC R3, (R4) // 7c60212d STDCCC R3, (R4)(R5) // 7c6521ad STDCCC R3, (R4)(R0) // 7c6021ad STDCCC R3, (R4) // 7c6021ad STHCCC R3, (R4)(R5) // 7c6525ad STHCCC R3, (R4)(R0) // 7c6025ad STHCCC R3, (R4) // 7c6025ad STSW R3, (R4)(R5) // 7c65252a STSW R3, (R4)(R0) // 7c60252a STSW R3, (R4) // 7c60252a SYNC // 7c0004ac ISYNC // 4c00012c LWSYNC // 7c2004ac EIEIO // 7c0006ac PTESYNC // 7c4004ac TLBIE R3 // 7c001a64 TLBIEL R3 // 7c001a24 TLBSYNC // 7c00046c HRFID // 4c000224 SLBIA // 7c0003e4 SLBIE R3 // 7c001b64 SLBMFEE R3, R4 // 7c801f26 SLBMFEV R3, R4 // 7c801ea6 SLBMTE R3, R4 // 7c801b24 TW $31, R0, R0 // 7fe00008 TD $31, R0, R0 // 7fe00088 DARN $1, R5 // 7ca105e6 DCBF (R3)(R4) // 7c0418ac DCBF (R3)(R0) // 7c0018ac DCBF (R3) // 7c0018ac DCBST (R3)(R4) // 7c04186c DCBST (R3)(R0) // 7c00186c DCBST (R3) // 7c00186c DCBZ (R3)(R4) // 7c041fec DCBZ (R3)(R0) // 7c001fec DCBZ (R3) // 7c001fec DCBT (R3)(R4) // 7c041a2c DCBT (R3)(R0) // 7c001a2c DCBT (R3) // 7c001a2c ICBI (R3)(R4) // 7c041fac ICBI (R3)(R0) // 7c001fac ICBI (R3) // 7c001fac // float constants FMOVD $(0.0), F1 // f0210cd0 FMOVD $(-0.0), F1 // f0210cd0fc200850 FMOVD 8(R3), F1 // c8230008 FMOVD (R3)(R4), F1 // 7c241cae FMOVD (R3)(R0), F1 // 7c201cae FMOVD (R3), F1 // c8230000 FMOVDU 8(R3), F1 // cc230008 FMOVDU (R3)(R4), F1 // 7c241cee FMOVDU (R3)(R0), F1 // 7c201cee FMOVDU (R3), F1 // cc230000 FMOVS 4(R3), F1 // c0230004 FMOVS (R3)(R4), F1 // 7c241c2e FMOVS (R3)(R0), F1 // 7c201c2e FMOVS (R3), F1 // c0230000 FMOVSU 4(R3), F1 // c4230004 FMOVSU (R3)(R4), F1 // 7c241c6e FMOVSU (R3)(R0), F1 // 7c201c6e FMOVSU (R3), F1 // c4230000 FMOVSX (R3)(R4), F1 // 7c241eae FMOVSX (R3)(R0), F1 // 7c201eae FMOVSX (R3), F1 // 7c201eae FMOVSZ (R3)(R4), F1 // 7c241eee FMOVSZ (R3)(R0), F1 // 7c201eee FMOVSZ (R3), F1 // 7c201eee FMOVD F1, 8(R3) // d8230008 FMOVD F1, (R3)(R4) // 7c241dae FMOVD F1, (R3)(R0) // 7c201dae FMOVD F1, (R3) // d8230000 FMOVDU F1, 8(R3) // dc230008 FMOVDU F1, (R3)(R4) // 7c241dee FMOVDU F1, (R3)(R0) // 7c201dee FMOVDU F1, (R3) // dc230000 FMOVS F1, 4(R3) // d0230004 FMOVS F1, (R3)(R4) // 7c241d2e FMOVS F1, (R3)(R0) // 7c201d2e FMOVS F1, (R3) // d0230000 FMOVSU F1, 4(R3) // d4230004 FMOVSU F1, (R3)(R4) // 7c241d6e FMOVSU F1, (R3)(R0) // 7c201d6e FMOVSU F1, (R3) // d4230000 FMOVSX F1, (R3)(R4) // 7c241fae FMOVSX F1, (R3)(R0) // 7c201fae FMOVSX F1, (R3) // 7c201fae FADD F1, F2 // fc42082a FADD F1, F2, F3 // fc62082a FADDCC F1, F2, F3 // fc62082b FMOVDCC F1, F2 // fc400891 FADDS F1, F2 // ec42082a FADDS F1, F2, F3 // ec62082a FADDSCC F1, F2, F3 // ec62082b FSUB F1, F2 // fc420828 FSUB F1, F2, F3 // fc620828 FSUBCC F1, F2, F3 // fc620829 FSUBS F1, F2 // ec420828 FSUBS F1, F2, F3 // ec620828 FSUBCC F1, F2, F3 // fc620829 FSUBSCC F1, F2, F3 // ec620829 FMUL F1, F2 // fc420072 FMUL F1, F2, F3 // fc620072 FMULCC F1, F2, F3 // fc620073 FMULS F1, F2 // ec420072 FMULS F1, F2, F3 // ec620072 FMULSCC F1, F2, F3 // ec620073 FDIV F1, F2 // fc420824 FDIV F1, F2, F3 // fc620824 FDIVCC F1, F2, F3 // fc620825 FDIVS F1, F2 // ec420824 FDIVS F1, F2, F3 // ec620824 FDIVSCC F1, F2, F3 // ec620825 FTDIV F1, F2, $2 // fd011100 FTSQRT F1, $2 // fd000940 FMADD F1, F2, F3, F4 // fc8110fa FMADDCC F1, F2, F3, F4 // fc8110fb FMADDS F1, F2, F3, F4 // ec8110fa FMADDSCC F1, F2, F3, F4 // ec8110fb FMSUB F1, F2, F3, F4 // fc8110f8 FMSUBCC F1, F2, F3, F4 // fc8110f9 FMSUBS F1, F2, F3, F4 // ec8110f8 FMSUBSCC F1, F2, F3, F4 // ec8110f9 FNMADD F1, F2, F3, F4 // fc8110fe FNMADDCC F1, F2, F3, F4 // fc8110ff FNMADDS F1, F2, F3, F4 // ec8110fe FNMADDSCC F1, F2, F3, F4 // ec8110ff FNMSUB F1, F2, F3, F4 // fc8110fc FNMSUBCC F1, F2, F3, F4 // fc8110fd FNMSUBS F1, F2, F3, F4 // ec8110fc FNMSUBSCC F1, F2, F3, F4 // ec8110fd FSEL F1, F2, F3, F4 // fc8110ee FSELCC F1, F2, F3, F4 // fc8110ef FABS F1, F2 // fc400a10 FNABS F1, F2 // fc400910 FABSCC F1, F2 // fc400a11 FNABSCC F1, F2 // fc400911 FNEG F1, F2 // fc400850 FNEGCC F1, F2 // fc400851 FABSCC F1, F2 // fc400a11 FRSP F1, F2 // fc400818 FRSPCC F1, F2 // fc400819 FCTIW F1, F2 // fc40081c FCTIWCC F1, F2 // fc40081d FCTIWZ F1, F2 // fc40081e FCTIWZCC F1, F2 // fc40081f FCTID F1, F2 // fc400e5c FCTIDCC F1, F2 // fc400e5d FCTIDZ F1, F2 // fc400e5e FCTIDZCC F1, F2 // fc400e5f FCFID F1, F2 // fc400e9c FCFIDCC F1, F2 // fc400e9d FCFIDU F1, F2 // fc400f9c FCFIDUCC F1, F2 // fc400f9d FCFIDS F1, F2 // ec400e9c FCFIDSCC F1, F2 // ec400e9d FRES F1, F2 // ec400830 FRESCC F1, F2 // ec400831 FRIM F1, F2 // fc400bd0 FRIMCC F1, F2 // fc400bd1 FRIP F1, F2 // fc400b90 FRIPCC F1, F2 // fc400b91 FRIZ F1, F2 // fc400b50 FRIZCC F1, F2 // fc400b51 FRIN F1, F2 // fc400b10 FRINCC F1, F2 // fc400b11 FRSQRTE F1, F2 // fc400834 FRSQRTECC F1, F2 // fc400835 FSQRT F1, F2 // fc40082c FSQRTCC F1, F2 // fc40082d FSQRTS F1, F2 // ec40082c FSQRTSCC F1, F2 // ec40082d FCPSGN F1, F2 // fc420810 FCPSGNCC F1, F2 // fc420811 FCMPO F1, F2 // fc011040 FCMPO F1, F2, CR0 // FCMPO F1,CR0,F2 // fc011040 FCMPU F1, F2 // fc011000 FCMPU F1, F2, CR0 // FCMPU F1,CR0,F2 // fc011000 LVX (R3)(R4), V1 // 7c2418ce LVX (R3)(R0), V1 // 7c2018ce LVX (R3), V1 // 7c2018ce LVXL (R3)(R4), V1 // 7c241ace LVXL (R3)(R0), V1 // 7c201ace LVXL (R3), V1 // 7c201ace LVSL (R3)(R4), V1 // 7c24180c LVSL (R3)(R0), V1 // 7c20180c LVSL (R3), V1 // 7c20180c LVSR (R3)(R4), V1 // 7c24184c LVSR (R3)(R0), V1 // 7c20184c LVSR (R3), V1 // 7c20184c LVEBX (R3)(R4), V1 // 7c24180e LVEBX (R3)(R0), V1 // 7c20180e LVEBX (R3), V1 // 7c20180e LVEHX (R3)(R4), V1 // 7c24184e LVEHX (R3)(R0), V1 // 7c20184e LVEHX (R3), V1 // 7c20184e LVEWX (R3)(R4), V1 // 7c24188e LVEWX (R3)(R0), V1 // 7c20188e LVEWX (R3), V1 // 7c20188e STVX V1, (R3)(R4) // 7c2419ce STVX V1, (R3)(R0) // 7c2019ce STVX V1, (R3) // 7c2019ce STVXL V1, (R3)(R4) // 7c241bce STVXL V1, (R3)(R0) // 7c201bce STVXL V1, (R3) // 7c201bce STVEBX V1, (R3)(R4) // 7c24190e STVEBX V1, (R3)(R0) // 7c20190e STVEBX V1, (R3) // 7c20190e STVEHX V1, (R3)(R4) // 7c24194e STVEHX V1, (R3)(R0) // 7c20194e STVEHX V1, (R3) // 7c20194e STVEWX V1, (R3)(R4) // 7c24198e STVEWX V1, (R3)(R0) // 7c20198e STVEWX V1, (R3) // 7c20198e VAND V1, V2, V3 // 10611404 VANDC V1, V2, V3 // 10611444 VNAND V1, V2, V3 // 10611584 VOR V1, V2, V3 // 10611484 VORC V1, V2, V3 // 10611544 VXOR V1, V2, V3 // 106114c4 VNOR V1, V2, V3 // 10611504 VEQV V1, V2, V3 // 10611684 VADDUBM V1, V2, V3 // 10611000 VADDUHM V1, V2, V3 // 10611040 VADDUWM V1, V2, V3 // 10611080 VADDUDM V1, V2, V3 // 106110c0 VADDUQM V1, V2, V3 // 10611100 VADDCUQ V1, V2, V3 // 10611140 VADDCUW V1, V2, V3 // 10611180 VADDUBS V1, V2, V3 // 10611200 VADDUHS V1, V2, V3 // 10611240 VADDUWS V1, V2, V3 // 10611280 VADDSBS V1, V2, V3 // 10611300 VADDSHS V1, V2, V3 // 10611340 VADDSWS V1, V2, V3 // 10611380 VADDEUQM V1, V2, V3, V4 // 108110fc VADDECUQ V1, V2, V3, V4 // 108110fd VSUBUBM V1, V2, V3 // 10611400 VSUBUHM V1, V2, V3 // 10611440 VSUBUWM V1, V2, V3 // 10611480 VSUBUDM V1, V2, V3 // 106114c0 VSUBUQM V1, V2, V3 // 10611500 VSUBCUQ V1, V2, V3 // 10611540 VSUBCUW V1, V2, V3 // 10611580 VSUBUBS V1, V2, V3 // 10611600 VSUBUHS V1, V2, V3 // 10611640 VSUBUWS V1, V2, V3 // 10611680 VSUBSBS V1, V2, V3 // 10611700 VSUBSHS V1, V2, V3 // 10611740 VSUBSWS V1, V2, V3 // 10611780 VSUBEUQM V1, V2, V3, V4 // 108110fe VSUBECUQ V1, V2, V3, V4 // 108110ff VMULESB V1, V2, V3 // 10611308 VMULESW V1, V2, V3 // 10611388 VMULOSB V1, V2, V3 // 10611108 VMULEUB V1, V2, V3 // 10611208 VMULOUB V1, V2, V3 // 10611008 VMULESH V1, V2, V3 // 10611348 VMULOSH V1, V2, V3 // 10611148 VMULEUH V1, V2, V3 // 10611248 VMULOUH V1, V2, V3 // 10611048 VMULESH V1, V2, V3 // 10611348 VMULOSW V1, V2, V3 // 10611188 VMULEUW V1, V2, V3 // 10611288 VMULOUW V1, V2, V3 // 10611088 VMULUWM V1, V2, V3 // 10611089 VPMSUMB V1, V2, V3 // 10611408 VPMSUMH V1, V2, V3 // 10611448 VPMSUMW V1, V2, V3 // 10611488 VPMSUMD V1, V2, V3 // 106114c8 VMSUMUDM V1, V2, V3, V4 // 108110e3 VRLB V1, V2, V3 // 10611004 VRLH V1, V2, V3 // 10611044 VRLW V1, V2, V3 // 10611084 VRLD V1, V2, V3 // 106110c4 VSLB V1, V2, V3 // 10611104 VSLH V1, V2, V3 // 10611144 VSLW V1, V2, V3 // 10611184 VSL V1, V2, V3 // 106111c4 VSLO V1, V2, V3 // 1061140c VSRB V1, V2, V3 // 10611204 VSRH V1, V2, V3 // 10611244 VSRW V1, V2, V3 // 10611284 VSRD V1, V2, V3 // 106116c4 VSR V1, V2, V3 // 106112c4 VSRO V1, V2, V3 // 1061144c VSLD V1, V2, V3 // 106115c4 VSRAB V1, V2, V3 // 10611304 VSRAH V1, V2, V3 // 10611344 VSRAW V1, V2, V3 // 10611384 VSRAD V1, V2, V3 // 106113c4 VSLDOI $3, V1, V2, V3 // 106110ec VCLZB V1, V2 // 10400f02 VCLZH V1, V2 // 10400f42 VCLZW V1, V2 // 10400f82 VCLZD V1, V2 // 10400fc2 VPOPCNTB V1, V2 // 10400f03 VPOPCNTH V1, V2 // 10400f43 VPOPCNTW V1, V2 // 10400f83 VPOPCNTD V1, V2 // 10400fc3 VCMPEQUB V1, V2, V3 // 10611006 VCMPEQUBCC V1, V2, V3 // 10611406 VCMPEQUH V1, V2, V3 // 10611046 VCMPEQUHCC V1, V2, V3 // 10611446 VCMPEQUW V1, V2, V3 // 10611086 VCMPEQUWCC V1, V2, V3 // 10611486 VCMPEQUD V1, V2, V3 // 106110c7 VCMPEQUDCC V1, V2, V3 // 106114c7 VCMPGTUB V1, V2, V3 // 10611206 VCMPGTUBCC V1, V2, V3 // 10611606 VCMPGTUH V1, V2, V3 // 10611246 VCMPGTUHCC V1, V2, V3 // 10611646 VCMPGTUW V1, V2, V3 // 10611286 VCMPGTUWCC V1, V2, V3 // 10611686 VCMPGTUD V1, V2, V3 // 106112c7 VCMPGTUDCC V1, V2, V3 // 106116c7 VCMPGTSB V1, V2, V3 // 10611306 VCMPGTSBCC V1, V2, V3 // 10611706 VCMPGTSH V1, V2, V3 // 10611346 VCMPGTSHCC V1, V2, V3 // 10611746 VCMPGTSW V1, V2, V3 // 10611386 VCMPGTSWCC V1, V2, V3 // 10611786 VCMPGTSD V1, V2, V3 // 106113c7 VCMPGTSDCC V1, V2, V3 // 106117c7 VCMPNEZB V1, V2, V3 // 10611107 VCMPNEZBCC V1, V2, V3 // 10611507 VCMPNEB V1, V2, V3 // 10611007 VCMPNEBCC V1, V2, V3 // 10611407 VCMPNEH V1, V2, V3 // 10611047 VCMPNEHCC V1, V2, V3 // 10611447 VCMPNEW V1, V2, V3 // 10611087 VCMPNEWCC V1, V2, V3 // 10611487 VPERM V1, V2, V3, V4 // 108110eb VPERMR V1, V2, V3, V4 // 108110fb VPERMXOR V1, V2, V3, V4 // 108110ed VBPERMQ V1, V2, V3 // 1061154c VBPERMD V1, V2, V3 // 106115cc VSEL V1, V2, V3, V4 // 108110ea VSPLTB $1, V1, V2 // 10410a0c VSPLTH $1, V1, V2 // 10410a4c VSPLTW $1, V1, V2 // 10410a8c VSPLTISB $1, V1 // 1021030c VSPLTISW $1, V1 // 1021038c VSPLTISH $1, V1 // 1021034c VCIPHER V1, V2, V3 // 10611508 VCIPHERLAST V1, V2, V3 // 10611509 VNCIPHER V1, V2, V3 // 10611548 VNCIPHERLAST V1, V2, V3 // 10611549 VSBOX V1, V2 // 104105c8 VSHASIGMAW $1, V1, $15, V2 // 10418e82 VSHASIGMAW $1, $15, V1, V2 // 10418e82 VSHASIGMAD $2, V1, $15, V2 // 104196c2 VSHASIGMAD $2, $15, V1, V2 // 104196c2 LXVD2X (R3)(R4), VS1 // 7c241e98 LXVD2X (R3)(R0), VS1 // 7c201e98 LXVD2X (R3), VS1 // 7c201e98 LXVDSX (R3)(R4), VS1 // 7c241a98 LXVDSX (R3)(R0), VS1 // 7c201a98 LXVDSX (R3), VS1 // 7c201a98 LXVH8X (R3)(R4), VS1 // 7c241e58 LXVH8X (R3)(R0), VS1 // 7c201e58 LXVH8X (R3), VS1 // 7c201e58 LXVB16X (R3)(R4), VS1 // 7c241ed8 LXVB16X (R3)(R0), VS1 // 7c201ed8 LXVB16X (R3), VS1 // 7c201ed8 LXVW4X (R3)(R4), VS1 // 7c241e18 LXVW4X (R3)(R0), VS1 // 7c201e18 LXVW4X (R3), VS1 // 7c201e18 LXV 16(R3), VS1 // f4230011 LXV (R3), VS1 // f4230001 LXV 16(R3), VS33 // f4230019 LXV (R3), VS33 // f4230009 LXV 16(R3), V1 // f4230019 LXV (R3), V1 // f4230009 LXVL R3, R4, VS1 // 7c23221a LXVLL R3, R4, VS1 // 7c23225a LXVX R3, R4, VS1 // 7c232218 LXSDX (R3)(R4), VS1 // 7c241c98 LXSDX (R3)(R0), VS1 // 7c201c98 LXSDX (R3), VS1 // 7c201c98 STXVD2X VS1, (R3)(R4) // 7c241f98 STXVD2X VS1, (R3)(R0) // 7c201f98 STXVD2X VS1, (R3) // 7c201f98 STXVW4X VS1, (R3)(R4) // 7c241f18 STXVW4X VS1, (R3)(R0) // 7c201f18 STXVW4X VS1, (R3) // 7c201f18 STXV VS1,16(R3) // f4230015 STXV VS1,(R3) // f4230005 STXVL VS1, R3, R4 // 7c23231a STXVLL VS1, R3, R4 // 7c23235a STXVX VS1, R3, R4 // 7c232318 STXVB16X VS1, (R4)(R5) // 7c2527d8 STXVB16X VS1, (R4)(R0) // 7c2027d8 STXVB16X VS1, (R4) // 7c2027d8 STXVH8X VS1, (R4)(R5) // 7c252758 STXVH8X VS1, (R4)(R0) // 7c202758 STXVH8X VS1, (R4) // 7c202758 STXSDX VS1, (R3)(R4) // 7c241d98 STXSDX VS1, (R4)(R0) // 7c202598 STXSDX VS1, (R4) // 7c202598 LXSIWAX (R3)(R4), VS1 // 7c241898 LXSIWAX (R3)(R0), VS1 // 7c201898 LXSIWAX (R3), VS1 // 7c201898 LXSIWZX (R3)(R4), VS1 // 7c241818 LXSIWZX (R3)(R0), VS1 // 7c201818 LXSIWZX (R3), VS1 // 7c201818 STXSIWX VS1, (R3)(R4) // 7c241918 STXSIWX VS1, (R3)(R0) // 7c201918 STXSIWX VS1, (R3) // 7c201918 MFVSRD VS1, R3 // 7c230066 MTFPRD R3, F0 // 7c030166 MFVRD V0, R3 // 7c030067 MFVSRLD VS63,R4 // 7fe40267 MFVSRLD V31,R4 // 7fe40267 MFVSRWZ VS33,R4 // 7c2400e7 MFVSRWZ V1,R4 // 7c2400e7 MTVSRD R3, VS1 // 7c230166 MTVSRDD R3, R4, VS1 // 7c232366 MTVSRDD R3, R4, VS33 // 7c232367 MTVSRDD R3, R4, V1 // 7c232367 MTVRD R3, V13 // 7da30167 MTVSRWA R4, VS31 // 7fe401a6 MTVSRWS R4, VS32 // 7c040327 MTVSRWZ R4, VS63 // 7fe401e7 MTFSB0 $2 // fc40008c MTFSB0CC $2 // fc40008d MTFSB1 $2 // fc40004c MTFSB1CC $2 // fc40004d XXBRQ VS0, VS1 // f03f076c XXBRD VS0, VS1 // f037076c XXBRW VS1, VS2 // f04f0f6c XXBRH VS2, VS3 // f067176c XXLAND VS1, VS2, VS3 // f0611410 XXLAND V1, V2, V3 // f0611417 XXLAND VS33, VS34, VS35 // f0611417 XXLANDC VS1, VS2, VS3 // f0611450 XXLEQV VS0, VS1, VS2 // f0400dd0 XXLNAND VS0, VS1, VS2 // f0400d90 XXLNOR VS0, VS1, VS32 // f0000d11 XXLOR VS1, VS2, VS3 // f0611490 XXLORC VS1, VS2, VS3 // f0611550 XXLORQ VS1, VS2, VS3 // f0611490 XXLXOR VS1, VS2, VS3 // f06114d0 XXSEL VS1, VS2, VS3, VS4 // f08110f0 XXSEL VS33, VS34, VS35, VS36 // f08110ff XXSEL V1, V2, V3, V4 // f08110ff XXMRGHW VS1, VS2, VS3 // f0611090 XXMRGLW VS1, VS2, VS3 // f0611190 XXSPLTW VS1, $1, VS2 // f0410a90 XXSPLTW VS33, $1, VS34 // f0410a93 XXSPLTW V1, $1, V2 // f0410a93 XXPERM VS1, VS2, VS3 // f06110d0 XXSLDWI VS1, VS2, $1, VS3 // f0611110 XXSLDWI V1, V2, $1, V3 // f0611117 XXSLDWI V1, $1, V2, V3 // f0611117 XXSLDWI VS33, VS34, $1, VS35 // f0611117 XXSLDWI VS33, $1, VS34, VS35 // f0611117 XXPERMDI VS33, VS34, $1, VS35 // f0611157 XXPERMDI VS33, $1, VS34, VS35 // f0611157 XSCVDPSP VS1, VS2 // f0400c24 XVCVDPSP VS1, VS2 // f0400e24 XSCVSXDDP VS1, VS2 // f0400de0 XVCVDPSXDS VS1, VS2 // f0400f60 XVCVSXDDP VS1, VS2 // f0400fe0 XSCVDPSPN VS1,VS32 // f0000c2d XSCVDPSP VS1,VS32 // f0000c25 XSCVDPSXDS VS1,VS32 // f0000d61 XSCVDPSXWS VS1,VS32 // f0000961 XSCVDPUXDS VS1,VS32 // f0000d21 XSCVDPUXWS VS1,VS32 // f0000921 XSCVSPDPN VS1,VS32 // f0000d2d XSCVSPDP VS1,VS32 // f0000d25 XSCVSXDDP VS1,VS32 // f0000de1 XSCVSXDSP VS1,VS32 // f0000ce1 XSCVUXDDP VS1,VS32 // f0000da1 XSCVUXDSP VS1,VS32 // f0000ca1 XVCVDPSP VS1,VS32 // f0000e25 XVCVDPSXDS VS1,VS32 // f0000f61 XVCVDPSXWS VS1,VS32 // f0000b61 XVCVDPUXDS VS1,VS32 // f0000f21 XVCVDPUXWS VS1,VS32 // f0000b21 XVCVSPDP VS1,VS32 // f0000f25 XVCVSPSXDS VS1,VS32 // f0000e61 XVCVSPSXWS VS1,VS32 // f0000a61 XVCVSPUXDS VS1,VS32 // f0000e21 XVCVSPUXWS VS1,VS32 // f0000a21 XVCVSXDDP VS1,VS32 // f0000fe1 XVCVSXDSP VS1,VS32 // f0000ee1 XVCVSXWDP VS1,VS32 // f0000be1 XVCVSXWSP VS1,VS32 // f0000ae1 XVCVUXDDP VS1,VS32 // f0000fa1 XVCVUXDSP VS1,VS32 // f0000ea1 XVCVUXWDP VS1,VS32 // f0000ba1 XVCVUXWSP VS1,VS32 // f0000aa1 MOVD R3, LR // 7c6803a6 MOVD R3, CTR // 7c6903a6 MOVD R3, XER // 7c6103a6 MOVD LR, R3 // 7c6802a6 MOVD CTR, R3 // 7c6902a6 MOVD XER, R3 // 7c6102a6 MOVFL CR3, CR1 // 4c8c0000 MOVW CR0, R1 // 7c380026 MOVW CR7, R1 // 7c301026 MOVW CR, R1 // 7c200026 MOVW R1, CR // 7c2ff120 MOVFL R1, CR // 7c2ff120 MOVW R1, CR2 // 7c320120 MOVFL R1, CR2 // 7c320120 MOVFL R1, $255 // 7c2ff120 MOVFL R1, $1 // 7c301120 MOVFL R1, $128 // 7c380120 MOVFL R1, $3 // 7c203120 MOVMW 4(R3), R4 // b8830004 // Verify supported bdnz/bdz encodings. BC 16,0,0(PC) // BC $16, CR0LT, 0(PC) // 42000000 BDNZ 0(PC) // 42000000 BDZ 0(PC) // 42400000 BC 18,0,0(PC) // BC $18, CR0LT, 0(PC) // 42400000 // Verify the supported forms of bcclr[l] BC $20,CR0LT,$1,LR // 4e800820 BC $20,CR0LT,$0,LR // 4e800020 BC $20,CR0LT,LR // 4e800020 BC $20,CR0GT,LR // 4e810020 BC 20,CR0LT,LR // BC $20,CR0LT,LR // 4e800020 BC 20,undefined_symbol,LR // BC $20,CR0LT,LR // 4e800020 BC 20,undefined_symbol+1,LR // BC $20,CR0GT,LR // 4e810020 JMP LR // 4e800020 BR LR // JMP LR // 4e800020 BCL $20,CR0LT,$1,LR // 4e800821 BCL $20,CR0LT,$0,LR // 4e800021 BCL $20,CR0LT,LR // 4e800021 BCL $20,CR0GT,LR // 4e810021 BCL 20,CR0LT,LR // BCL $20,CR0LT,LR // 4e800021 BCL 20,undefined_symbol,LR // BCL $20,CR0LT,LR // 4e800021 BCL 20,undefined_symbol+1,LR // BCL $20,CR0GT,LR // 4e810021 // Verify the supported forms of bcctr[l] BC $20,CR0LT,CTR // 4e800420 BC $20,CR0GT,CTR // 4e810420 BC 20,CR0LT,CTR // BC $20,CR0LT,CTR // 4e800420 BC 20,undefined_symbol,CTR // BC $20,CR0LT,CTR // 4e800420 BC 20,undefined_symbol+1,CTR // BC $20,CR0GT,CTR // 4e810420 JMP CTR // 4e800420 BR CTR // JMP CTR // 4e800420 BCL $20,CR0LT,CTR // 4e800421 BCL $20,CR0GT,CTR // 4e810421 BCL 20,CR0LT,CTR // BCL $20,CR0LT,CTR // 4e800421 BCL 20,undefined_symbol,CTR // BCL $20,CR0LT,CTR // 4e800421 BCL 20,undefined_symbol+1,CTR // BCL $20,CR0GT,CTR // 4e810421 // Verify bc encoding (without pic enabled) BC $16,CR0LT,0(PC) // 42000000 BCL $16,CR0LT,0(PC) // 42000001 BC $18,CR0LT,0(PC) // 42400000 MOVD SPR(3), 4(R1) // 7fe302a6fbe10004 MOVD XER, 4(R1) // 7fe102a6fbe10004 MOVD 4(R1), SPR(3) // ebe100047fe303a6 MOVD 4(R1), XER // ebe100047fe103a6 OR $0, R0, R0 // 60000000 PNOP // 0700000000000000 SETB CR1,R3 // 7c640100 VCLZLSBB V1,R2 // 10400e02 VCTZLSBB V1,R2 // 10410e02 XSMAXJDP VS1,VS2,VS3 // f0611480 XSMINJDP VS1,VS2,VS3 // f06114c0 RET
go/src/cmd/asm/internal/asm/testdata/ppc64.s/0
{ "file_path": "go/src/cmd/asm/internal/asm/testdata/ppc64.s", "repo_id": "go", "token_count": 36362 }
67
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build compiler_bootstrap package main import ( "go/ast" "go/token" ) func (f *File) walkUnexpected(x interface{}, context astContext, visit func(*File, interface{}, astContext)) { error_(token.NoPos, "unexpected type %T in walk", x) panic("unexpected type") } func funcTypeTypeParams(n *ast.FuncType) *ast.FieldList { return nil } func typeSpecTypeParams(n *ast.TypeSpec) *ast.FieldList { return nil }
go/src/cmd/cgo/ast_go1.go/0
{ "file_path": "go/src/cmd/cgo/ast_go1.go", "repo_id": "go", "token_count": 193 }
68
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <string.h> #include "_cgo_export.h" void callback(void *f) { // use some stack space volatile char data[64*1024]; data[0] = 0; goCallback(f); data[sizeof(data)-1] = 0; } void callGoFoo(void) { extern void goFoo(void); goFoo(); } void IntoC(void) { BackIntoGo(); } void Issue1560InC(void) { Issue1560FromC(); } void callGoStackCheck(void) { extern void goStackCheck(void); goStackCheck(); } int returnAfterGrow(void) { extern int goReturnVal(void); goReturnVal(); return 123456; } int returnAfterGrowFromGo(void) { extern int goReturnVal(void); return goReturnVal(); } void callGoWithString(void) { extern void goWithString(GoString); const char *str = "string passed from C to Go"; goWithString((GoString){str, strlen(str)}); }
go/src/cmd/cgo/internal/test/callback_c.c/0
{ "file_path": "go/src/cmd/cgo/internal/test/callback_c.c", "repo_id": "go", "token_count": 370 }
69
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <stdio.h> #include "issue4339.h" static void impl(void) { //printf("impl\n"); } Issue4339 exported4339 = {"bar", impl}; void handle4339(Issue4339 *x) { //printf("handle\n"); x->bar(); //printf("done\n"); }
go/src/cmd/cgo/internal/test/issue4339.c/0
{ "file_path": "go/src/cmd/cgo/internal/test/issue4339.c", "repo_id": "go", "token_count": 138 }
70
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cgotest import "testing" // This test actually doesn't have anything to do with cgo. It is a // test of https://golang.org/issue/7234, a compiler/linker bug in // handling string constants when using -linkmode=external. The test // is in this directory because we routinely test -linkmode=external // here. var v7234 = [...]string{"runtime/cgo"} func Test7234(t *testing.T) { if v7234[0] != "runtime/cgo" { t.Errorf("bad string constant %q", v7234[0]) } }
go/src/cmd/cgo/internal/test/issue7234_test.go/0
{ "file_path": "go/src/cmd/cgo/internal/test/issue7234_test.go", "repo_id": "go", "token_count": 202 }
71
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build gc #include "textflag.h" TEXT ·RewindAndSetgid(SB),NOSPLIT,$0-0 MOVL $·Baton(SB), BX // Rewind stack pointer so anything that happens on the stack // will clobber the test pattern created by the caller ADDL $(1024 * 8), SP // Ask signaller to setgid MOVL $1, (BX) // Wait for setgid completion loop: PAUSE MOVL (BX), AX CMPL AX, $0 JNE loop // Restore stack SUBL $(1024 * 8), SP RET
go/src/cmd/cgo/internal/test/issue9400/asm_386.s/0
{ "file_path": "go/src/cmd/cgo/internal/test/issue9400/asm_386.s", "repo_id": "go", "token_count": 221 }
72
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // This test uses various syscall.SIG* constants that are defined on Unix // platforms and Windows. //go:build unix || windows package carchive_test import ( "bufio" "bytes" "cmd/cgo/internal/cgotest" "debug/elf" "flag" "fmt" "internal/testenv" "io" "log" "os" "os/exec" "path/filepath" "regexp" "runtime" "strconv" "strings" "sync" "syscall" "testing" "time" "unicode" ) var globalSkip = func(t *testing.T) {} // Program to run. var bin []string // C compiler with args (from $(go env CC) $(go env GOGCCFLAGS)). var cc []string // ".exe" on Windows. var exeSuffix string var GOOS, GOARCH, GOPATH string var libgodir string var testWork bool // If true, preserve temporary directories. func TestMain(m *testing.M) { flag.BoolVar(&testWork, "testwork", false, "if true, log and preserve the test's temporary working directory") flag.Parse() log.SetFlags(log.Lshortfile) os.Exit(testMain(m)) } func testMain(m *testing.M) int { if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" { globalSkip = func(t *testing.T) { t.Skip("short mode and $GO_BUILDER_NAME not set") } return m.Run() } if runtime.GOOS == "linux" { if _, err := os.Stat("/etc/alpine-release"); err == nil { globalSkip = func(t *testing.T) { t.Skip("skipping failing test on alpine - go.dev/issue/19938") } return m.Run() } } // We need a writable GOPATH in which to run the tests. // Construct one in a temporary directory. var err error GOPATH, err = os.MkdirTemp("", "carchive_test") if err != nil { log.Panic(err) } if testWork { log.Println(GOPATH) } else { defer os.RemoveAll(GOPATH) } os.Setenv("GOPATH", GOPATH) // Copy testdata into GOPATH/src/testarchive, along with a go.mod file // declaring the same path. modRoot := filepath.Join(GOPATH, "src", "testcarchive") if err := cgotest.OverlayDir(modRoot, "testdata"); err != nil { log.Panic(err) } if err := os.Chdir(modRoot); err != nil { log.Panic(err) } os.Setenv("PWD", modRoot) if err := os.WriteFile("go.mod", []byte("module testcarchive\n"), 0666); err != nil { log.Panic(err) } GOOS = goEnv("GOOS") GOARCH = goEnv("GOARCH") bin = cmdToRun("./testp") ccOut := goEnv("CC") cc = []string{string(ccOut)} out := goEnv("GOGCCFLAGS") quote := '\000' start := 0 lastSpace := true backslash := false s := string(out) for i, c := range s { if quote == '\000' && unicode.IsSpace(c) { if !lastSpace { cc = append(cc, s[start:i]) lastSpace = true } } else { if lastSpace { start = i lastSpace = false } if quote == '\000' && !backslash && (c == '"' || c == '\'') { quote = c backslash = false } else if !backslash && quote == c { quote = '\000' } else if (quote == '\000' || quote == '"') && !backslash && c == '\\' { backslash = true } else { backslash = false } } } if !lastSpace { cc = append(cc, s[start:]) } if GOOS == "aix" { // -Wl,-bnoobjreorder is mandatory to keep the same layout // in .text section. cc = append(cc, "-Wl,-bnoobjreorder") } if GOOS == "ios" { // Linking runtime/cgo on ios requires the CoreFoundation framework because // x_cgo_init uses CoreFoundation APIs to switch directory to the app root. // // TODO(#58225): This special case probably should not be needed. // runtime/cgo is a very low-level package, and should not provide // high-level behaviors like changing the current working directory at init. cc = append(cc, "-framework", "CoreFoundation") } libbase := GOOS + "_" + GOARCH if runtime.Compiler == "gccgo" { libbase = "gccgo_" + libgodir + "_fPIC" } else { switch GOOS { case "darwin", "ios": if GOARCH == "arm64" { libbase += "_shared" } case "dragonfly", "freebsd", "linux", "netbsd", "openbsd", "solaris", "illumos": libbase += "_shared" } } libgodir = filepath.Join(GOPATH, "pkg", libbase, "testcarchive") cc = append(cc, "-I", libgodir) // Force reallocation (and avoid aliasing bugs) for parallel tests that append to cc. cc = cc[:len(cc):len(cc)] if GOOS == "windows" { exeSuffix = ".exe" } return m.Run() } func goEnv(key string) string { out, err := exec.Command("go", "env", key).Output() if err != nil { if ee, ok := err.(*exec.ExitError); ok { fmt.Fprintf(os.Stderr, "%s", ee.Stderr) } log.Panicf("go env %s failed:\n%s\n", key, err) } return strings.TrimSpace(string(out)) } func cmdToRun(name string) []string { execScript := "go_" + goEnv("GOOS") + "_" + goEnv("GOARCH") + "_exec" executor, err := exec.LookPath(execScript) if err != nil { return []string{name} } return []string{executor, name} } // genHeader writes a C header file for the C-exported declarations found in .go // source files in dir. // // TODO(golang.org/issue/35715): This should be simpler. func genHeader(t *testing.T, header, dir string) { t.Helper() // The 'cgo' command generates a number of additional artifacts, // but we're only interested in the header. // Shunt the rest of the outputs to a temporary directory. objDir, err := os.MkdirTemp(GOPATH, "_obj") if err != nil { t.Fatal(err) } defer os.RemoveAll(objDir) files, err := filepath.Glob(filepath.Join(dir, "*.go")) if err != nil { t.Fatal(err) } cmd := exec.Command("go", "tool", "cgo", "-objdir", objDir, "-exportheader", header) cmd.Args = append(cmd.Args, files...) t.Log(cmd.Args) if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } } func testInstall(t *testing.T, exe, libgoa, libgoh string, buildcmd ...string) { t.Helper() cmd := exec.Command(buildcmd[0], buildcmd[1:]...) cmd.Env = append(cmd.Environ(), "GO111MODULE=off") // 'go install' only works in GOPATH mode t.Log(buildcmd) if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } if !testWork { defer func() { os.Remove(libgoa) os.Remove(libgoh) }() } ccArgs := append(cc, "-o", exe, "main.c") if GOOS == "windows" { ccArgs = append(ccArgs, "main_windows.c", libgoa, "-lntdll", "-lws2_32", "-lwinmm") } else { ccArgs = append(ccArgs, "main_unix.c", libgoa) } if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } t.Log(ccArgs) if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } if !testWork { defer os.Remove(exe) } binArgs := append(cmdToRun(exe), "arg1", "arg2") cmd = exec.Command(binArgs[0], binArgs[1:]...) if runtime.Compiler == "gccgo" { cmd.Env = append(cmd.Environ(), "GCCGO=1") } if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } checkLineComments(t, libgoh) } var badLineRegexp = regexp.MustCompile(`(?m)^#line [0-9]+ "/.*$`) // checkLineComments checks that the export header generated by // -buildmode=c-archive doesn't have any absolute paths in the #line // comments. We don't want those paths because they are unhelpful for // the user and make the files change based on details of the location // of GOPATH. func checkLineComments(t *testing.T, hdrname string) { hdr, err := os.ReadFile(hdrname) if err != nil { if !os.IsNotExist(err) { t.Error(err) } return } if line := badLineRegexp.Find(hdr); line != nil { t.Errorf("bad #line directive with absolute path in %s: %q", hdrname, line) } } // checkArchive verifies that the created library looks OK. // We just check a couple of things now, we can add more checks as needed. func checkArchive(t *testing.T, arname string) { t.Helper() switch GOOS { case "aix", "darwin", "ios", "windows": // We don't have any checks for non-ELF libraries yet. if _, err := os.Stat(arname); err != nil { t.Errorf("archive %s does not exist: %v", arname, err) } default: checkELFArchive(t, arname) } } // checkELFArchive checks an ELF archive. func checkELFArchive(t *testing.T, arname string) { t.Helper() f, err := os.Open(arname) if err != nil { t.Errorf("archive %s does not exist: %v", arname, err) return } defer f.Close() // TODO(iant): put these in a shared package? But where? const ( magic = "!<arch>\n" fmag = "`\n" namelen = 16 datelen = 12 uidlen = 6 gidlen = 6 modelen = 8 sizelen = 10 fmaglen = 2 hdrlen = namelen + datelen + uidlen + gidlen + modelen + sizelen + fmaglen ) type arhdr struct { name string date string uid string gid string mode string size string fmag string } var magbuf [len(magic)]byte if _, err := io.ReadFull(f, magbuf[:]); err != nil { t.Errorf("%s: archive too short", arname) return } if string(magbuf[:]) != magic { t.Errorf("%s: incorrect archive magic string %q", arname, magbuf) } off := int64(len(magic)) for { if off&1 != 0 { var b [1]byte if _, err := f.Read(b[:]); err != nil { if err == io.EOF { break } t.Errorf("%s: error skipping alignment byte at %d: %v", arname, off, err) } off++ } var hdrbuf [hdrlen]byte if _, err := io.ReadFull(f, hdrbuf[:]); err != nil { if err == io.EOF { break } t.Errorf("%s: error reading archive header at %d: %v", arname, off, err) return } var hdr arhdr hdrslice := hdrbuf[:] set := func(len int, ps *string) { *ps = string(bytes.TrimSpace(hdrslice[:len])) hdrslice = hdrslice[len:] } set(namelen, &hdr.name) set(datelen, &hdr.date) set(uidlen, &hdr.uid) set(gidlen, &hdr.gid) set(modelen, &hdr.mode) set(sizelen, &hdr.size) hdr.fmag = string(hdrslice[:fmaglen]) hdrslice = hdrslice[fmaglen:] if len(hdrslice) != 0 { t.Fatalf("internal error: len(hdrslice) == %d", len(hdrslice)) } if hdr.fmag != fmag { t.Errorf("%s: invalid fmagic value %q at %d", arname, hdr.fmag, off) return } size, err := strconv.ParseInt(hdr.size, 10, 64) if err != nil { t.Errorf("%s: error parsing size %q at %d: %v", arname, hdr.size, off, err) return } off += hdrlen switch hdr.name { case "__.SYMDEF", "/", "/SYM64/": // The archive symbol map. case "//", "ARFILENAMES/": // The extended name table. default: // This should be an ELF object. checkELFArchiveObject(t, arname, off, io.NewSectionReader(f, off, size)) } off += size if _, err := f.Seek(off, io.SeekStart); err != nil { t.Errorf("%s: failed to seek to %d: %v", arname, off, err) } } } // checkELFArchiveObject checks an object in an ELF archive. func checkELFArchiveObject(t *testing.T, arname string, off int64, obj io.ReaderAt) { t.Helper() ef, err := elf.NewFile(obj) if err != nil { t.Errorf("%s: failed to open ELF file at %d: %v", arname, off, err) return } defer ef.Close() // Verify section types. for _, sec := range ef.Sections { want := elf.SHT_NULL switch sec.Name { case ".text", ".data": want = elf.SHT_PROGBITS case ".bss": want = elf.SHT_NOBITS case ".symtab": want = elf.SHT_SYMTAB case ".strtab": want = elf.SHT_STRTAB case ".init_array": want = elf.SHT_INIT_ARRAY case ".fini_array": want = elf.SHT_FINI_ARRAY case ".preinit_array": want = elf.SHT_PREINIT_ARRAY } if want != elf.SHT_NULL && sec.Type != want { t.Errorf("%s: incorrect section type in elf file at %d for section %q: got %v want %v", arname, off, sec.Name, sec.Type, want) } } } func TestInstall(t *testing.T) { globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") if !testWork { defer os.RemoveAll(filepath.Join(GOPATH, "pkg")) } libgoa := "libgo.a" if runtime.Compiler == "gccgo" { libgoa = "liblibgo.a" } // Generate the p.h header file. // // 'go install -i -buildmode=c-archive ./libgo' would do that too, but that // would also attempt to install transitive standard-library dependencies to // GOROOT, and we cannot assume that GOROOT is writable. (A non-root user may // be running this test in a GOROOT owned by root.) genHeader(t, "p.h", "./p") testInstall(t, "./testp1"+exeSuffix, filepath.Join(libgodir, libgoa), filepath.Join(libgodir, "libgo.h"), "go", "install", "-buildmode=c-archive", "./libgo") // Test building libgo other than installing it. // Header files are now present. testInstall(t, "./testp2"+exeSuffix, "libgo.a", "libgo.h", "go", "build", "-buildmode=c-archive", filepath.Join(".", "libgo", "libgo.go")) testInstall(t, "./testp3"+exeSuffix, "libgo.a", "libgo.h", "go", "build", "-buildmode=c-archive", "-o", "libgo.a", "./libgo") } func TestEarlySignalHandler(t *testing.T) { switch GOOS { case "darwin", "ios": switch GOARCH { case "arm64": t.Skipf("skipping on %s/%s; see https://golang.org/issue/13701", GOOS, GOARCH) } case "windows": t.Skip("skipping signal test on Windows") } globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") if !testWork { defer func() { os.Remove("libgo2.a") os.Remove("libgo2.h") os.Remove("testp" + exeSuffix) os.RemoveAll(filepath.Join(GOPATH, "pkg")) }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo2.a", "./libgo2") if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } checkLineComments(t, "libgo2.h") checkArchive(t, "libgo2.a") ccArgs := append(cc, "-o", "testp"+exeSuffix, "main2.c", "libgo2.a") if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } darwin := "0" if runtime.GOOS == "darwin" { darwin = "1" } cmd = exec.Command(bin[0], append(bin[1:], darwin)...) if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } } func TestSignalForwarding(t *testing.T) { globalSkip(t) checkSignalForwardingTest(t) buildSignalForwardingTest(t) cmd := exec.Command(bin[0], append(bin[1:], "1")...) out, err := cmd.CombinedOutput() t.Logf("%v\n%s", cmd.Args, out) expectSignal(t, err, syscall.SIGSEGV, 0) // SIGPIPE is never forwarded on darwin. See golang.org/issue/33384. if runtime.GOOS != "darwin" && runtime.GOOS != "ios" { // Test SIGPIPE forwarding cmd = exec.Command(bin[0], append(bin[1:], "3")...) out, err = cmd.CombinedOutput() if len(out) > 0 { t.Logf("%s", out) } expectSignal(t, err, syscall.SIGPIPE, 0) } } func TestSignalForwardingExternal(t *testing.T) { if GOOS == "freebsd" || GOOS == "aix" { t.Skipf("skipping on %s/%s; signal always goes to the Go runtime", GOOS, GOARCH) } else if GOOS == "darwin" && GOARCH == "amd64" { t.Skipf("skipping on %s/%s: runtime does not permit SI_USER SIGSEGV", GOOS, GOARCH) } globalSkip(t) checkSignalForwardingTest(t) buildSignalForwardingTest(t) // We want to send the process a signal and see if it dies. // Normally the signal goes to the C thread, the Go signal // handler picks it up, sees that it is running in a C thread, // and the program dies. Unfortunately, occasionally the // signal is delivered to a Go thread, which winds up // discarding it because it was sent by another program and // there is no Go handler for it. To avoid this, run the // program several times in the hopes that it will eventually // fail. const tries = 20 for i := 0; i < tries; i++ { err := runSignalForwardingTest(t, "2") if err == nil { continue } // If the signal is delivered to a C thread, as expected, // the Go signal handler will disable itself and re-raise // the signal, causing the program to die with SIGSEGV. // // It is also possible that the signal will be // delivered to a Go thread, such as a GC thread. // Currently when the Go runtime sees that a SIGSEGV was // sent from a different program, it first tries to send // the signal to the os/signal API. If nothing is looking // for (or explicitly ignoring) SIGSEGV, then it crashes. // Because the Go runtime is invoked via a c-archive, // it treats this as GOTRACEBACK=crash, meaning that it // dumps a stack trace for all goroutines, which it does // by raising SIGQUIT. The effect is that we will see the // program die with SIGQUIT in that case, not SIGSEGV. if expectSignal(t, err, syscall.SIGSEGV, syscall.SIGQUIT) { return } } t.Errorf("program succeeded unexpectedly %d times", tries) } func TestSignalForwardingGo(t *testing.T) { // This test fails on darwin-amd64 because of the special // handling of user-generated SIGSEGV signals in fixsigcode in // runtime/signal_darwin_amd64.go. if runtime.GOOS == "darwin" && runtime.GOARCH == "amd64" { t.Skip("not supported on darwin-amd64") } globalSkip(t) checkSignalForwardingTest(t) buildSignalForwardingTest(t) err := runSignalForwardingTest(t, "4") // Occasionally the signal will be delivered to a C thread, // and the program will crash with SIGSEGV. expectSignal(t, err, syscall.SIGQUIT, syscall.SIGSEGV) } // checkSignalForwardingTest calls t.Skip if the SignalForwarding test // doesn't work on this platform. func checkSignalForwardingTest(t *testing.T) { switch GOOS { case "darwin", "ios": switch GOARCH { case "arm64": t.Skipf("skipping on %s/%s; see https://golang.org/issue/13701", GOOS, GOARCH) } case "windows": t.Skip("skipping signal test on Windows") } testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") } // buildSignalForwardingTest builds the executable used by the various // signal forwarding tests. func buildSignalForwardingTest(t *testing.T) { if !testWork { t.Cleanup(func() { os.Remove("libgo2.a") os.Remove("libgo2.h") os.Remove("testp" + exeSuffix) os.RemoveAll(filepath.Join(GOPATH, "pkg")) }) } t.Log("go build -buildmode=c-archive -o libgo2.a ./libgo2") cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo2.a", "./libgo2") out, err := cmd.CombinedOutput() if len(out) > 0 { t.Logf("%s", out) } if err != nil { t.Fatal(err) } checkLineComments(t, "libgo2.h") checkArchive(t, "libgo2.a") ccArgs := append(cc, "-o", "testp"+exeSuffix, "main5.c", "libgo2.a") if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } t.Log(ccArgs) out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() if len(out) > 0 { t.Logf("%s", out) } if err != nil { t.Fatal(err) } } func runSignalForwardingTest(t *testing.T, arg string) error { t.Logf("%v %s", bin, arg) cmd := exec.Command(bin[0], append(bin[1:], arg)...) var out strings.Builder cmd.Stdout = &out stderr, err := cmd.StderrPipe() if err != nil { t.Fatal(err) } defer stderr.Close() r := bufio.NewReader(stderr) err = cmd.Start() if err != nil { t.Fatal(err) } // Wait for trigger to ensure that process is started. ok, err := r.ReadString('\n') // Verify trigger. if err != nil || ok != "OK\n" { t.Fatal("Did not receive OK signal") } var wg sync.WaitGroup wg.Add(1) var errsb strings.Builder go func() { defer wg.Done() io.Copy(&errsb, r) }() // Give the program a chance to enter the function. // If the program doesn't get there the test will still // pass, although it doesn't quite test what we intended. // This is fine as long as the program normally makes it. time.Sleep(time.Millisecond) cmd.Process.Signal(syscall.SIGSEGV) err = cmd.Wait() s := out.String() if len(s) > 0 { t.Log(s) } wg.Wait() s = errsb.String() if len(s) > 0 { t.Log(s) } return err } // expectSignal checks that err, the exit status of a test program, // shows a failure due to a specific signal or two. Returns whether we // found an expected signal. func expectSignal(t *testing.T, err error, sig1, sig2 syscall.Signal) bool { t.Helper() if err == nil { t.Error("test program succeeded unexpectedly") } else if ee, ok := err.(*exec.ExitError); !ok { t.Errorf("error (%v) has type %T; expected exec.ExitError", err, err) } else if ws, ok := ee.Sys().(syscall.WaitStatus); !ok { t.Errorf("error.Sys (%v) has type %T; expected syscall.WaitStatus", ee.Sys(), ee.Sys()) } else if !ws.Signaled() || (ws.Signal() != sig1 && ws.Signal() != sig2) { if sig2 == 0 { t.Errorf("got %q; expected signal %q", ee, sig1) } else { t.Errorf("got %q; expected signal %q or %q", ee, sig1, sig2) } } else { return true } return false } func TestOsSignal(t *testing.T) { switch GOOS { case "windows": t.Skip("skipping signal test on Windows") } globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") if !testWork { defer func() { os.Remove("libgo3.a") os.Remove("libgo3.h") os.Remove("testp" + exeSuffix) os.RemoveAll(filepath.Join(GOPATH, "pkg")) }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo3.a", "./libgo3") if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } checkLineComments(t, "libgo3.h") checkArchive(t, "libgo3.a") ccArgs := append(cc, "-o", "testp"+exeSuffix, "main3.c", "libgo3.a") if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } if out, err := exec.Command(bin[0], bin[1:]...).CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } } func TestSigaltstack(t *testing.T) { switch GOOS { case "windows": t.Skip("skipping signal test on Windows") } globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") if !testWork { defer func() { os.Remove("libgo4.a") os.Remove("libgo4.h") os.Remove("testp" + exeSuffix) os.RemoveAll(filepath.Join(GOPATH, "pkg")) }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo4.a", "./libgo4") if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } checkLineComments(t, "libgo4.h") checkArchive(t, "libgo4.a") ccArgs := append(cc, "-o", "testp"+exeSuffix, "main4.c", "libgo4.a") if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } if out, err := exec.Command(bin[0], bin[1:]...).CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } } const testar = `#!/usr/bin/env bash while [[ $1 == -* ]] >/dev/null; do shift done echo "testar" > $1 echo "testar" > PWD/testar.ran ` func TestExtar(t *testing.T) { switch GOOS { case "windows": t.Skip("skipping signal test on Windows") } if runtime.Compiler == "gccgo" { t.Skip("skipping -extar test when using gccgo") } globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") testenv.MustHaveExecPath(t, "bash") // This test uses a bash script if !testWork { defer func() { os.Remove("libgo4.a") os.Remove("libgo4.h") os.Remove("testar") os.Remove("testar.ran") os.RemoveAll(filepath.Join(GOPATH, "pkg")) }() } os.Remove("testar") dir, err := os.Getwd() if err != nil { t.Fatal(err) } s := strings.Replace(testar, "PWD", dir, 1) if err := os.WriteFile("testar", []byte(s), 0777); err != nil { t.Fatal(err) } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-ldflags=-extar="+filepath.Join(dir, "testar"), "-o", "libgo4.a", "./libgo4") if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } checkLineComments(t, "libgo4.h") if _, err := os.Stat("testar.ran"); err != nil { if os.IsNotExist(err) { t.Error("testar does not exist after go build") } else { t.Errorf("error checking testar: %v", err) } } } func TestPIE(t *testing.T) { switch GOOS { case "windows", "darwin", "ios", "plan9": t.Skipf("skipping PIE test on %s", GOOS) } globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") libgoa := "libgo.a" if runtime.Compiler == "gccgo" { libgoa = "liblibgo.a" } if !testWork { defer func() { os.Remove("testp" + exeSuffix) os.Remove(libgoa) os.RemoveAll(filepath.Join(GOPATH, "pkg")) }() } // Generate the p.h header file. // // 'go install -i -buildmode=c-archive ./libgo' would do that too, but that // would also attempt to install transitive standard-library dependencies to // GOROOT, and we cannot assume that GOROOT is writable. (A non-root user may // be running this test in a GOROOT owned by root.) genHeader(t, "p.h", "./p") cmd := exec.Command("go", "build", "-buildmode=c-archive", "./libgo") if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } ccArgs := append(cc, "-fPIE", "-pie", "-o", "testp"+exeSuffix, "main.c", "main_unix.c", libgoa) if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } if out, err := exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } binArgs := append(bin, "arg1", "arg2") cmd = exec.Command(binArgs[0], binArgs[1:]...) if runtime.Compiler == "gccgo" { cmd.Env = append(os.Environ(), "GCCGO=1") } if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } if GOOS != "aix" { f, err := elf.Open("testp" + exeSuffix) if err != nil { t.Fatal("elf.Open failed: ", err) } defer f.Close() if hasDynTag(t, f, elf.DT_TEXTREL) { t.Errorf("%s has DT_TEXTREL flag", "testp"+exeSuffix) } } } func hasDynTag(t *testing.T, f *elf.File, tag elf.DynTag) bool { ds := f.SectionByType(elf.SHT_DYNAMIC) if ds == nil { t.Error("no SHT_DYNAMIC section") return false } d, err := ds.Data() if err != nil { t.Errorf("can't read SHT_DYNAMIC contents: %v", err) return false } for len(d) > 0 { var t elf.DynTag switch f.Class { case elf.ELFCLASS32: t = elf.DynTag(f.ByteOrder.Uint32(d[:4])) d = d[8:] case elf.ELFCLASS64: t = elf.DynTag(f.ByteOrder.Uint64(d[:8])) d = d[16:] } if t == tag { return true } } return false } func TestSIGPROF(t *testing.T) { switch GOOS { case "windows", "plan9": t.Skipf("skipping SIGPROF test on %s", GOOS) case "darwin", "ios": t.Skipf("skipping SIGPROF test on %s; see https://golang.org/issue/19320", GOOS) } globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") t.Parallel() if !testWork { defer func() { os.Remove("testp6" + exeSuffix) os.Remove("libgo6.a") os.Remove("libgo6.h") }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo6.a", "./libgo6") out, err := cmd.CombinedOutput() t.Logf("%v\n%s", cmd.Args, out) if err != nil { t.Fatal(err) } checkLineComments(t, "libgo6.h") checkArchive(t, "libgo6.a") ccArgs := append(cc, "-o", "testp6"+exeSuffix, "main6.c", "libgo6.a") if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", ccArgs, out) if err != nil { t.Fatal(err) } argv := cmdToRun("./testp6") cmd = exec.Command(argv[0], argv[1:]...) out, err = cmd.CombinedOutput() t.Logf("%v\n%s", argv, out) if err != nil { t.Fatal(err) } } // TestCompileWithoutShared tests that if we compile code without the // -shared option, we can put it into an archive. When we use the go // tool with -buildmode=c-archive, it passes -shared to the compiler, // so we override that. The go tool doesn't work this way, but Bazel // will likely do it in the future. And it ought to work. This test // was added because at one time it did not work on PPC Linux. func TestCompileWithoutShared(t *testing.T) { globalSkip(t) // For simplicity, reuse the signal forwarding test. checkSignalForwardingTest(t) testenv.MustHaveGoBuild(t) if !testWork { defer func() { os.Remove("libgo2.a") os.Remove("libgo2.h") }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-gcflags=-shared=false", "-o", "libgo2.a", "./libgo2") out, err := cmd.CombinedOutput() t.Logf("%v\n%s", cmd.Args, out) if err != nil { t.Fatal(err) } checkLineComments(t, "libgo2.h") checkArchive(t, "libgo2.a") exe := "./testnoshared" + exeSuffix // In some cases, -no-pie is needed here, but not accepted everywhere. First try // if -no-pie is accepted. See #22126. ccArgs := append(cc, "-o", exe, "-no-pie", "main5.c", "libgo2.a") if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", ccArgs, out) // If -no-pie unrecognized, try -nopie if this is possibly clang if err != nil && bytes.Contains(out, []byte("unknown")) && !strings.Contains(cc[0], "gcc") { ccArgs = append(cc, "-o", exe, "-nopie", "main5.c", "libgo2.a") out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", ccArgs, out) } // Don't use either -no-pie or -nopie if err != nil && bytes.Contains(out, []byte("unrecognized")) { ccArgs = append(cc, "-o", exe, "main5.c", "libgo2.a") out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", ccArgs, out) } if err != nil { t.Fatal(err) } if !testWork { defer os.Remove(exe) } binArgs := append(cmdToRun(exe), "1") out, err = exec.Command(binArgs[0], binArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", binArgs, out) expectSignal(t, err, syscall.SIGSEGV, 0) // SIGPIPE is never forwarded on darwin. See golang.org/issue/33384. if runtime.GOOS != "darwin" && runtime.GOOS != "ios" { binArgs := append(cmdToRun(exe), "3") out, err = exec.Command(binArgs[0], binArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", binArgs, out) expectSignal(t, err, syscall.SIGPIPE, 0) } } // Test that installing a second time recreates the header file. func TestCachedInstall(t *testing.T) { globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") if !testWork { defer os.RemoveAll(filepath.Join(GOPATH, "pkg")) } h := filepath.Join(libgodir, "libgo.h") buildcmd := []string{"go", "install", "-buildmode=c-archive", "./libgo"} cmd := exec.Command(buildcmd[0], buildcmd[1:]...) cmd.Env = append(cmd.Environ(), "GO111MODULE=off") // 'go install' only works in GOPATH mode t.Log(buildcmd) if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } if _, err := os.Stat(h); err != nil { t.Errorf("libgo.h not installed: %v", err) } if err := os.Remove(h); err != nil { t.Fatal(err) } cmd = exec.Command(buildcmd[0], buildcmd[1:]...) cmd.Env = append(cmd.Environ(), "GO111MODULE=off") t.Log(buildcmd) if out, err := cmd.CombinedOutput(); err != nil { t.Logf("%s", out) t.Fatal(err) } if _, err := os.Stat(h); err != nil { t.Errorf("libgo.h not installed in second run: %v", err) } } // Issue 35294. func TestManyCalls(t *testing.T) { globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") t.Parallel() if !testWork { defer func() { os.Remove("testp7" + exeSuffix) os.Remove("libgo7.a") os.Remove("libgo7.h") }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo7.a", "./libgo7") out, err := cmd.CombinedOutput() t.Logf("%v\n%s", cmd.Args, out) if err != nil { t.Fatal(err) } checkLineComments(t, "libgo7.h") checkArchive(t, "libgo7.a") ccArgs := append(cc, "-o", "testp7"+exeSuffix, "main7.c", "libgo7.a") if runtime.Compiler == "gccgo" { ccArgs = append(ccArgs, "-lgo") } out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", ccArgs, out) if err != nil { t.Fatal(err) } argv := cmdToRun("./testp7") cmd = testenv.Command(t, argv[0], argv[1:]...) sb := new(strings.Builder) cmd.Stdout = sb cmd.Stderr = sb if err := cmd.Start(); err != nil { t.Fatal(err) } err = cmd.Wait() t.Logf("%v\n%s", cmd.Args, sb) if err != nil { t.Error(err) } } // Issue 49288. func TestPreemption(t *testing.T) { if runtime.Compiler == "gccgo" { t.Skip("skipping asynchronous preemption test with gccgo") } globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") t.Parallel() if !testWork { defer func() { os.Remove("testp8" + exeSuffix) os.Remove("libgo8.a") os.Remove("libgo8.h") }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo8.a", "./libgo8") out, err := cmd.CombinedOutput() t.Logf("%v\n%s", cmd.Args, out) if err != nil { t.Fatal(err) } checkLineComments(t, "libgo8.h") checkArchive(t, "libgo8.a") ccArgs := append(cc, "-o", "testp8"+exeSuffix, "main8.c", "libgo8.a") out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", ccArgs, out) if err != nil { t.Fatal(err) } argv := cmdToRun("./testp8") cmd = testenv.Command(t, argv[0], argv[1:]...) sb := new(strings.Builder) cmd.Stdout = sb cmd.Stderr = sb if err := cmd.Start(); err != nil { t.Fatal(err) } err = cmd.Wait() t.Logf("%v\n%s", cmd.Args, sb) if err != nil { t.Error(err) } } // Issue 59294. Test calling Go function from C after using some // stack space. func TestDeepStack(t *testing.T) { globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") t.Parallel() if !testWork { defer func() { os.Remove("testp9" + exeSuffix) os.Remove("libgo9.a") os.Remove("libgo9.h") }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo9.a", "./libgo9") out, err := cmd.CombinedOutput() t.Logf("%v\n%s", cmd.Args, out) if err != nil { t.Fatal(err) } checkLineComments(t, "libgo9.h") checkArchive(t, "libgo9.a") // build with -O0 so the C compiler won't optimize out the large stack frame ccArgs := append(cc, "-O0", "-o", "testp9"+exeSuffix, "main9.c", "libgo9.a") out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", ccArgs, out) if err != nil { t.Fatal(err) } argv := cmdToRun("./testp9") cmd = exec.Command(argv[0], argv[1:]...) sb := new(strings.Builder) cmd.Stdout = sb cmd.Stderr = sb if err := cmd.Start(); err != nil { t.Fatal(err) } timer := time.AfterFunc(time.Minute, func() { t.Error("test program timed out") cmd.Process.Kill() }, ) defer timer.Stop() err = cmd.Wait() t.Logf("%v\n%s", cmd.Args, sb) if err != nil { t.Error(err) } } func TestSharedObject(t *testing.T) { // Test that we can put a Go c-archive into a C shared object. globalSkip(t) testenv.MustHaveGoBuild(t) testenv.MustHaveCGO(t) testenv.MustHaveBuildMode(t, "c-archive") t.Parallel() if !testWork { defer func() { os.Remove("libgo_s.a") os.Remove("libgo_s.h") os.Remove("libgo_s.so") }() } cmd := exec.Command("go", "build", "-buildmode=c-archive", "-o", "libgo_s.a", "./libgo") out, err := cmd.CombinedOutput() t.Logf("%v\n%s", cmd.Args, out) if err != nil { t.Fatal(err) } ccArgs := append(cc, "-shared", "-o", "libgo_s.so", "libgo_s.a") out, err = exec.Command(ccArgs[0], ccArgs[1:]...).CombinedOutput() t.Logf("%v\n%s", ccArgs, out) if err != nil { t.Fatal(err) } }
go/src/cmd/cgo/internal/testcarchive/carchive_test.go/0
{ "file_path": "go/src/cmd/cgo/internal/testcarchive/carchive_test.go", "repo_id": "go", "token_count": 15106 }
73
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import "C" import ( "os" "os/signal" "syscall" "time" ) // The channel used to read SIGIO signals. var sigioChan chan os.Signal // CatchSIGIO starts catching SIGIO signals. // //export CatchSIGIO func CatchSIGIO() { sigioChan = make(chan os.Signal, 1) signal.Notify(sigioChan, syscall.SIGIO) } // ResetSIGIO stops catching SIGIO signals. // //export ResetSIGIO func ResetSIGIO() { signal.Reset(syscall.SIGIO) } // AwaitSIGIO blocks indefinitely until a SIGIO is reported. // //export AwaitSIGIO func AwaitSIGIO() { <-sigioChan } // SawSIGIO reports whether we saw a SIGIO within a brief pause. // //export SawSIGIO func SawSIGIO() bool { timer := time.NewTimer(100 * time.Millisecond) select { case <-sigioChan: timer.Stop() return true case <-timer.C: return false } } func main() { }
go/src/cmd/cgo/internal/testcshared/testdata/libgo5/libgo5.go/0
{ "file_path": "go/src/cmd/cgo/internal/testcshared/testdata/libgo5/libgo5.go", "repo_id": "go", "token_count": 371 }
74
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main /* // TODO(#56378): change back to "#cgo noescape noMatchedCFunction: no matched C function" in Go 1.23 // ERROR MESSAGE: #cgo noescape disabled until Go 1.23 #cgo noescape noMatchedCFunction */ import "C" func main() { }
go/src/cmd/cgo/internal/testerrors/testdata/notmatchedcfunction.go/0
{ "file_path": "go/src/cmd/cgo/internal/testerrors/testdata/notmatchedcfunction.go", "repo_id": "go", "token_count": 126 }
75
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package life_test import ( "bytes" "cmd/cgo/internal/cgotest" "internal/testenv" "log" "os" "os/exec" "path/filepath" "testing" ) func TestMain(m *testing.M) { log.SetFlags(log.Lshortfile) os.Exit(testMain(m)) } func testMain(m *testing.M) int { GOPATH, err := os.MkdirTemp("", "cgolife") if err != nil { log.Panic(err) } defer os.RemoveAll(GOPATH) os.Setenv("GOPATH", GOPATH) // Copy testdata into GOPATH/src/cgolife, along with a go.mod file // declaring the same path. modRoot := filepath.Join(GOPATH, "src", "cgolife") if err := cgotest.OverlayDir(modRoot, "testdata"); err != nil { log.Panic(err) } if err := os.Chdir(modRoot); err != nil { log.Panic(err) } os.Setenv("PWD", modRoot) if err := os.WriteFile("go.mod", []byte("module cgolife\n"), 0666); err != nil { log.Panic(err) } return m.Run() } // TestTestRun runs a test case for cgo //export. func TestTestRun(t *testing.T) { testenv.MustHaveGoRun(t) testenv.MustHaveCGO(t) cmd := exec.Command("go", "run", "main.go") got, err := cmd.CombinedOutput() if err != nil { t.Fatalf("%v: %s\n%s", cmd, err, got) } want, err := os.ReadFile("main.out") if err != nil { t.Fatal("reading golden output:", err) } if !bytes.Equal(got, want) { t.Errorf("'%v' output does not match expected in main.out. Instead saw:\n%s", cmd, got) } }
go/src/cmd/cgo/internal/testlife/life_test.go/0
{ "file_path": "go/src/cmd/cgo/internal/testlife/life_test.go", "repo_id": "go", "token_count": 625 }
76
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build ignore package main import ( "log" "plugin" ) func main() { p, err := plugin.Open("issue.22295.so") if err != nil { log.Fatal(err) } f, err := p.Lookup("F") if err != nil { log.Fatal(err) } const want = 2503 got := f.(func() int)() if got != want { log.Fatalf("got %d, want %d", got, want) } }
go/src/cmd/cgo/internal/testplugin/testdata/issue22295.pkg/main.go/0
{ "file_path": "go/src/cmd/cgo/internal/testplugin/testdata/issue22295.pkg/main.go", "repo_id": "go", "token_count": 193 }
77
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Issue 62430: a program that uses plugins may appear // to have no references to an initialized global map variable defined // in some stdlib package (ex: unicode), however there // may be references to that map var from a plugin that // gets loaded. package main import ( "fmt" "plugin" "unicode" ) func main() { p, err := plugin.Open("issue62430.so") if err != nil { panic(err) } s, err := p.Lookup("F") if err != nil { panic(err) } f := s.(func(string) *unicode.RangeTable) if f("C") == nil { panic("unicode.Categories not properly initialized") } else { fmt.Println("unicode.Categories properly initialized") } }
go/src/cmd/cgo/internal/testplugin/testdata/issue62430/main.go/0
{ "file_path": "go/src/cmd/cgo/internal/testplugin/testdata/issue62430/main.go", "repo_id": "go", "token_count": 267 }
78
// Copyright 2022 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "fmt" "unsafe" ) var intGlo int func main() { r := bar(&intGlo) fmt.Printf("r value is %d", r) } func bar(a *int) int { p := (*int)(unsafe.Add(unsafe.Pointer(a), 1*unsafe.Sizeof(int(1)))) if *p == 10 { // BOOM fmt.Println("its value is 10") } return *p }
go/src/cmd/cgo/internal/testsanitizers/testdata/asan_global4_fail.go/0
{ "file_path": "go/src/cmd/cgo/internal/testsanitizers/testdata/asan_global4_fail.go", "repo_id": "go", "token_count": 181 }
79
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main // Using reflect to set a value was not seen by msan. /* #include <stdlib.h> extern void Go1(int*); extern void Go2(char*); // Use weak as a hack to permit defining a function even though we use export. void C1() __attribute__ ((weak)); void C2() __attribute__ ((weak)); void C1() { int i; Go1(&i); if (i != 42) { abort(); } } void C2() { char a[2]; a[1] = 42; Go2(a); if (a[0] != 42) { abort(); } } */ import "C" import ( "reflect" "unsafe" ) //export Go1 func Go1(p *C.int) { reflect.ValueOf(p).Elem().Set(reflect.ValueOf(C.int(42))) } //export Go2 func Go2(p *C.char) { a := (*[2]byte)(unsafe.Pointer(p)) reflect.Copy(reflect.ValueOf(a[:1]), reflect.ValueOf(a[1:])) } func main() { C.C1() C.C2() }
go/src/cmd/cgo/internal/testsanitizers/testdata/msan5.go/0
{ "file_path": "go/src/cmd/cgo/internal/testsanitizers/testdata/msan5.go", "repo_id": "go", "token_count": 381 }
80
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main // Check that calls to C.malloc/C.free do not collide with the calls // made by the os/user package. // #cgo CFLAGS: -fsanitize=thread // #cgo LDFLAGS: -fsanitize=thread // #include <stdlib.h> import "C" import ( "fmt" "os" "os/user" "runtime" "sync" ) func main() { u, err := user.Current() if err != nil { fmt.Fprintln(os.Stderr, err) // Let the test pass. os.Exit(0) } var wg sync.WaitGroup for i := 0; i < 20; i++ { wg.Add(2) go func() { defer wg.Done() for i := 0; i < 1000; i++ { user.Lookup(u.Username) runtime.Gosched() } }() go func() { defer wg.Done() for i := 0; i < 1000; i++ { p := C.malloc(C.size_t(len(u.Username) + 1)) runtime.Gosched() C.free(p) } }() } wg.Wait() }
go/src/cmd/cgo/internal/testsanitizers/testdata/tsan5.go/0
{ "file_path": "go/src/cmd/cgo/internal/testsanitizers/testdata/tsan5.go", "repo_id": "go", "token_count": 427 }
81
package main import ( "os" "reflect" "runtime" "testshared/depBase" ) // Having a function declared in the main package triggered // golang.org/issue/18250 func DeclaredInMain() { } type C struct { } func F() *C { return nil } var slicePtr interface{} = &[]int{} func main() { defer depBase.ImplementedInAsm() // This code below causes various go.itab.* symbols to be generated in // the executable. Similar code in ../depBase/dep.go results in // exercising https://golang.org/issues/17594 reflect.TypeOf(os.Stdout).Elem() runtime.GC() depBase.V = depBase.F() + 1 var c *C if reflect.TypeOf(F).Out(0) != reflect.TypeOf(c) { panic("bad reflection results, see golang.org/issue/18252") } sp := reflect.New(reflect.TypeOf(slicePtr).Elem()) s := sp.Interface() if reflect.TypeOf(s) != reflect.TypeOf(slicePtr) { panic("bad reflection results, see golang.org/issue/18729") } }
go/src/cmd/cgo/internal/testshared/testdata/exe/exe.go/0
{ "file_path": "go/src/cmd/cgo/internal/testshared/testdata/exe/exe.go", "repo_id": "go", "token_count": 335 }
82
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package issue30768lib // S is a struct that requires a generated hash function. type S struct { A string B int }
go/src/cmd/cgo/internal/testshared/testdata/issue30768/issue30768lib/lib.go/0
{ "file_path": "go/src/cmd/cgo/internal/testshared/testdata/issue30768/issue30768lib/lib.go", "repo_id": "go", "token_count": 76 }
83
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build ignore #ifdef WIN32 // A Windows DLL is unable to call an arbitrary function in // the main executable. Work around that by making the main // executable pass the callback function pointer to us. void (*goCallback)(void); __declspec(dllexport) void setCallback(void *f) { goCallback = (void (*)())f; } __declspec(dllexport) void sofunc(void); #elif defined(_AIX) // AIX doesn't allow the creation of a shared object with an // undefined symbol. It's possible to bypass this problem by // using -Wl,-G and -Wl,-brtl option which allows run-time linking. // However, that's not how most of AIX shared object works. // Therefore, it's better to consider goCallback as a pointer and // to set up during an init function. void (*goCallback)(void); void setCallback(void *f) { goCallback = f; } #else extern void goCallback(void); void setCallback(void *f) { (void)f; } #endif // OpenBSD and older Darwin lack TLS support #if !defined(__OpenBSD__) && !defined(__APPLE__) __thread int tlsvar = 12345; #endif void sofunc(void) { goCallback(); }
go/src/cmd/cgo/internal/testso/testdata/so/cgoso_c.c/0
{ "file_path": "go/src/cmd/cgo/internal/testso/testdata/so/cgoso_c.c", "repo_id": "go", "token_count": 366 }
84
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <stddef.h> #if __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) // Mingw seems not to have threads.h, so we use the _Thread_local keyword rather // than the thread_local macro. static _Thread_local int tls; const char * checkTLS() { return NULL; } void setTLS(int v) { tls = v; } int getTLS() { return tls; } #else const char * checkTLS() { return "_Thread_local requires C11 and not __STDC_NO_THREADS__"; } void setTLS(int v) { } int getTLS() { return 0; } #endif
go/src/cmd/cgo/internal/testtls/tls.c/0
{ "file_path": "go/src/cmd/cgo/internal/testtls/tls.c", "repo_id": "go", "token_count": 255 }
85
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package amd64 import ( "fmt" "internal/buildcfg" "math" "cmd/compile/internal/base" "cmd/compile/internal/ir" "cmd/compile/internal/logopt" "cmd/compile/internal/objw" "cmd/compile/internal/ssa" "cmd/compile/internal/ssagen" "cmd/compile/internal/types" "cmd/internal/obj" "cmd/internal/obj/x86" ) // ssaMarkMoves marks any MOVXconst ops that need to avoid clobbering flags. func ssaMarkMoves(s *ssagen.State, b *ssa.Block) { flive := b.FlagsLiveAtEnd for _, c := range b.ControlValues() { flive = c.Type.IsFlags() || flive } for i := len(b.Values) - 1; i >= 0; i-- { v := b.Values[i] if flive && (v.Op == ssa.OpAMD64MOVLconst || v.Op == ssa.OpAMD64MOVQconst) { // The "mark" is any non-nil Aux value. v.Aux = ssa.AuxMark } if v.Type.IsFlags() { flive = false } for _, a := range v.Args { if a.Type.IsFlags() { flive = true } } } } // loadByType returns the load instruction of the given type. func loadByType(t *types.Type) obj.As { // Avoid partial register write if !t.IsFloat() { switch t.Size() { case 1: return x86.AMOVBLZX case 2: return x86.AMOVWLZX } } // Otherwise, there's no difference between load and store opcodes. return storeByType(t) } // storeByType returns the store instruction of the given type. func storeByType(t *types.Type) obj.As { width := t.Size() if t.IsFloat() { switch width { case 4: return x86.AMOVSS case 8: return x86.AMOVSD } } else { switch width { case 1: return x86.AMOVB case 2: return x86.AMOVW case 4: return x86.AMOVL case 8: return x86.AMOVQ case 16: return x86.AMOVUPS } } panic(fmt.Sprintf("bad store type %v", t)) } // moveByType returns the reg->reg move instruction of the given type. func moveByType(t *types.Type) obj.As { if t.IsFloat() { // Moving the whole sse2 register is faster // than moving just the correct low portion of it. // There is no xmm->xmm move with 1 byte opcode, // so use movups, which has 2 byte opcode. return x86.AMOVUPS } else { switch t.Size() { case 1: // Avoids partial register write return x86.AMOVL case 2: return x86.AMOVL case 4: return x86.AMOVL case 8: return x86.AMOVQ case 16: return x86.AMOVUPS // int128s are in SSE registers default: panic(fmt.Sprintf("bad int register width %d:%v", t.Size(), t)) } } } // opregreg emits instructions for // // dest := dest(To) op src(From) // // and also returns the created obj.Prog so it // may be further adjusted (offset, scale, etc). func opregreg(s *ssagen.State, op obj.As, dest, src int16) *obj.Prog { p := s.Prog(op) p.From.Type = obj.TYPE_REG p.To.Type = obj.TYPE_REG p.To.Reg = dest p.From.Reg = src return p } // memIdx fills out a as an indexed memory reference for v. // It assumes that the base register and the index register // are v.Args[0].Reg() and v.Args[1].Reg(), respectively. // The caller must still use gc.AddAux/gc.AddAux2 to handle v.Aux as necessary. func memIdx(a *obj.Addr, v *ssa.Value) { r, i := v.Args[0].Reg(), v.Args[1].Reg() a.Type = obj.TYPE_MEM a.Scale = v.Op.Scale() if a.Scale == 1 && i == x86.REG_SP { r, i = i, r } a.Reg = r a.Index = i } // DUFFZERO consists of repeated blocks of 4 MOVUPSs + LEAQ, // See runtime/mkduff.go. func duffStart(size int64) int64 { x, _ := duff(size) return x } func duffAdj(size int64) int64 { _, x := duff(size) return x } // duff returns the offset (from duffzero, in bytes) and pointer adjust (in bytes) // required to use the duffzero mechanism for a block of the given size. func duff(size int64) (int64, int64) { if size < 32 || size > 1024 || size%dzClearStep != 0 { panic("bad duffzero size") } steps := size / dzClearStep blocks := steps / dzBlockLen steps %= dzBlockLen off := dzBlockSize * (dzBlocks - blocks) var adj int64 if steps != 0 { off -= dzLeaqSize off -= dzMovSize * steps adj -= dzClearStep * (dzBlockLen - steps) } return off, adj } func getgFromTLS(s *ssagen.State, r int16) { // See the comments in cmd/internal/obj/x86/obj6.go // near CanUse1InsnTLS for a detailed explanation of these instructions. if x86.CanUse1InsnTLS(base.Ctxt) { // MOVQ (TLS), r p := s.Prog(x86.AMOVQ) p.From.Type = obj.TYPE_MEM p.From.Reg = x86.REG_TLS p.To.Type = obj.TYPE_REG p.To.Reg = r } else { // MOVQ TLS, r // MOVQ (r)(TLS*1), r p := s.Prog(x86.AMOVQ) p.From.Type = obj.TYPE_REG p.From.Reg = x86.REG_TLS p.To.Type = obj.TYPE_REG p.To.Reg = r q := s.Prog(x86.AMOVQ) q.From.Type = obj.TYPE_MEM q.From.Reg = r q.From.Index = x86.REG_TLS q.From.Scale = 1 q.To.Type = obj.TYPE_REG q.To.Reg = r } } func ssaGenValue(s *ssagen.State, v *ssa.Value) { switch v.Op { case ssa.OpAMD64VFMADD231SD: p := s.Prog(v.Op.Asm()) p.From = obj.Addr{Type: obj.TYPE_REG, Reg: v.Args[2].Reg()} p.To = obj.Addr{Type: obj.TYPE_REG, Reg: v.Reg()} p.AddRestSourceReg(v.Args[1].Reg()) case ssa.OpAMD64ADDQ, ssa.OpAMD64ADDL: r := v.Reg() r1 := v.Args[0].Reg() r2 := v.Args[1].Reg() switch { case r == r1: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = r2 p.To.Type = obj.TYPE_REG p.To.Reg = r case r == r2: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = r1 p.To.Type = obj.TYPE_REG p.To.Reg = r default: var asm obj.As if v.Op == ssa.OpAMD64ADDQ { asm = x86.ALEAQ } else { asm = x86.ALEAL } p := s.Prog(asm) p.From.Type = obj.TYPE_MEM p.From.Reg = r1 p.From.Scale = 1 p.From.Index = r2 p.To.Type = obj.TYPE_REG p.To.Reg = r } // 2-address opcode arithmetic case ssa.OpAMD64SUBQ, ssa.OpAMD64SUBL, ssa.OpAMD64MULQ, ssa.OpAMD64MULL, ssa.OpAMD64ANDQ, ssa.OpAMD64ANDL, ssa.OpAMD64ORQ, ssa.OpAMD64ORL, ssa.OpAMD64XORQ, ssa.OpAMD64XORL, ssa.OpAMD64SHLQ, ssa.OpAMD64SHLL, ssa.OpAMD64SHRQ, ssa.OpAMD64SHRL, ssa.OpAMD64SHRW, ssa.OpAMD64SHRB, ssa.OpAMD64SARQ, ssa.OpAMD64SARL, ssa.OpAMD64SARW, ssa.OpAMD64SARB, ssa.OpAMD64ROLQ, ssa.OpAMD64ROLL, ssa.OpAMD64ROLW, ssa.OpAMD64ROLB, ssa.OpAMD64RORQ, ssa.OpAMD64RORL, ssa.OpAMD64RORW, ssa.OpAMD64RORB, ssa.OpAMD64ADDSS, ssa.OpAMD64ADDSD, ssa.OpAMD64SUBSS, ssa.OpAMD64SUBSD, ssa.OpAMD64MULSS, ssa.OpAMD64MULSD, ssa.OpAMD64DIVSS, ssa.OpAMD64DIVSD, ssa.OpAMD64MINSS, ssa.OpAMD64MINSD, ssa.OpAMD64POR, ssa.OpAMD64PXOR, ssa.OpAMD64BTSL, ssa.OpAMD64BTSQ, ssa.OpAMD64BTCL, ssa.OpAMD64BTCQ, ssa.OpAMD64BTRL, ssa.OpAMD64BTRQ: opregreg(s, v.Op.Asm(), v.Reg(), v.Args[1].Reg()) case ssa.OpAMD64SHRDQ, ssa.OpAMD64SHLDQ: p := s.Prog(v.Op.Asm()) lo, hi, bits := v.Args[0].Reg(), v.Args[1].Reg(), v.Args[2].Reg() p.From.Type = obj.TYPE_REG p.From.Reg = bits p.To.Type = obj.TYPE_REG p.To.Reg = lo p.AddRestSourceReg(hi) case ssa.OpAMD64BLSIQ, ssa.OpAMD64BLSIL, ssa.OpAMD64BLSMSKQ, ssa.OpAMD64BLSMSKL, ssa.OpAMD64BLSRQ, ssa.OpAMD64BLSRL: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[0].Reg() p.To.Type = obj.TYPE_REG switch v.Op { case ssa.OpAMD64BLSRQ, ssa.OpAMD64BLSRL: p.To.Reg = v.Reg0() default: p.To.Reg = v.Reg() } case ssa.OpAMD64ANDNQ, ssa.OpAMD64ANDNL: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[0].Reg() p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() p.AddRestSourceReg(v.Args[1].Reg()) case ssa.OpAMD64SARXL, ssa.OpAMD64SARXQ, ssa.OpAMD64SHLXL, ssa.OpAMD64SHLXQ, ssa.OpAMD64SHRXL, ssa.OpAMD64SHRXQ: p := opregreg(s, v.Op.Asm(), v.Reg(), v.Args[1].Reg()) p.AddRestSourceReg(v.Args[0].Reg()) case ssa.OpAMD64SHLXLload, ssa.OpAMD64SHLXQload, ssa.OpAMD64SHRXLload, ssa.OpAMD64SHRXQload, ssa.OpAMD64SARXLload, ssa.OpAMD64SARXQload: p := opregreg(s, v.Op.Asm(), v.Reg(), v.Args[1].Reg()) m := obj.Addr{Type: obj.TYPE_MEM, Reg: v.Args[0].Reg()} ssagen.AddAux(&m, v) p.AddRestSource(m) case ssa.OpAMD64SHLXLloadidx1, ssa.OpAMD64SHLXLloadidx4, ssa.OpAMD64SHLXLloadidx8, ssa.OpAMD64SHRXLloadidx1, ssa.OpAMD64SHRXLloadidx4, ssa.OpAMD64SHRXLloadidx8, ssa.OpAMD64SARXLloadidx1, ssa.OpAMD64SARXLloadidx4, ssa.OpAMD64SARXLloadidx8, ssa.OpAMD64SHLXQloadidx1, ssa.OpAMD64SHLXQloadidx8, ssa.OpAMD64SHRXQloadidx1, ssa.OpAMD64SHRXQloadidx8, ssa.OpAMD64SARXQloadidx1, ssa.OpAMD64SARXQloadidx8: p := opregreg(s, v.Op.Asm(), v.Reg(), v.Args[2].Reg()) m := obj.Addr{Type: obj.TYPE_MEM} memIdx(&m, v) ssagen.AddAux(&m, v) p.AddRestSource(m) case ssa.OpAMD64DIVQU, ssa.OpAMD64DIVLU, ssa.OpAMD64DIVWU: // Arg[0] (the dividend) is in AX. // Arg[1] (the divisor) can be in any other register. // Result[0] (the quotient) is in AX. // Result[1] (the remainder) is in DX. r := v.Args[1].Reg() // Zero extend dividend. opregreg(s, x86.AXORL, x86.REG_DX, x86.REG_DX) // Issue divide. p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = r case ssa.OpAMD64DIVQ, ssa.OpAMD64DIVL, ssa.OpAMD64DIVW: // Arg[0] (the dividend) is in AX. // Arg[1] (the divisor) can be in any other register. // Result[0] (the quotient) is in AX. // Result[1] (the remainder) is in DX. r := v.Args[1].Reg() var opCMP, opNEG, opSXD obj.As switch v.Op { case ssa.OpAMD64DIVQ: opCMP, opNEG, opSXD = x86.ACMPQ, x86.ANEGQ, x86.ACQO case ssa.OpAMD64DIVL: opCMP, opNEG, opSXD = x86.ACMPL, x86.ANEGL, x86.ACDQ case ssa.OpAMD64DIVW: opCMP, opNEG, opSXD = x86.ACMPW, x86.ANEGW, x86.ACWD } // CPU faults upon signed overflow, which occurs when the most // negative int is divided by -1. Handle divide by -1 as a special case. var j1, j2 *obj.Prog if ssa.DivisionNeedsFixUp(v) { c := s.Prog(opCMP) c.From.Type = obj.TYPE_REG c.From.Reg = r c.To.Type = obj.TYPE_CONST c.To.Offset = -1 // Divisor is not -1, proceed with normal division. j1 = s.Prog(x86.AJNE) j1.To.Type = obj.TYPE_BRANCH // Divisor is -1, manually compute quotient and remainder via fixup code. // n / -1 = -n n1 := s.Prog(opNEG) n1.To.Type = obj.TYPE_REG n1.To.Reg = x86.REG_AX // n % -1 == 0 opregreg(s, x86.AXORL, x86.REG_DX, x86.REG_DX) // TODO(khr): issue only the -1 fixup code we need. // For instance, if only the quotient is used, no point in zeroing the remainder. // Skip over normal division. j2 = s.Prog(obj.AJMP) j2.To.Type = obj.TYPE_BRANCH } // Sign extend dividend and perform division. p := s.Prog(opSXD) if j1 != nil { j1.To.SetTarget(p) } p = s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = r if j2 != nil { j2.To.SetTarget(s.Pc()) } case ssa.OpAMD64HMULQ, ssa.OpAMD64HMULL, ssa.OpAMD64HMULQU, ssa.OpAMD64HMULLU: // the frontend rewrites constant division by 8/16/32 bit integers into // HMUL by a constant // SSA rewrites generate the 64 bit versions // Arg[0] is already in AX as it's the only register we allow // and DX is the only output we care about (the high bits) p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[1].Reg() // IMULB puts the high portion in AH instead of DL, // so move it to DL for consistency if v.Type.Size() == 1 { m := s.Prog(x86.AMOVB) m.From.Type = obj.TYPE_REG m.From.Reg = x86.REG_AH m.To.Type = obj.TYPE_REG m.To.Reg = x86.REG_DX } case ssa.OpAMD64MULQU, ssa.OpAMD64MULLU: // Arg[0] is already in AX as it's the only register we allow // results lo in AX p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[1].Reg() case ssa.OpAMD64MULQU2: // Arg[0] is already in AX as it's the only register we allow // results hi in DX, lo in AX p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[1].Reg() case ssa.OpAMD64DIVQU2: // Arg[0], Arg[1] are already in Dx, AX, as they're the only registers we allow // results q in AX, r in DX p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[2].Reg() case ssa.OpAMD64AVGQU: // compute (x+y)/2 unsigned. // Do a 64-bit add, the overflow goes into the carry. // Shift right once and pull the carry back into the 63rd bit. p := s.Prog(x86.AADDQ) p.From.Type = obj.TYPE_REG p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() p.From.Reg = v.Args[1].Reg() p = s.Prog(x86.ARCRQ) p.From.Type = obj.TYPE_CONST p.From.Offset = 1 p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64ADDQcarry, ssa.OpAMD64ADCQ: r := v.Reg0() r0 := v.Args[0].Reg() r1 := v.Args[1].Reg() switch r { case r0: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = r1 p.To.Type = obj.TYPE_REG p.To.Reg = r case r1: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = r0 p.To.Type = obj.TYPE_REG p.To.Reg = r default: v.Fatalf("output not in same register as an input %s", v.LongString()) } case ssa.OpAMD64SUBQborrow, ssa.OpAMD64SBBQ: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[1].Reg() p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg0() case ssa.OpAMD64ADDQconstcarry, ssa.OpAMD64ADCQconst, ssa.OpAMD64SUBQconstborrow, ssa.OpAMD64SBBQconst: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_CONST p.From.Offset = v.AuxInt p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg0() case ssa.OpAMD64ADDQconst, ssa.OpAMD64ADDLconst: r := v.Reg() a := v.Args[0].Reg() if r == a { switch v.AuxInt { case 1: var asm obj.As // Software optimization manual recommends add $1,reg. // But inc/dec is 1 byte smaller. ICC always uses inc // Clang/GCC choose depending on flags, but prefer add. // Experiments show that inc/dec is both a little faster // and make a binary a little smaller. if v.Op == ssa.OpAMD64ADDQconst { asm = x86.AINCQ } else { asm = x86.AINCL } p := s.Prog(asm) p.To.Type = obj.TYPE_REG p.To.Reg = r return case -1: var asm obj.As if v.Op == ssa.OpAMD64ADDQconst { asm = x86.ADECQ } else { asm = x86.ADECL } p := s.Prog(asm) p.To.Type = obj.TYPE_REG p.To.Reg = r return case 0x80: // 'SUBQ $-0x80, r' is shorter to encode than // and functionally equivalent to 'ADDQ $0x80, r'. asm := x86.ASUBL if v.Op == ssa.OpAMD64ADDQconst { asm = x86.ASUBQ } p := s.Prog(asm) p.From.Type = obj.TYPE_CONST p.From.Offset = -0x80 p.To.Type = obj.TYPE_REG p.To.Reg = r return } p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_CONST p.From.Offset = v.AuxInt p.To.Type = obj.TYPE_REG p.To.Reg = r return } var asm obj.As if v.Op == ssa.OpAMD64ADDQconst { asm = x86.ALEAQ } else { asm = x86.ALEAL } p := s.Prog(asm) p.From.Type = obj.TYPE_MEM p.From.Reg = a p.From.Offset = v.AuxInt p.To.Type = obj.TYPE_REG p.To.Reg = r case ssa.OpAMD64CMOVQEQ, ssa.OpAMD64CMOVLEQ, ssa.OpAMD64CMOVWEQ, ssa.OpAMD64CMOVQLT, ssa.OpAMD64CMOVLLT, ssa.OpAMD64CMOVWLT, ssa.OpAMD64CMOVQNE, ssa.OpAMD64CMOVLNE, ssa.OpAMD64CMOVWNE, ssa.OpAMD64CMOVQGT, ssa.OpAMD64CMOVLGT, ssa.OpAMD64CMOVWGT, ssa.OpAMD64CMOVQLE, ssa.OpAMD64CMOVLLE, ssa.OpAMD64CMOVWLE, ssa.OpAMD64CMOVQGE, ssa.OpAMD64CMOVLGE, ssa.OpAMD64CMOVWGE, ssa.OpAMD64CMOVQHI, ssa.OpAMD64CMOVLHI, ssa.OpAMD64CMOVWHI, ssa.OpAMD64CMOVQLS, ssa.OpAMD64CMOVLLS, ssa.OpAMD64CMOVWLS, ssa.OpAMD64CMOVQCC, ssa.OpAMD64CMOVLCC, ssa.OpAMD64CMOVWCC, ssa.OpAMD64CMOVQCS, ssa.OpAMD64CMOVLCS, ssa.OpAMD64CMOVWCS, ssa.OpAMD64CMOVQGTF, ssa.OpAMD64CMOVLGTF, ssa.OpAMD64CMOVWGTF, ssa.OpAMD64CMOVQGEF, ssa.OpAMD64CMOVLGEF, ssa.OpAMD64CMOVWGEF: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[1].Reg() p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64CMOVQNEF, ssa.OpAMD64CMOVLNEF, ssa.OpAMD64CMOVWNEF: // Flag condition: ^ZERO || PARITY // Generate: // CMOV*NE SRC,DST // CMOV*PS SRC,DST p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[1].Reg() p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() var q *obj.Prog if v.Op == ssa.OpAMD64CMOVQNEF { q = s.Prog(x86.ACMOVQPS) } else if v.Op == ssa.OpAMD64CMOVLNEF { q = s.Prog(x86.ACMOVLPS) } else { q = s.Prog(x86.ACMOVWPS) } q.From.Type = obj.TYPE_REG q.From.Reg = v.Args[1].Reg() q.To.Type = obj.TYPE_REG q.To.Reg = v.Reg() case ssa.OpAMD64CMOVQEQF, ssa.OpAMD64CMOVLEQF, ssa.OpAMD64CMOVWEQF: // Flag condition: ZERO && !PARITY // Generate: // MOV SRC,TMP // CMOV*NE DST,TMP // CMOV*PC TMP,DST // // TODO(rasky): we could generate: // CMOV*NE DST,SRC // CMOV*PC SRC,DST // But this requires a way for regalloc to know that SRC might be // clobbered by this instruction. t := v.RegTmp() opregreg(s, moveByType(v.Type), t, v.Args[1].Reg()) p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Reg() p.To.Type = obj.TYPE_REG p.To.Reg = t var q *obj.Prog if v.Op == ssa.OpAMD64CMOVQEQF { q = s.Prog(x86.ACMOVQPC) } else if v.Op == ssa.OpAMD64CMOVLEQF { q = s.Prog(x86.ACMOVLPC) } else { q = s.Prog(x86.ACMOVWPC) } q.From.Type = obj.TYPE_REG q.From.Reg = t q.To.Type = obj.TYPE_REG q.To.Reg = v.Reg() case ssa.OpAMD64MULQconst, ssa.OpAMD64MULLconst: r := v.Reg() p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_CONST p.From.Offset = v.AuxInt p.To.Type = obj.TYPE_REG p.To.Reg = r p.AddRestSourceReg(v.Args[0].Reg()) case ssa.OpAMD64ANDQconst: asm := v.Op.Asm() // If the constant is positive and fits into 32 bits, use ANDL. // This saves a few bytes of encoding. if 0 <= v.AuxInt && v.AuxInt <= (1<<32-1) { asm = x86.AANDL } p := s.Prog(asm) p.From.Type = obj.TYPE_CONST p.From.Offset = v.AuxInt p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64SUBQconst, ssa.OpAMD64SUBLconst, ssa.OpAMD64ANDLconst, ssa.OpAMD64ORQconst, ssa.OpAMD64ORLconst, ssa.OpAMD64XORQconst, ssa.OpAMD64XORLconst, ssa.OpAMD64SHLQconst, ssa.OpAMD64SHLLconst, ssa.OpAMD64SHRQconst, ssa.OpAMD64SHRLconst, ssa.OpAMD64SHRWconst, ssa.OpAMD64SHRBconst, ssa.OpAMD64SARQconst, ssa.OpAMD64SARLconst, ssa.OpAMD64SARWconst, ssa.OpAMD64SARBconst, ssa.OpAMD64ROLQconst, ssa.OpAMD64ROLLconst, ssa.OpAMD64ROLWconst, ssa.OpAMD64ROLBconst: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_CONST p.From.Offset = v.AuxInt p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64SBBQcarrymask, ssa.OpAMD64SBBLcarrymask: r := v.Reg() p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = r p.To.Type = obj.TYPE_REG p.To.Reg = r case ssa.OpAMD64LEAQ1, ssa.OpAMD64LEAQ2, ssa.OpAMD64LEAQ4, ssa.OpAMD64LEAQ8, ssa.OpAMD64LEAL1, ssa.OpAMD64LEAL2, ssa.OpAMD64LEAL4, ssa.OpAMD64LEAL8, ssa.OpAMD64LEAW1, ssa.OpAMD64LEAW2, ssa.OpAMD64LEAW4, ssa.OpAMD64LEAW8: p := s.Prog(v.Op.Asm()) memIdx(&p.From, v) o := v.Reg() p.To.Type = obj.TYPE_REG p.To.Reg = o if v.AuxInt != 0 && v.Aux == nil { // Emit an additional LEA to add the displacement instead of creating a slow 3 operand LEA. switch v.Op { case ssa.OpAMD64LEAQ1, ssa.OpAMD64LEAQ2, ssa.OpAMD64LEAQ4, ssa.OpAMD64LEAQ8: p = s.Prog(x86.ALEAQ) case ssa.OpAMD64LEAL1, ssa.OpAMD64LEAL2, ssa.OpAMD64LEAL4, ssa.OpAMD64LEAL8: p = s.Prog(x86.ALEAL) case ssa.OpAMD64LEAW1, ssa.OpAMD64LEAW2, ssa.OpAMD64LEAW4, ssa.OpAMD64LEAW8: p = s.Prog(x86.ALEAW) } p.From.Type = obj.TYPE_MEM p.From.Reg = o p.To.Type = obj.TYPE_REG p.To.Reg = o } ssagen.AddAux(&p.From, v) case ssa.OpAMD64LEAQ, ssa.OpAMD64LEAL, ssa.OpAMD64LEAW: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_MEM p.From.Reg = v.Args[0].Reg() ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64CMPQ, ssa.OpAMD64CMPL, ssa.OpAMD64CMPW, ssa.OpAMD64CMPB, ssa.OpAMD64TESTQ, ssa.OpAMD64TESTL, ssa.OpAMD64TESTW, ssa.OpAMD64TESTB, ssa.OpAMD64BTL, ssa.OpAMD64BTQ: opregreg(s, v.Op.Asm(), v.Args[1].Reg(), v.Args[0].Reg()) case ssa.OpAMD64UCOMISS, ssa.OpAMD64UCOMISD: // Go assembler has swapped operands for UCOMISx relative to CMP, // must account for that right here. opregreg(s, v.Op.Asm(), v.Args[0].Reg(), v.Args[1].Reg()) case ssa.OpAMD64CMPQconst, ssa.OpAMD64CMPLconst, ssa.OpAMD64CMPWconst, ssa.OpAMD64CMPBconst: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[0].Reg() p.To.Type = obj.TYPE_CONST p.To.Offset = v.AuxInt case ssa.OpAMD64BTLconst, ssa.OpAMD64BTQconst, ssa.OpAMD64TESTQconst, ssa.OpAMD64TESTLconst, ssa.OpAMD64TESTWconst, ssa.OpAMD64TESTBconst, ssa.OpAMD64BTSQconst, ssa.OpAMD64BTCQconst, ssa.OpAMD64BTRQconst: op := v.Op if op == ssa.OpAMD64BTQconst && v.AuxInt < 32 { // Emit 32-bit version because it's shorter op = ssa.OpAMD64BTLconst } p := s.Prog(op.Asm()) p.From.Type = obj.TYPE_CONST p.From.Offset = v.AuxInt p.To.Type = obj.TYPE_REG p.To.Reg = v.Args[0].Reg() case ssa.OpAMD64CMPQload, ssa.OpAMD64CMPLload, ssa.OpAMD64CMPWload, ssa.OpAMD64CMPBload: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_MEM p.From.Reg = v.Args[0].Reg() ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Args[1].Reg() case ssa.OpAMD64CMPQconstload, ssa.OpAMD64CMPLconstload, ssa.OpAMD64CMPWconstload, ssa.OpAMD64CMPBconstload: sc := v.AuxValAndOff() p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_MEM p.From.Reg = v.Args[0].Reg() ssagen.AddAux2(&p.From, v, sc.Off64()) p.To.Type = obj.TYPE_CONST p.To.Offset = sc.Val64() case ssa.OpAMD64CMPQloadidx8, ssa.OpAMD64CMPQloadidx1, ssa.OpAMD64CMPLloadidx4, ssa.OpAMD64CMPLloadidx1, ssa.OpAMD64CMPWloadidx2, ssa.OpAMD64CMPWloadidx1, ssa.OpAMD64CMPBloadidx1: p := s.Prog(v.Op.Asm()) memIdx(&p.From, v) ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Args[2].Reg() case ssa.OpAMD64CMPQconstloadidx8, ssa.OpAMD64CMPQconstloadidx1, ssa.OpAMD64CMPLconstloadidx4, ssa.OpAMD64CMPLconstloadidx1, ssa.OpAMD64CMPWconstloadidx2, ssa.OpAMD64CMPWconstloadidx1, ssa.OpAMD64CMPBconstloadidx1: sc := v.AuxValAndOff() p := s.Prog(v.Op.Asm()) memIdx(&p.From, v) ssagen.AddAux2(&p.From, v, sc.Off64()) p.To.Type = obj.TYPE_CONST p.To.Offset = sc.Val64() case ssa.OpAMD64MOVLconst, ssa.OpAMD64MOVQconst: x := v.Reg() // If flags aren't live (indicated by v.Aux == nil), // then we can rewrite MOV $0, AX into XOR AX, AX. if v.AuxInt == 0 && v.Aux == nil { opregreg(s, x86.AXORL, x, x) break } asm := v.Op.Asm() // Use MOVL to move a small constant into a register // when the constant is positive and fits into 32 bits. if 0 <= v.AuxInt && v.AuxInt <= (1<<32-1) { // The upper 32bit are zeroed automatically when using MOVL. asm = x86.AMOVL } p := s.Prog(asm) p.From.Type = obj.TYPE_CONST p.From.Offset = v.AuxInt p.To.Type = obj.TYPE_REG p.To.Reg = x case ssa.OpAMD64MOVSSconst, ssa.OpAMD64MOVSDconst: x := v.Reg() p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_FCONST p.From.Val = math.Float64frombits(uint64(v.AuxInt)) p.To.Type = obj.TYPE_REG p.To.Reg = x case ssa.OpAMD64MOVQload, ssa.OpAMD64MOVLload, ssa.OpAMD64MOVWload, ssa.OpAMD64MOVBload, ssa.OpAMD64MOVOload, ssa.OpAMD64MOVSSload, ssa.OpAMD64MOVSDload, ssa.OpAMD64MOVBQSXload, ssa.OpAMD64MOVWQSXload, ssa.OpAMD64MOVLQSXload, ssa.OpAMD64MOVBEQload, ssa.OpAMD64MOVBELload: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_MEM p.From.Reg = v.Args[0].Reg() ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64MOVBloadidx1, ssa.OpAMD64MOVWloadidx1, ssa.OpAMD64MOVLloadidx1, ssa.OpAMD64MOVQloadidx1, ssa.OpAMD64MOVSSloadidx1, ssa.OpAMD64MOVSDloadidx1, ssa.OpAMD64MOVQloadidx8, ssa.OpAMD64MOVSDloadidx8, ssa.OpAMD64MOVLloadidx8, ssa.OpAMD64MOVLloadidx4, ssa.OpAMD64MOVSSloadidx4, ssa.OpAMD64MOVWloadidx2, ssa.OpAMD64MOVBELloadidx1, ssa.OpAMD64MOVBELloadidx4, ssa.OpAMD64MOVBELloadidx8, ssa.OpAMD64MOVBEQloadidx1, ssa.OpAMD64MOVBEQloadidx8: p := s.Prog(v.Op.Asm()) memIdx(&p.From, v) ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64MOVQstore, ssa.OpAMD64MOVSSstore, ssa.OpAMD64MOVSDstore, ssa.OpAMD64MOVLstore, ssa.OpAMD64MOVWstore, ssa.OpAMD64MOVBstore, ssa.OpAMD64MOVOstore, ssa.OpAMD64ADDQmodify, ssa.OpAMD64SUBQmodify, ssa.OpAMD64ANDQmodify, ssa.OpAMD64ORQmodify, ssa.OpAMD64XORQmodify, ssa.OpAMD64ADDLmodify, ssa.OpAMD64SUBLmodify, ssa.OpAMD64ANDLmodify, ssa.OpAMD64ORLmodify, ssa.OpAMD64XORLmodify, ssa.OpAMD64MOVBEQstore, ssa.OpAMD64MOVBELstore, ssa.OpAMD64MOVBEWstore: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[1].Reg() p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() ssagen.AddAux(&p.To, v) case ssa.OpAMD64MOVBstoreidx1, ssa.OpAMD64MOVWstoreidx1, ssa.OpAMD64MOVLstoreidx1, ssa.OpAMD64MOVQstoreidx1, ssa.OpAMD64MOVSSstoreidx1, ssa.OpAMD64MOVSDstoreidx1, ssa.OpAMD64MOVQstoreidx8, ssa.OpAMD64MOVSDstoreidx8, ssa.OpAMD64MOVLstoreidx8, ssa.OpAMD64MOVSSstoreidx4, ssa.OpAMD64MOVLstoreidx4, ssa.OpAMD64MOVWstoreidx2, ssa.OpAMD64ADDLmodifyidx1, ssa.OpAMD64ADDLmodifyidx4, ssa.OpAMD64ADDLmodifyidx8, ssa.OpAMD64ADDQmodifyidx1, ssa.OpAMD64ADDQmodifyidx8, ssa.OpAMD64SUBLmodifyidx1, ssa.OpAMD64SUBLmodifyidx4, ssa.OpAMD64SUBLmodifyidx8, ssa.OpAMD64SUBQmodifyidx1, ssa.OpAMD64SUBQmodifyidx8, ssa.OpAMD64ANDLmodifyidx1, ssa.OpAMD64ANDLmodifyidx4, ssa.OpAMD64ANDLmodifyidx8, ssa.OpAMD64ANDQmodifyidx1, ssa.OpAMD64ANDQmodifyidx8, ssa.OpAMD64ORLmodifyidx1, ssa.OpAMD64ORLmodifyidx4, ssa.OpAMD64ORLmodifyidx8, ssa.OpAMD64ORQmodifyidx1, ssa.OpAMD64ORQmodifyidx8, ssa.OpAMD64XORLmodifyidx1, ssa.OpAMD64XORLmodifyidx4, ssa.OpAMD64XORLmodifyidx8, ssa.OpAMD64XORQmodifyidx1, ssa.OpAMD64XORQmodifyidx8, ssa.OpAMD64MOVBEWstoreidx1, ssa.OpAMD64MOVBEWstoreidx2, ssa.OpAMD64MOVBELstoreidx1, ssa.OpAMD64MOVBELstoreidx4, ssa.OpAMD64MOVBELstoreidx8, ssa.OpAMD64MOVBEQstoreidx1, ssa.OpAMD64MOVBEQstoreidx8: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[2].Reg() memIdx(&p.To, v) ssagen.AddAux(&p.To, v) case ssa.OpAMD64ADDQconstmodify, ssa.OpAMD64ADDLconstmodify: sc := v.AuxValAndOff() off := sc.Off64() val := sc.Val() if val == 1 || val == -1 { var asm obj.As if v.Op == ssa.OpAMD64ADDQconstmodify { if val == 1 { asm = x86.AINCQ } else { asm = x86.ADECQ } } else { if val == 1 { asm = x86.AINCL } else { asm = x86.ADECL } } p := s.Prog(asm) p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() ssagen.AddAux2(&p.To, v, off) break } fallthrough case ssa.OpAMD64ANDQconstmodify, ssa.OpAMD64ANDLconstmodify, ssa.OpAMD64ORQconstmodify, ssa.OpAMD64ORLconstmodify, ssa.OpAMD64XORQconstmodify, ssa.OpAMD64XORLconstmodify, ssa.OpAMD64BTSQconstmodify, ssa.OpAMD64BTRQconstmodify, ssa.OpAMD64BTCQconstmodify: sc := v.AuxValAndOff() off := sc.Off64() val := sc.Val64() p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_CONST p.From.Offset = val p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() ssagen.AddAux2(&p.To, v, off) case ssa.OpAMD64MOVQstoreconst, ssa.OpAMD64MOVLstoreconst, ssa.OpAMD64MOVWstoreconst, ssa.OpAMD64MOVBstoreconst: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_CONST sc := v.AuxValAndOff() p.From.Offset = sc.Val64() p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() ssagen.AddAux2(&p.To, v, sc.Off64()) case ssa.OpAMD64MOVOstoreconst: sc := v.AuxValAndOff() if sc.Val() != 0 { v.Fatalf("MOVO for non zero constants not implemented: %s", v.LongString()) } if s.ABI != obj.ABIInternal { // zero X15 manually opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15) } p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = x86.REG_X15 p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() ssagen.AddAux2(&p.To, v, sc.Off64()) case ssa.OpAMD64MOVQstoreconstidx1, ssa.OpAMD64MOVQstoreconstidx8, ssa.OpAMD64MOVLstoreconstidx1, ssa.OpAMD64MOVLstoreconstidx4, ssa.OpAMD64MOVWstoreconstidx1, ssa.OpAMD64MOVWstoreconstidx2, ssa.OpAMD64MOVBstoreconstidx1, ssa.OpAMD64ADDLconstmodifyidx1, ssa.OpAMD64ADDLconstmodifyidx4, ssa.OpAMD64ADDLconstmodifyidx8, ssa.OpAMD64ADDQconstmodifyidx1, ssa.OpAMD64ADDQconstmodifyidx8, ssa.OpAMD64ANDLconstmodifyidx1, ssa.OpAMD64ANDLconstmodifyidx4, ssa.OpAMD64ANDLconstmodifyidx8, ssa.OpAMD64ANDQconstmodifyidx1, ssa.OpAMD64ANDQconstmodifyidx8, ssa.OpAMD64ORLconstmodifyidx1, ssa.OpAMD64ORLconstmodifyidx4, ssa.OpAMD64ORLconstmodifyidx8, ssa.OpAMD64ORQconstmodifyidx1, ssa.OpAMD64ORQconstmodifyidx8, ssa.OpAMD64XORLconstmodifyidx1, ssa.OpAMD64XORLconstmodifyidx4, ssa.OpAMD64XORLconstmodifyidx8, ssa.OpAMD64XORQconstmodifyidx1, ssa.OpAMD64XORQconstmodifyidx8: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_CONST sc := v.AuxValAndOff() p.From.Offset = sc.Val64() switch { case p.As == x86.AADDQ && p.From.Offset == 1: p.As = x86.AINCQ p.From.Type = obj.TYPE_NONE case p.As == x86.AADDQ && p.From.Offset == -1: p.As = x86.ADECQ p.From.Type = obj.TYPE_NONE case p.As == x86.AADDL && p.From.Offset == 1: p.As = x86.AINCL p.From.Type = obj.TYPE_NONE case p.As == x86.AADDL && p.From.Offset == -1: p.As = x86.ADECL p.From.Type = obj.TYPE_NONE } memIdx(&p.To, v) ssagen.AddAux2(&p.To, v, sc.Off64()) case ssa.OpAMD64MOVLQSX, ssa.OpAMD64MOVWQSX, ssa.OpAMD64MOVBQSX, ssa.OpAMD64MOVLQZX, ssa.OpAMD64MOVWQZX, ssa.OpAMD64MOVBQZX, ssa.OpAMD64CVTTSS2SL, ssa.OpAMD64CVTTSD2SL, ssa.OpAMD64CVTTSS2SQ, ssa.OpAMD64CVTTSD2SQ, ssa.OpAMD64CVTSS2SD, ssa.OpAMD64CVTSD2SS: opregreg(s, v.Op.Asm(), v.Reg(), v.Args[0].Reg()) case ssa.OpAMD64CVTSL2SD, ssa.OpAMD64CVTSQ2SD, ssa.OpAMD64CVTSQ2SS, ssa.OpAMD64CVTSL2SS: r := v.Reg() // Break false dependency on destination register. opregreg(s, x86.AXORPS, r, r) opregreg(s, v.Op.Asm(), r, v.Args[0].Reg()) case ssa.OpAMD64MOVQi2f, ssa.OpAMD64MOVQf2i, ssa.OpAMD64MOVLi2f, ssa.OpAMD64MOVLf2i: var p *obj.Prog switch v.Op { case ssa.OpAMD64MOVQi2f, ssa.OpAMD64MOVQf2i: p = s.Prog(x86.AMOVQ) case ssa.OpAMD64MOVLi2f, ssa.OpAMD64MOVLf2i: p = s.Prog(x86.AMOVL) } p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[0].Reg() p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64ADDQload, ssa.OpAMD64ADDLload, ssa.OpAMD64SUBQload, ssa.OpAMD64SUBLload, ssa.OpAMD64ANDQload, ssa.OpAMD64ANDLload, ssa.OpAMD64ORQload, ssa.OpAMD64ORLload, ssa.OpAMD64XORQload, ssa.OpAMD64XORLload, ssa.OpAMD64ADDSDload, ssa.OpAMD64ADDSSload, ssa.OpAMD64SUBSDload, ssa.OpAMD64SUBSSload, ssa.OpAMD64MULSDload, ssa.OpAMD64MULSSload, ssa.OpAMD64DIVSDload, ssa.OpAMD64DIVSSload: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_MEM p.From.Reg = v.Args[1].Reg() ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64ADDLloadidx1, ssa.OpAMD64ADDLloadidx4, ssa.OpAMD64ADDLloadidx8, ssa.OpAMD64ADDQloadidx1, ssa.OpAMD64ADDQloadidx8, ssa.OpAMD64SUBLloadidx1, ssa.OpAMD64SUBLloadidx4, ssa.OpAMD64SUBLloadidx8, ssa.OpAMD64SUBQloadidx1, ssa.OpAMD64SUBQloadidx8, ssa.OpAMD64ANDLloadidx1, ssa.OpAMD64ANDLloadidx4, ssa.OpAMD64ANDLloadidx8, ssa.OpAMD64ANDQloadidx1, ssa.OpAMD64ANDQloadidx8, ssa.OpAMD64ORLloadidx1, ssa.OpAMD64ORLloadidx4, ssa.OpAMD64ORLloadidx8, ssa.OpAMD64ORQloadidx1, ssa.OpAMD64ORQloadidx8, ssa.OpAMD64XORLloadidx1, ssa.OpAMD64XORLloadidx4, ssa.OpAMD64XORLloadidx8, ssa.OpAMD64XORQloadidx1, ssa.OpAMD64XORQloadidx8, ssa.OpAMD64ADDSSloadidx1, ssa.OpAMD64ADDSSloadidx4, ssa.OpAMD64ADDSDloadidx1, ssa.OpAMD64ADDSDloadidx8, ssa.OpAMD64SUBSSloadidx1, ssa.OpAMD64SUBSSloadidx4, ssa.OpAMD64SUBSDloadidx1, ssa.OpAMD64SUBSDloadidx8, ssa.OpAMD64MULSSloadidx1, ssa.OpAMD64MULSSloadidx4, ssa.OpAMD64MULSDloadidx1, ssa.OpAMD64MULSDloadidx8, ssa.OpAMD64DIVSSloadidx1, ssa.OpAMD64DIVSSloadidx4, ssa.OpAMD64DIVSDloadidx1, ssa.OpAMD64DIVSDloadidx8: p := s.Prog(v.Op.Asm()) r, i := v.Args[1].Reg(), v.Args[2].Reg() p.From.Type = obj.TYPE_MEM p.From.Scale = v.Op.Scale() if p.From.Scale == 1 && i == x86.REG_SP { r, i = i, r } p.From.Reg = r p.From.Index = i ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64DUFFZERO: if s.ABI != obj.ABIInternal { // zero X15 manually opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15) } off := duffStart(v.AuxInt) adj := duffAdj(v.AuxInt) var p *obj.Prog if adj != 0 { p = s.Prog(x86.ALEAQ) p.From.Type = obj.TYPE_MEM p.From.Offset = adj p.From.Reg = x86.REG_DI p.To.Type = obj.TYPE_REG p.To.Reg = x86.REG_DI } p = s.Prog(obj.ADUFFZERO) p.To.Type = obj.TYPE_ADDR p.To.Sym = ir.Syms.Duffzero p.To.Offset = off case ssa.OpAMD64DUFFCOPY: p := s.Prog(obj.ADUFFCOPY) p.To.Type = obj.TYPE_ADDR p.To.Sym = ir.Syms.Duffcopy if v.AuxInt%16 != 0 { v.Fatalf("bad DUFFCOPY AuxInt %v", v.AuxInt) } p.To.Offset = 14 * (64 - v.AuxInt/16) // 14 and 64 are magic constants. 14 is the number of bytes to encode: // MOVUPS (SI), X0 // ADDQ $16, SI // MOVUPS X0, (DI) // ADDQ $16, DI // and 64 is the number of such blocks. See src/runtime/duff_amd64.s:duffcopy. case ssa.OpCopy: // TODO: use MOVQreg for reg->reg copies instead of OpCopy? if v.Type.IsMemory() { return } x := v.Args[0].Reg() y := v.Reg() if x != y { opregreg(s, moveByType(v.Type), y, x) } case ssa.OpLoadReg: if v.Type.IsFlags() { v.Fatalf("load flags not implemented: %v", v.LongString()) return } p := s.Prog(loadByType(v.Type)) ssagen.AddrAuto(&p.From, v.Args[0]) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpStoreReg: if v.Type.IsFlags() { v.Fatalf("store flags not implemented: %v", v.LongString()) return } p := s.Prog(storeByType(v.Type)) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[0].Reg() ssagen.AddrAuto(&p.To, v) case ssa.OpAMD64LoweredHasCPUFeature: p := s.Prog(x86.AMOVBLZX) p.From.Type = obj.TYPE_MEM ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpArgIntReg, ssa.OpArgFloatReg: // The assembler needs to wrap the entry safepoint/stack growth code with spill/unspill // The loop only runs once. for _, ap := range v.Block.Func.RegArgs { // Pass the spill/unspill information along to the assembler, offset by size of return PC pushed on stack. addr := ssagen.SpillSlotAddr(ap, x86.REG_SP, v.Block.Func.Config.PtrSize) s.FuncInfo().AddSpill( obj.RegSpill{Reg: ap.Reg, Addr: addr, Unspill: loadByType(ap.Type), Spill: storeByType(ap.Type)}) } v.Block.Func.RegArgs = nil ssagen.CheckArgReg(v) case ssa.OpAMD64LoweredGetClosurePtr: // Closure pointer is DX. ssagen.CheckLoweredGetClosurePtr(v) case ssa.OpAMD64LoweredGetG: if s.ABI == obj.ABIInternal { v.Fatalf("LoweredGetG should not appear in ABIInternal") } r := v.Reg() getgFromTLS(s, r) case ssa.OpAMD64CALLstatic, ssa.OpAMD64CALLtail: if s.ABI == obj.ABI0 && v.Aux.(*ssa.AuxCall).Fn.ABI() == obj.ABIInternal { // zeroing X15 when entering ABIInternal from ABI0 if buildcfg.GOOS != "plan9" { // do not use SSE on Plan 9 opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15) } // set G register from TLS getgFromTLS(s, x86.REG_R14) } if v.Op == ssa.OpAMD64CALLtail { s.TailCall(v) break } s.Call(v) if s.ABI == obj.ABIInternal && v.Aux.(*ssa.AuxCall).Fn.ABI() == obj.ABI0 { // zeroing X15 when entering ABIInternal from ABI0 if buildcfg.GOOS != "plan9" { // do not use SSE on Plan 9 opregreg(s, x86.AXORPS, x86.REG_X15, x86.REG_X15) } // set G register from TLS getgFromTLS(s, x86.REG_R14) } case ssa.OpAMD64CALLclosure, ssa.OpAMD64CALLinter: s.Call(v) case ssa.OpAMD64LoweredGetCallerPC: p := s.Prog(x86.AMOVQ) p.From.Type = obj.TYPE_MEM p.From.Offset = -8 // PC is stored 8 bytes below first parameter. p.From.Name = obj.NAME_PARAM p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64LoweredGetCallerSP: // caller's SP is the address of the first arg mov := x86.AMOVQ if types.PtrSize == 4 { mov = x86.AMOVL } p := s.Prog(mov) p.From.Type = obj.TYPE_ADDR p.From.Offset = -base.Ctxt.Arch.FixedFrameSize // 0 on amd64, just to be consistent with other architectures p.From.Name = obj.NAME_PARAM p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64LoweredWB: p := s.Prog(obj.ACALL) p.To.Type = obj.TYPE_MEM p.To.Name = obj.NAME_EXTERN // AuxInt encodes how many buffer entries we need. p.To.Sym = ir.Syms.GCWriteBarrier[v.AuxInt-1] case ssa.OpAMD64LoweredPanicBoundsA, ssa.OpAMD64LoweredPanicBoundsB, ssa.OpAMD64LoweredPanicBoundsC: p := s.Prog(obj.ACALL) p.To.Type = obj.TYPE_MEM p.To.Name = obj.NAME_EXTERN p.To.Sym = ssagen.BoundsCheckFunc[v.AuxInt] s.UseArgs(int64(2 * types.PtrSize)) // space used in callee args area by assembly stubs case ssa.OpAMD64NEGQ, ssa.OpAMD64NEGL, ssa.OpAMD64BSWAPQ, ssa.OpAMD64BSWAPL, ssa.OpAMD64NOTQ, ssa.OpAMD64NOTL: p := s.Prog(v.Op.Asm()) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64NEGLflags: p := s.Prog(v.Op.Asm()) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg0() case ssa.OpAMD64BSFQ, ssa.OpAMD64BSRQ, ssa.OpAMD64BSFL, ssa.OpAMD64BSRL, ssa.OpAMD64SQRTSD, ssa.OpAMD64SQRTSS: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[0].Reg() p.To.Type = obj.TYPE_REG switch v.Op { case ssa.OpAMD64BSFQ, ssa.OpAMD64BSRQ: p.To.Reg = v.Reg0() case ssa.OpAMD64BSFL, ssa.OpAMD64BSRL, ssa.OpAMD64SQRTSD, ssa.OpAMD64SQRTSS: p.To.Reg = v.Reg() } case ssa.OpAMD64ROUNDSD: p := s.Prog(v.Op.Asm()) val := v.AuxInt // 0 means math.RoundToEven, 1 Floor, 2 Ceil, 3 Trunc if val < 0 || val > 3 { v.Fatalf("Invalid rounding mode") } p.From.Offset = val p.From.Type = obj.TYPE_CONST p.AddRestSourceReg(v.Args[0].Reg()) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64POPCNTQ, ssa.OpAMD64POPCNTL, ssa.OpAMD64TZCNTQ, ssa.OpAMD64TZCNTL, ssa.OpAMD64LZCNTQ, ssa.OpAMD64LZCNTL: if v.Args[0].Reg() != v.Reg() { // POPCNT/TZCNT/LZCNT have a false dependency on the destination register on Intel cpus. // TZCNT/LZCNT problem affects pre-Skylake models. See discussion at https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011#c7. // Xor register with itself to break the dependency. opregreg(s, x86.AXORL, v.Reg(), v.Reg()) } p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[0].Reg() p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64SETEQ, ssa.OpAMD64SETNE, ssa.OpAMD64SETL, ssa.OpAMD64SETLE, ssa.OpAMD64SETG, ssa.OpAMD64SETGE, ssa.OpAMD64SETGF, ssa.OpAMD64SETGEF, ssa.OpAMD64SETB, ssa.OpAMD64SETBE, ssa.OpAMD64SETORD, ssa.OpAMD64SETNAN, ssa.OpAMD64SETA, ssa.OpAMD64SETAE, ssa.OpAMD64SETO: p := s.Prog(v.Op.Asm()) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() case ssa.OpAMD64SETEQstore, ssa.OpAMD64SETNEstore, ssa.OpAMD64SETLstore, ssa.OpAMD64SETLEstore, ssa.OpAMD64SETGstore, ssa.OpAMD64SETGEstore, ssa.OpAMD64SETBstore, ssa.OpAMD64SETBEstore, ssa.OpAMD64SETAstore, ssa.OpAMD64SETAEstore: p := s.Prog(v.Op.Asm()) p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() ssagen.AddAux(&p.To, v) case ssa.OpAMD64SETEQstoreidx1, ssa.OpAMD64SETNEstoreidx1, ssa.OpAMD64SETLstoreidx1, ssa.OpAMD64SETLEstoreidx1, ssa.OpAMD64SETGstoreidx1, ssa.OpAMD64SETGEstoreidx1, ssa.OpAMD64SETBstoreidx1, ssa.OpAMD64SETBEstoreidx1, ssa.OpAMD64SETAstoreidx1, ssa.OpAMD64SETAEstoreidx1: p := s.Prog(v.Op.Asm()) memIdx(&p.To, v) ssagen.AddAux(&p.To, v) case ssa.OpAMD64SETNEF: t := v.RegTmp() p := s.Prog(v.Op.Asm()) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() q := s.Prog(x86.ASETPS) q.To.Type = obj.TYPE_REG q.To.Reg = t // ORL avoids partial register write and is smaller than ORQ, used by old compiler opregreg(s, x86.AORL, v.Reg(), t) case ssa.OpAMD64SETEQF: t := v.RegTmp() p := s.Prog(v.Op.Asm()) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() q := s.Prog(x86.ASETPC) q.To.Type = obj.TYPE_REG q.To.Reg = t // ANDL avoids partial register write and is smaller than ANDQ, used by old compiler opregreg(s, x86.AANDL, v.Reg(), t) case ssa.OpAMD64InvertFlags: v.Fatalf("InvertFlags should never make it to codegen %v", v.LongString()) case ssa.OpAMD64FlagEQ, ssa.OpAMD64FlagLT_ULT, ssa.OpAMD64FlagLT_UGT, ssa.OpAMD64FlagGT_ULT, ssa.OpAMD64FlagGT_UGT: v.Fatalf("Flag* ops should never make it to codegen %v", v.LongString()) case ssa.OpAMD64AddTupleFirst32, ssa.OpAMD64AddTupleFirst64: v.Fatalf("AddTupleFirst* should never make it to codegen %v", v.LongString()) case ssa.OpAMD64REPSTOSQ: s.Prog(x86.AREP) s.Prog(x86.ASTOSQ) case ssa.OpAMD64REPMOVSQ: s.Prog(x86.AREP) s.Prog(x86.AMOVSQ) case ssa.OpAMD64LoweredNilCheck: // Issue a load which will fault if the input is nil. // TODO: We currently use the 2-byte instruction TESTB AX, (reg). // Should we use the 3-byte TESTB $0, (reg) instead? It is larger // but it doesn't have false dependency on AX. // Or maybe allocate an output register and use MOVL (reg),reg2 ? // That trades clobbering flags for clobbering a register. p := s.Prog(x86.ATESTB) p.From.Type = obj.TYPE_REG p.From.Reg = x86.REG_AX p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() if logopt.Enabled() { logopt.LogOpt(v.Pos, "nilcheck", "genssa", v.Block.Func.Name) } if base.Debug.Nil != 0 && v.Pos.Line() > 1 { // v.Pos.Line()==1 in generated wrappers base.WarnfAt(v.Pos, "generated nil check") } case ssa.OpAMD64MOVBatomicload, ssa.OpAMD64MOVLatomicload, ssa.OpAMD64MOVQatomicload: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_MEM p.From.Reg = v.Args[0].Reg() ssagen.AddAux(&p.From, v) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg0() case ssa.OpAMD64XCHGB, ssa.OpAMD64XCHGL, ssa.OpAMD64XCHGQ: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Reg0() p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[1].Reg() ssagen.AddAux(&p.To, v) case ssa.OpAMD64XADDLlock, ssa.OpAMD64XADDQlock: s.Prog(x86.ALOCK) p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Reg0() p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[1].Reg() ssagen.AddAux(&p.To, v) case ssa.OpAMD64CMPXCHGLlock, ssa.OpAMD64CMPXCHGQlock: if v.Args[1].Reg() != x86.REG_AX { v.Fatalf("input[1] not in AX %s", v.LongString()) } s.Prog(x86.ALOCK) p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[2].Reg() p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() ssagen.AddAux(&p.To, v) p = s.Prog(x86.ASETEQ) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg0() case ssa.OpAMD64ANDBlock, ssa.OpAMD64ANDLlock, ssa.OpAMD64ANDQlock, ssa.OpAMD64ORBlock, ssa.OpAMD64ORLlock, ssa.OpAMD64ORQlock: // Atomic memory operations that don't need to return the old value. s.Prog(x86.ALOCK) p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_REG p.From.Reg = v.Args[1].Reg() p.To.Type = obj.TYPE_MEM p.To.Reg = v.Args[0].Reg() ssagen.AddAux(&p.To, v) case ssa.OpAMD64LoweredAtomicAnd64, ssa.OpAMD64LoweredAtomicOr64, ssa.OpAMD64LoweredAtomicAnd32, ssa.OpAMD64LoweredAtomicOr32: // Atomic memory operations that need to return the old value. // We need to do these with compare-and-exchange to get access to the old value. // loop: // MOVQ mask, tmp // MOVQ (addr), AX // ANDQ AX, tmp // LOCK CMPXCHGQ tmp, (addr) : note that AX is implicit old value to compare against // JNE loop // : result in AX mov := x86.AMOVQ op := x86.AANDQ cmpxchg := x86.ACMPXCHGQ switch v.Op { case ssa.OpAMD64LoweredAtomicOr64: op = x86.AORQ case ssa.OpAMD64LoweredAtomicAnd32: mov = x86.AMOVL op = x86.AANDL cmpxchg = x86.ACMPXCHGL case ssa.OpAMD64LoweredAtomicOr32: mov = x86.AMOVL op = x86.AORL cmpxchg = x86.ACMPXCHGL } addr := v.Args[0].Reg() mask := v.Args[1].Reg() tmp := v.RegTmp() p1 := s.Prog(mov) p1.From.Type = obj.TYPE_REG p1.From.Reg = mask p1.To.Type = obj.TYPE_REG p1.To.Reg = tmp p2 := s.Prog(mov) p2.From.Type = obj.TYPE_MEM p2.From.Reg = addr ssagen.AddAux(&p2.From, v) p2.To.Type = obj.TYPE_REG p2.To.Reg = x86.REG_AX p3 := s.Prog(op) p3.From.Type = obj.TYPE_REG p3.From.Reg = x86.REG_AX p3.To.Type = obj.TYPE_REG p3.To.Reg = tmp s.Prog(x86.ALOCK) p5 := s.Prog(cmpxchg) p5.From.Type = obj.TYPE_REG p5.From.Reg = tmp p5.To.Type = obj.TYPE_MEM p5.To.Reg = addr ssagen.AddAux(&p5.To, v) p6 := s.Prog(x86.AJNE) p6.To.Type = obj.TYPE_BRANCH p6.To.SetTarget(p1) case ssa.OpAMD64PrefetchT0, ssa.OpAMD64PrefetchNTA: p := s.Prog(v.Op.Asm()) p.From.Type = obj.TYPE_MEM p.From.Reg = v.Args[0].Reg() case ssa.OpClobber: p := s.Prog(x86.AMOVL) p.From.Type = obj.TYPE_CONST p.From.Offset = 0xdeaddead p.To.Type = obj.TYPE_MEM p.To.Reg = x86.REG_SP ssagen.AddAux(&p.To, v) p = s.Prog(x86.AMOVL) p.From.Type = obj.TYPE_CONST p.From.Offset = 0xdeaddead p.To.Type = obj.TYPE_MEM p.To.Reg = x86.REG_SP ssagen.AddAux(&p.To, v) p.To.Offset += 4 case ssa.OpClobberReg: x := uint64(0xdeaddeaddeaddead) p := s.Prog(x86.AMOVQ) p.From.Type = obj.TYPE_CONST p.From.Offset = int64(x) p.To.Type = obj.TYPE_REG p.To.Reg = v.Reg() default: v.Fatalf("genValue not implemented: %s", v.LongString()) } } var blockJump = [...]struct { asm, invasm obj.As }{ ssa.BlockAMD64EQ: {x86.AJEQ, x86.AJNE}, ssa.BlockAMD64NE: {x86.AJNE, x86.AJEQ}, ssa.BlockAMD64LT: {x86.AJLT, x86.AJGE}, ssa.BlockAMD64GE: {x86.AJGE, x86.AJLT}, ssa.BlockAMD64LE: {x86.AJLE, x86.AJGT}, ssa.BlockAMD64GT: {x86.AJGT, x86.AJLE}, ssa.BlockAMD64OS: {x86.AJOS, x86.AJOC}, ssa.BlockAMD64OC: {x86.AJOC, x86.AJOS}, ssa.BlockAMD64ULT: {x86.AJCS, x86.AJCC}, ssa.BlockAMD64UGE: {x86.AJCC, x86.AJCS}, ssa.BlockAMD64UGT: {x86.AJHI, x86.AJLS}, ssa.BlockAMD64ULE: {x86.AJLS, x86.AJHI}, ssa.BlockAMD64ORD: {x86.AJPC, x86.AJPS}, ssa.BlockAMD64NAN: {x86.AJPS, x86.AJPC}, } var eqfJumps = [2][2]ssagen.IndexJump{ {{Jump: x86.AJNE, Index: 1}, {Jump: x86.AJPS, Index: 1}}, // next == b.Succs[0] {{Jump: x86.AJNE, Index: 1}, {Jump: x86.AJPC, Index: 0}}, // next == b.Succs[1] } var nefJumps = [2][2]ssagen.IndexJump{ {{Jump: x86.AJNE, Index: 0}, {Jump: x86.AJPC, Index: 1}}, // next == b.Succs[0] {{Jump: x86.AJNE, Index: 0}, {Jump: x86.AJPS, Index: 0}}, // next == b.Succs[1] } func ssaGenBlock(s *ssagen.State, b, next *ssa.Block) { switch b.Kind { case ssa.BlockPlain: if b.Succs[0].Block() != next { p := s.Prog(obj.AJMP) p.To.Type = obj.TYPE_BRANCH s.Branches = append(s.Branches, ssagen.Branch{P: p, B: b.Succs[0].Block()}) } case ssa.BlockDefer: // defer returns in rax: // 0 if we should continue executing // 1 if we should jump to deferreturn call p := s.Prog(x86.ATESTL) p.From.Type = obj.TYPE_REG p.From.Reg = x86.REG_AX p.To.Type = obj.TYPE_REG p.To.Reg = x86.REG_AX p = s.Prog(x86.AJNE) p.To.Type = obj.TYPE_BRANCH s.Branches = append(s.Branches, ssagen.Branch{P: p, B: b.Succs[1].Block()}) if b.Succs[0].Block() != next { p := s.Prog(obj.AJMP) p.To.Type = obj.TYPE_BRANCH s.Branches = append(s.Branches, ssagen.Branch{P: p, B: b.Succs[0].Block()}) } case ssa.BlockExit, ssa.BlockRetJmp: case ssa.BlockRet: s.Prog(obj.ARET) case ssa.BlockAMD64EQF: s.CombJump(b, next, &eqfJumps) case ssa.BlockAMD64NEF: s.CombJump(b, next, &nefJumps) case ssa.BlockAMD64EQ, ssa.BlockAMD64NE, ssa.BlockAMD64LT, ssa.BlockAMD64GE, ssa.BlockAMD64LE, ssa.BlockAMD64GT, ssa.BlockAMD64OS, ssa.BlockAMD64OC, ssa.BlockAMD64ULT, ssa.BlockAMD64UGT, ssa.BlockAMD64ULE, ssa.BlockAMD64UGE: jmp := blockJump[b.Kind] switch next { case b.Succs[0].Block(): s.Br(jmp.invasm, b.Succs[1].Block()) case b.Succs[1].Block(): s.Br(jmp.asm, b.Succs[0].Block()) default: if b.Likely != ssa.BranchUnlikely { s.Br(jmp.asm, b.Succs[0].Block()) s.Br(obj.AJMP, b.Succs[1].Block()) } else { s.Br(jmp.invasm, b.Succs[1].Block()) s.Br(obj.AJMP, b.Succs[0].Block()) } } case ssa.BlockAMD64JUMPTABLE: // JMP *(TABLE)(INDEX*8) p := s.Prog(obj.AJMP) p.To.Type = obj.TYPE_MEM p.To.Reg = b.Controls[1].Reg() p.To.Index = b.Controls[0].Reg() p.To.Scale = 8 // Save jump tables for later resolution of the target blocks. s.JumpTables = append(s.JumpTables, b) default: b.Fatalf("branch not implemented: %s", b.LongString()) } } func loadRegResult(s *ssagen.State, f *ssa.Func, t *types.Type, reg int16, n *ir.Name, off int64) *obj.Prog { p := s.Prog(loadByType(t)) p.From.Type = obj.TYPE_MEM p.From.Name = obj.NAME_AUTO p.From.Sym = n.Linksym() p.From.Offset = n.FrameOffset() + off p.To.Type = obj.TYPE_REG p.To.Reg = reg return p } func spillArgReg(pp *objw.Progs, p *obj.Prog, f *ssa.Func, t *types.Type, reg int16, n *ir.Name, off int64) *obj.Prog { p = pp.Append(p, storeByType(t), obj.TYPE_REG, reg, 0, obj.TYPE_MEM, 0, n.FrameOffset()+off) p.To.Name = obj.NAME_PARAM p.To.Sym = n.Linksym() p.Pos = p.Pos.WithNotStmt() return p }
go/src/cmd/compile/internal/amd64/ssa.go/0
{ "file_path": "go/src/cmd/compile/internal/amd64/ssa.go", "repo_id": "go", "token_count": 25059 }
86
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build unix package base import ( "internal/unsafeheader" "os" "runtime" "syscall" "unsafe" ) // TODO(mdempsky): Is there a higher-level abstraction that still // works well for iimport? // MapFile returns length bytes from the file starting at the // specified offset as a string. func MapFile(f *os.File, offset, length int64) (string, error) { // POSIX mmap: "The implementation may require that off is a // multiple of the page size." x := offset & int64(os.Getpagesize()-1) offset -= x length += x buf, err := syscall.Mmap(int(f.Fd()), offset, int(length), syscall.PROT_READ, syscall.MAP_SHARED) runtime.KeepAlive(f) if err != nil { return "", err } buf = buf[x:] pSlice := (*unsafeheader.Slice)(unsafe.Pointer(&buf)) var res string pString := (*unsafeheader.String)(unsafe.Pointer(&res)) pString.Data = pSlice.Data pString.Len = pSlice.Len return res, nil }
go/src/cmd/compile/internal/base/mapfile_mmap.go/0
{ "file_path": "go/src/cmd/compile/internal/base/mapfile_mmap.go", "repo_id": "go", "token_count": 376 }
87
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package escape import ( "cmd/compile/internal/base" "cmd/compile/internal/ir" ) // addr evaluates an addressable expression n and returns a hole // that represents storing into the represented location. func (e *escape) addr(n ir.Node) hole { if n == nil || ir.IsBlank(n) { // Can happen in select case, range, maybe others. return e.discardHole() } k := e.heapHole() switch n.Op() { default: base.Fatalf("unexpected addr: %v", n) case ir.ONAME: n := n.(*ir.Name) if n.Class == ir.PEXTERN { break } k = e.oldLoc(n).asHole() case ir.OLINKSYMOFFSET: break case ir.ODOT: n := n.(*ir.SelectorExpr) k = e.addr(n.X) case ir.OINDEX: n := n.(*ir.IndexExpr) e.discard(n.Index) if n.X.Type().IsArray() { k = e.addr(n.X) } else { e.mutate(n.X) } case ir.ODEREF: n := n.(*ir.StarExpr) e.mutate(n.X) case ir.ODOTPTR: n := n.(*ir.SelectorExpr) e.mutate(n.X) case ir.OINDEXMAP: n := n.(*ir.IndexExpr) e.discard(n.X) e.assignHeap(n.Index, "key of map put", n) } return k } func (e *escape) mutate(n ir.Node) { e.expr(e.mutatorHole(), n) } func (e *escape) addrs(l ir.Nodes) []hole { var ks []hole for _, n := range l { ks = append(ks, e.addr(n)) } return ks } func (e *escape) assignHeap(src ir.Node, why string, where ir.Node) { e.expr(e.heapHole().note(where, why), src) } // assignList evaluates the assignment dsts... = srcs.... func (e *escape) assignList(dsts, srcs []ir.Node, why string, where ir.Node) { ks := e.addrs(dsts) for i, k := range ks { var src ir.Node if i < len(srcs) { src = srcs[i] } if dst := dsts[i]; dst != nil { // Detect implicit conversion of uintptr to unsafe.Pointer when // storing into reflect.{Slice,String}Header. if dst.Op() == ir.ODOTPTR && ir.IsReflectHeaderDataField(dst) { e.unsafeValue(e.heapHole().note(where, why), src) continue } // Filter out some no-op assignments for escape analysis. if src != nil && isSelfAssign(dst, src) { if base.Flag.LowerM != 0 { base.WarnfAt(where.Pos(), "%v ignoring self-assignment in %v", e.curfn, where) } k = e.discardHole() } } e.expr(k.note(where, why), src) } e.reassigned(ks, where) } // reassigned marks the locations associated with the given holes as // reassigned, unless the location represents a variable declared and // assigned exactly once by where. func (e *escape) reassigned(ks []hole, where ir.Node) { if as, ok := where.(*ir.AssignStmt); ok && as.Op() == ir.OAS && as.Y == nil { if dst, ok := as.X.(*ir.Name); ok && dst.Op() == ir.ONAME && dst.Defn == nil { // Zero-value assignment for variable declared without an // explicit initial value. Assume this is its initialization // statement. return } } for _, k := range ks { loc := k.dst // Variables declared by range statements are assigned on every iteration. if n, ok := loc.n.(*ir.Name); ok && n.Defn == where && where.Op() != ir.ORANGE { continue } loc.reassigned = true } }
go/src/cmd/compile/internal/escape/assign.go/0
{ "file_path": "go/src/cmd/compile/internal/escape/assign.go", "repo_id": "go", "token_count": 1317 }
88
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package importer import ( "bytes" "cmd/compile/internal/types2" "fmt" "go/build" "internal/testenv" "os" "os/exec" "path" "path/filepath" "runtime" "strings" "testing" "time" ) func TestMain(m *testing.M) { build.Default.GOROOT = testenv.GOROOT(nil) os.Exit(m.Run()) } // compile runs the compiler on filename, with dirname as the working directory, // and writes the output file to outdirname. // compile gives the resulting package a packagepath of testdata/<filebasename>. func compile(t *testing.T, dirname, filename, outdirname string, packagefiles map[string]string) string { // filename must end with ".go" basename, ok := strings.CutSuffix(filepath.Base(filename), ".go") if !ok { t.Helper() t.Fatalf("filename doesn't end in .go: %s", filename) } objname := basename + ".o" outname := filepath.Join(outdirname, objname) pkgpath := path.Join("testdata", basename) importcfgfile := os.DevNull if len(packagefiles) > 0 { importcfgfile = filepath.Join(outdirname, basename) + ".importcfg" importcfg := new(bytes.Buffer) for k, v := range packagefiles { fmt.Fprintf(importcfg, "packagefile %s=%s\n", k, v) } if err := os.WriteFile(importcfgfile, importcfg.Bytes(), 0655); err != nil { t.Fatal(err) } } cmd := testenv.Command(t, testenv.GoToolPath(t), "tool", "compile", "-p", pkgpath, "-D", "testdata", "-importcfg", importcfgfile, "-o", outname, filename) cmd.Dir = dirname out, err := cmd.CombinedOutput() if err != nil { t.Helper() t.Logf("%s", out) t.Fatalf("go tool compile %s failed: %s", filename, err) } return outname } func testPath(t *testing.T, path, srcDir string) *types2.Package { t0 := time.Now() pkg, err := Import(make(map[string]*types2.Package), path, srcDir, nil) if err != nil { t.Errorf("testPath(%s): %s", path, err) return nil } t.Logf("testPath(%s): %v", path, time.Since(t0)) return pkg } func mktmpdir(t *testing.T) string { tmpdir := t.TempDir() if err := os.Mkdir(filepath.Join(tmpdir, "testdata"), 0700); err != nil { t.Fatal("mktmpdir:", err) } return tmpdir } func TestImportTestdata(t *testing.T) { // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } testenv.MustHaveGoBuild(t) testfiles := map[string][]string{ "exports.go": {"go/ast"}, "generics.go": nil, } for testfile, wantImports := range testfiles { tmpdir := mktmpdir(t) importMap := map[string]string{} for _, pkg := range wantImports { export, _, err := FindPkg(pkg, "testdata") if export == "" { t.Fatalf("no export data found for %s: %v", pkg, err) } importMap[pkg] = export } compile(t, "testdata", testfile, filepath.Join(tmpdir, "testdata"), importMap) path := "./testdata/" + strings.TrimSuffix(testfile, ".go") if pkg := testPath(t, path, tmpdir); pkg != nil { // The package's Imports list must include all packages // explicitly imported by testfile, plus all packages // referenced indirectly via exported objects in testfile. got := fmt.Sprint(pkg.Imports()) for _, want := range wantImports { if !strings.Contains(got, want) { t.Errorf(`Package("exports").Imports() = %s, does not contain %s`, got, want) } } } } } func TestVersionHandling(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } const dir = "./testdata/versions" list, err := os.ReadDir(dir) if err != nil { t.Fatal(err) } tmpdir := mktmpdir(t) corruptdir := filepath.Join(tmpdir, "testdata", "versions") if err := os.Mkdir(corruptdir, 0700); err != nil { t.Fatal(err) } for _, f := range list { name := f.Name() if !strings.HasSuffix(name, ".a") { continue // not a package file } if strings.Contains(name, "corrupted") { continue // don't process a leftover corrupted file } pkgpath := "./" + name[:len(name)-2] if testing.Verbose() { t.Logf("importing %s", name) } // test that export data can be imported _, err := Import(make(map[string]*types2.Package), pkgpath, dir, nil) if err != nil { // ok to fail if it fails with a no longer supported error for select files if strings.Contains(err.Error(), "no longer supported") { switch name { case "test_go1.7_0.a", "test_go1.7_1.a", "test_go1.8_4.a", "test_go1.8_5.a", "test_go1.11_6b.a", "test_go1.11_999b.a": continue } // fall through } // ok to fail if it fails with a newer version error for select files if strings.Contains(err.Error(), "newer version") { switch name { case "test_go1.11_999i.a": continue } // fall through } t.Errorf("import %q failed: %v", pkgpath, err) continue } // create file with corrupted export data // 1) read file data, err := os.ReadFile(filepath.Join(dir, name)) if err != nil { t.Fatal(err) } // 2) find export data i := bytes.Index(data, []byte("\n$$B\n")) + 5 j := bytes.Index(data[i:], []byte("\n$$\n")) + i if i < 0 || j < 0 || i > j { t.Fatalf("export data section not found (i = %d, j = %d)", i, j) } // 3) corrupt the data (increment every 7th byte) for k := j - 13; k >= i; k -= 7 { data[k]++ } // 4) write the file pkgpath += "_corrupted" filename := filepath.Join(corruptdir, pkgpath) + ".a" os.WriteFile(filename, data, 0666) // test that importing the corrupted file results in an error _, err = Import(make(map[string]*types2.Package), pkgpath, corruptdir, nil) if err == nil { t.Errorf("import corrupted %q succeeded", pkgpath) } else if msg := err.Error(); !strings.Contains(msg, "version skew") { t.Errorf("import %q error incorrect (%s)", pkgpath, msg) } } } func TestImportStdLib(t *testing.T) { if testing.Short() { t.Skip("the imports can be expensive, and this test is especially slow when the build cache is empty") } testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } // Get list of packages in stdlib. Filter out test-only packages with {{if .GoFiles}} check. var stderr bytes.Buffer cmd := exec.Command("go", "list", "-f", "{{if .GoFiles}}{{.ImportPath}}{{end}}", "std") cmd.Stderr = &stderr out, err := cmd.Output() if err != nil { t.Fatalf("failed to run go list to determine stdlib packages: %v\nstderr:\n%v", err, stderr.String()) } pkgs := strings.Fields(string(out)) var nimports int for _, pkg := range pkgs { t.Run(pkg, func(t *testing.T) { if testPath(t, pkg, filepath.Join(testenv.GOROOT(t), "src", path.Dir(pkg))) != nil { nimports++ } }) } const minPkgs = 225 // 'GOOS=plan9 go1.18 list std | wc -l' reports 228; most other platforms have more. if len(pkgs) < minPkgs { t.Fatalf("too few packages (%d) were imported", nimports) } t.Logf("tested %d imports", nimports) } var importedObjectTests = []struct { name string want string }{ // non-interfaces {"crypto.Hash", "type Hash uint"}, {"go/ast.ObjKind", "type ObjKind int"}, {"go/types.Qualifier", "type Qualifier func(*Package) string"}, {"go/types.Comparable", "func Comparable(T Type) bool"}, {"math.Pi", "const Pi untyped float"}, {"math.Sin", "func Sin(x float64) float64"}, {"go/ast.NotNilFilter", "func NotNilFilter(_ string, v reflect.Value) bool"}, {"go/internal/gcimporter.FindPkg", "func FindPkg(path string, srcDir string) (filename string, id string, err error)"}, // interfaces {"context.Context", "type Context interface{Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key any) any}"}, {"crypto.Decrypter", "type Decrypter interface{Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error); Public() PublicKey}"}, {"encoding.BinaryMarshaler", "type BinaryMarshaler interface{MarshalBinary() (data []byte, err error)}"}, {"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"}, {"io.ReadWriter", "type ReadWriter interface{Reader; Writer}"}, {"go/ast.Node", "type Node interface{End() go/token.Pos; Pos() go/token.Pos}"}, {"go/types.Type", "type Type interface{String() string; Underlying() Type}"}, } func TestImportedTypes(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } for _, test := range importedObjectTests { s := strings.Split(test.name, ".") if len(s) != 2 { t.Fatal("inconsistent test data") } importPath := s[0] objName := s[1] pkg, err := Import(make(map[string]*types2.Package), importPath, ".", nil) if err != nil { t.Error(err) continue } obj := pkg.Scope().Lookup(objName) if obj == nil { t.Errorf("%s: object not found", test.name) continue } got := types2.ObjectString(obj, types2.RelativeTo(pkg)) if got != test.want { t.Errorf("%s: got %q; want %q", test.name, got, test.want) } if named, _ := obj.Type().(*types2.Named); named != nil { verifyInterfaceMethodRecvs(t, named, 0) } } } // verifyInterfaceMethodRecvs verifies that method receiver types // are named if the methods belong to a named interface type. func verifyInterfaceMethodRecvs(t *testing.T, named *types2.Named, level int) { // avoid endless recursion in case of an embedding bug that lead to a cycle if level > 10 { t.Errorf("%s: embeds itself", named) return } iface, _ := named.Underlying().(*types2.Interface) if iface == nil { return // not an interface } // The unified IR importer always sets interface method receiver // parameters to point to the Interface type, rather than the Named. // See #49906. var want types2.Type = iface // check explicitly declared methods for i := 0; i < iface.NumExplicitMethods(); i++ { m := iface.ExplicitMethod(i) recv := m.Type().(*types2.Signature).Recv() if recv == nil { t.Errorf("%s: missing receiver type", m) continue } if recv.Type() != want { t.Errorf("%s: got recv type %s; want %s", m, recv.Type(), named) } } // check embedded interfaces (if they are named, too) for i := 0; i < iface.NumEmbeddeds(); i++ { // embedding of interfaces cannot have cycles; recursion will terminate if etype, _ := iface.EmbeddedType(i).(*types2.Named); etype != nil { verifyInterfaceMethodRecvs(t, etype, level+1) } } } func TestIssue5815(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } pkg := importPkg(t, "strings", ".") scope := pkg.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) if obj.Pkg() == nil { t.Errorf("no pkg for %s", obj) } if tname, _ := obj.(*types2.TypeName); tname != nil { named := tname.Type().(*types2.Named) for i := 0; i < named.NumMethods(); i++ { m := named.Method(i) if m.Pkg() == nil { t.Errorf("no pkg for %s", m) } } } } } // Smoke test to ensure that imported methods get the correct package. func TestCorrectMethodPackage(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } imports := make(map[string]*types2.Package) _, err := Import(imports, "net/http", ".", nil) if err != nil { t.Fatal(err) } mutex := imports["sync"].Scope().Lookup("Mutex").(*types2.TypeName).Type() obj, _, _ := types2.LookupFieldOrMethod(types2.NewPointer(mutex), false, nil, "Lock") lock := obj.(*types2.Func) if got, want := lock.Pkg().Path(), "sync"; got != want { t.Errorf("got package path %q; want %q", got, want) } } func TestIssue13566(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } tmpdir := mktmpdir(t) testoutdir := filepath.Join(tmpdir, "testdata") // b.go needs to be compiled from the output directory so that the compiler can // find the compiled package a. We pass the full path to compile() so that we // don't have to copy the file to that directory. bpath, err := filepath.Abs(filepath.Join("testdata", "b.go")) if err != nil { t.Fatal(err) } jsonExport, _, err := FindPkg("encoding/json", "testdata") if jsonExport == "" { t.Fatalf("no export data found for encoding/json: %v", err) } compile(t, "testdata", "a.go", testoutdir, map[string]string{"encoding/json": jsonExport}) compile(t, testoutdir, bpath, testoutdir, map[string]string{"testdata/a": filepath.Join(testoutdir, "a.o")}) // import must succeed (test for issue at hand) pkg := importPkg(t, "./testdata/b", tmpdir) // make sure all indirectly imported packages have names for _, imp := range pkg.Imports() { if imp.Name() == "" { t.Errorf("no name for %s package", imp.Path()) } } } func TestIssue13898(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } // import go/internal/gcimporter which imports go/types partially imports := make(map[string]*types2.Package) _, err := Import(imports, "go/internal/gcimporter", ".", nil) if err != nil { t.Fatal(err) } // look for go/types package var goTypesPkg *types2.Package for path, pkg := range imports { if path == "go/types" { goTypesPkg = pkg break } } if goTypesPkg == nil { t.Fatal("go/types not found") } // look for go/types.Object type obj := lookupObj(t, goTypesPkg.Scope(), "Object") typ, ok := obj.Type().(*types2.Named) if !ok { t.Fatalf("go/types.Object type is %v; wanted named type", typ) } // lookup go/types.Object.Pkg method m, index, indirect := types2.LookupFieldOrMethod(typ, false, nil, "Pkg") if m == nil { t.Fatalf("go/types.Object.Pkg not found (index = %v, indirect = %v)", index, indirect) } // the method must belong to go/types if m.Pkg().Path() != "go/types" { t.Fatalf("found %v; want go/types", m.Pkg()) } } func TestIssue15517(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } tmpdir := mktmpdir(t) compile(t, "testdata", "p.go", filepath.Join(tmpdir, "testdata"), nil) // Multiple imports of p must succeed without redeclaration errors. // We use an import path that's not cleaned up so that the eventual // file path for the package is different from the package path; this // will expose the error if it is present. // // (Issue: Both the textual and the binary importer used the file path // of the package to be imported as key into the shared packages map. // However, the binary importer then used the package path to identify // the imported package to mark it as complete; effectively marking the // wrong package as complete. By using an "unclean" package path, the // file and package path are different, exposing the problem if present. // The same issue occurs with vendoring.) imports := make(map[string]*types2.Package) for i := 0; i < 3; i++ { if _, err := Import(imports, "./././testdata/p", tmpdir, nil); err != nil { t.Fatal(err) } } } func TestIssue15920(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } compileAndImportPkg(t, "issue15920") } func TestIssue20046(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } // "./issue20046".V.M must exist pkg := compileAndImportPkg(t, "issue20046") obj := lookupObj(t, pkg.Scope(), "V") if m, index, indirect := types2.LookupFieldOrMethod(obj.Type(), false, nil, "M"); m == nil { t.Fatalf("V.M not found (index = %v, indirect = %v)", index, indirect) } } func TestIssue25301(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } compileAndImportPkg(t, "issue25301") } func TestIssue25596(t *testing.T) { testenv.MustHaveGoBuild(t) // This package only handles gc export data. if runtime.Compiler != "gc" { t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) } compileAndImportPkg(t, "issue25596") } func importPkg(t *testing.T, path, srcDir string) *types2.Package { pkg, err := Import(make(map[string]*types2.Package), path, srcDir, nil) if err != nil { t.Helper() t.Fatal(err) } return pkg } func compileAndImportPkg(t *testing.T, name string) *types2.Package { t.Helper() tmpdir := mktmpdir(t) compile(t, "testdata", name+".go", filepath.Join(tmpdir, "testdata"), nil) return importPkg(t, "./testdata/"+name, tmpdir) } func lookupObj(t *testing.T, scope *types2.Scope, name string) types2.Object { if obj := scope.Lookup(name); obj != nil { return obj } t.Helper() t.Fatalf("%s not found", name) return nil }
go/src/cmd/compile/internal/importer/gcimporter_test.go/0
{ "file_path": "go/src/cmd/compile/internal/importer/gcimporter_test.go", "repo_id": "go", "token_count": 6721 }
89
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package inlheur import ( "cmd/compile/internal/base" "cmd/compile/internal/ir" "cmd/compile/internal/types" "encoding/json" "fmt" "internal/buildcfg" "io" "os" "path/filepath" "sort" "strings" ) const ( debugTraceFuncs = 1 << iota debugTraceFuncFlags debugTraceResults debugTraceParams debugTraceExprClassify debugTraceCalls debugTraceScoring ) // propAnalyzer interface is used for defining one or more analyzer // helper objects, each tasked with computing some specific subset of // the properties we're interested in. The assumption is that // properties are independent, so each new analyzer that implements // this interface can operate entirely on its own. For a given analyzer // there will be a sequence of calls to nodeVisitPre and nodeVisitPost // as the nodes within a function are visited, then a followup call to // setResults so that the analyzer can transfer its results into the // final properties object. type propAnalyzer interface { nodeVisitPre(n ir.Node) nodeVisitPost(n ir.Node) setResults(funcProps *FuncProps) } // fnInlHeur contains inline heuristics state information about a // specific Go function being analyzed/considered by the inliner. Note // that in addition to constructing a fnInlHeur object by analyzing a // specific *ir.Func, there is also code in the test harness // (funcprops_test.go) that builds up fnInlHeur's by reading in and // parsing a dump. This is the reason why we have file/fname/line // fields below instead of just an *ir.Func field. type fnInlHeur struct { props *FuncProps cstab CallSiteTab fname string file string line uint } var fpmap = map[*ir.Func]fnInlHeur{} // AnalyzeFunc computes function properties for fn and its contained // closures, updating the global 'fpmap' table. It is assumed that // "CanInline" has been run on fn and on the closures that feed // directly into calls; other closures not directly called will also // be checked inlinability for inlinability here in case they are // returned as a result. func AnalyzeFunc(fn *ir.Func, canInline func(*ir.Func), budgetForFunc func(*ir.Func) int32, inlineMaxBudget int) { if fpmap == nil { // If fpmap is nil this indicates that the main inliner pass is // complete and we're doing inlining of wrappers (no heuristics // used here). return } if fn.OClosure != nil { // closures will be processed along with their outer enclosing func. return } enableDebugTraceIfEnv() if debugTrace&debugTraceFuncs != 0 { fmt.Fprintf(os.Stderr, "=-= AnalyzeFunc(%v)\n", fn) } // Build up a list containing 'fn' and any closures it contains. Along // the way, test to see whether each closure is inlinable in case // we might be returning it. funcs := []*ir.Func{fn} ir.VisitFuncAndClosures(fn, func(n ir.Node) { if clo, ok := n.(*ir.ClosureExpr); ok { funcs = append(funcs, clo.Func) } }) // Analyze the list of functions. We want to visit a given func // only after the closures it contains have been processed, so // iterate through the list in reverse order. Once a function has // been analyzed, revisit the question of whether it should be // inlinable; if it is over the default hairiness limit and it // doesn't have any interesting properties, then we don't want // the overhead of writing out its inline body. nameFinder := newNameFinder(fn) for i := len(funcs) - 1; i >= 0; i-- { f := funcs[i] if f.OClosure != nil && !f.InlinabilityChecked() { canInline(f) } funcProps := analyzeFunc(f, inlineMaxBudget, nameFinder) revisitInlinability(f, funcProps, budgetForFunc) if f.Inl != nil { f.Inl.Properties = funcProps.SerializeToString() } } disableDebugTrace() } // TearDown is invoked at the end of the main inlining pass; doing // function analysis and call site scoring is unlikely to help a lot // after this point, so nil out fpmap and other globals to reclaim // storage. func TearDown() { fpmap = nil scoreCallsCache.tab = nil scoreCallsCache.csl = nil } func analyzeFunc(fn *ir.Func, inlineMaxBudget int, nf *nameFinder) *FuncProps { if funcInlHeur, ok := fpmap[fn]; ok { return funcInlHeur.props } funcProps, fcstab := computeFuncProps(fn, inlineMaxBudget, nf) file, line := fnFileLine(fn) entry := fnInlHeur{ fname: fn.Sym().Name, file: file, line: line, props: funcProps, cstab: fcstab, } fn.SetNeverReturns(entry.props.Flags&FuncPropNeverReturns != 0) fpmap[fn] = entry if fn.Inl != nil && fn.Inl.Properties == "" { fn.Inl.Properties = entry.props.SerializeToString() } return funcProps } // revisitInlinability revisits the question of whether to continue to // treat function 'fn' as an inline candidate based on the set of // properties we've computed for it. If (for example) it has an // initial size score of 150 and no interesting properties to speak // of, then there isn't really any point to moving ahead with it as an // inline candidate. func revisitInlinability(fn *ir.Func, funcProps *FuncProps, budgetForFunc func(*ir.Func) int32) { if fn.Inl == nil { return } maxAdj := int32(LargestNegativeScoreAdjustment(fn, funcProps)) budget := budgetForFunc(fn) if fn.Inl.Cost+maxAdj > budget { fn.Inl = nil } } // computeFuncProps examines the Go function 'fn' and computes for it // a function "properties" object, to be used to drive inlining // heuristics. See comments on the FuncProps type for more info. func computeFuncProps(fn *ir.Func, inlineMaxBudget int, nf *nameFinder) (*FuncProps, CallSiteTab) { if debugTrace&debugTraceFuncs != 0 { fmt.Fprintf(os.Stderr, "=-= starting analysis of func %v:\n%+v\n", fn, fn) } funcProps := new(FuncProps) ffa := makeFuncFlagsAnalyzer(fn) analyzers := []propAnalyzer{ffa} analyzers = addResultsAnalyzer(fn, analyzers, funcProps, inlineMaxBudget, nf) analyzers = addParamsAnalyzer(fn, analyzers, funcProps, nf) runAnalyzersOnFunction(fn, analyzers) for _, a := range analyzers { a.setResults(funcProps) } cstab := computeCallSiteTable(fn, fn.Body, nil, ffa.panicPathTable(), 0, nf) return funcProps, cstab } func runAnalyzersOnFunction(fn *ir.Func, analyzers []propAnalyzer) { var doNode func(ir.Node) bool doNode = func(n ir.Node) bool { for _, a := range analyzers { a.nodeVisitPre(n) } ir.DoChildren(n, doNode) for _, a := range analyzers { a.nodeVisitPost(n) } return false } doNode(fn) } func propsForFunc(fn *ir.Func) *FuncProps { if funcInlHeur, ok := fpmap[fn]; ok { return funcInlHeur.props } else if fn.Inl != nil && fn.Inl.Properties != "" { // FIXME: considering adding some sort of cache or table // for deserialized properties of imported functions. return DeserializeFromString(fn.Inl.Properties) } return nil } func fnFileLine(fn *ir.Func) (string, uint) { p := base.Ctxt.InnermostPos(fn.Pos()) return filepath.Base(p.Filename()), p.Line() } func Enabled() bool { return buildcfg.Experiment.NewInliner || UnitTesting() } func UnitTesting() bool { return base.Debug.DumpInlFuncProps != "" || base.Debug.DumpInlCallSiteScores != 0 } // DumpFuncProps computes and caches function properties for the func // 'fn', writing out a description of the previously computed set of // properties to the file given in 'dumpfile'. Used for the // "-d=dumpinlfuncprops=..." command line flag, intended for use // primarily in unit testing. func DumpFuncProps(fn *ir.Func, dumpfile string) { if fn != nil { if fn.OClosure != nil { // closures will be processed along with their outer enclosing func. return } captureFuncDumpEntry(fn) ir.VisitFuncAndClosures(fn, func(n ir.Node) { if clo, ok := n.(*ir.ClosureExpr); ok { captureFuncDumpEntry(clo.Func) } }) } else { emitDumpToFile(dumpfile) } } // emitDumpToFile writes out the buffer function property dump entries // to a file, for unit testing. Dump entries need to be sorted by // definition line, and due to generics we need to account for the // possibility that several ir.Func's will have the same def line. func emitDumpToFile(dumpfile string) { mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC if dumpfile[0] == '+' { dumpfile = dumpfile[1:] mode = os.O_WRONLY | os.O_APPEND | os.O_CREATE } if dumpfile[0] == '%' { dumpfile = dumpfile[1:] d, b := filepath.Dir(dumpfile), filepath.Base(dumpfile) ptag := strings.ReplaceAll(types.LocalPkg.Path, "/", ":") dumpfile = d + "/" + ptag + "." + b } outf, err := os.OpenFile(dumpfile, mode, 0644) if err != nil { base.Fatalf("opening function props dump file %q: %v\n", dumpfile, err) } defer outf.Close() dumpFilePreamble(outf) atline := map[uint]uint{} sl := make([]fnInlHeur, 0, len(dumpBuffer)) for _, e := range dumpBuffer { sl = append(sl, e) atline[e.line] = atline[e.line] + 1 } sl = sortFnInlHeurSlice(sl) prevline := uint(0) for _, entry := range sl { idx := uint(0) if prevline == entry.line { idx++ } prevline = entry.line atl := atline[entry.line] if err := dumpFnPreamble(outf, &entry, nil, idx, atl); err != nil { base.Fatalf("function props dump: %v\n", err) } } dumpBuffer = nil } // captureFuncDumpEntry grabs the function properties object for 'fn' // and enqueues it for later dumping. Used for the // "-d=dumpinlfuncprops=..." command line flag, intended for use // primarily in unit testing. func captureFuncDumpEntry(fn *ir.Func) { // avoid capturing compiler-generated equality funcs. if strings.HasPrefix(fn.Sym().Name, ".eq.") { return } funcInlHeur, ok := fpmap[fn] if !ok { // Missing entry is expected for functions that are too large // to inline. We still want to write out call site scores in // this case however. funcInlHeur = fnInlHeur{cstab: callSiteTab} } if dumpBuffer == nil { dumpBuffer = make(map[*ir.Func]fnInlHeur) } if _, ok := dumpBuffer[fn]; ok { return } if debugTrace&debugTraceFuncs != 0 { fmt.Fprintf(os.Stderr, "=-= capturing dump for %v:\n", fn) } dumpBuffer[fn] = funcInlHeur } // dumpFilePreamble writes out a file-level preamble for a given // Go function as part of a function properties dump. func dumpFilePreamble(w io.Writer) { fmt.Fprintf(w, "// DO NOT EDIT (use 'go test -v -update-expected' instead.)\n") fmt.Fprintf(w, "// See cmd/compile/internal/inline/inlheur/testdata/props/README.txt\n") fmt.Fprintf(w, "// for more information on the format of this file.\n") fmt.Fprintf(w, "// %s\n", preambleDelimiter) } // dumpFnPreamble writes out a function-level preamble for a given // Go function as part of a function properties dump. See the // README.txt file in testdata/props for more on the format of // this preamble. func dumpFnPreamble(w io.Writer, funcInlHeur *fnInlHeur, ecst encodedCallSiteTab, idx, atl uint) error { fmt.Fprintf(w, "// %s %s %d %d %d\n", funcInlHeur.file, funcInlHeur.fname, funcInlHeur.line, idx, atl) // emit props as comments, followed by delimiter fmt.Fprintf(w, "%s// %s\n", funcInlHeur.props.ToString("// "), comDelimiter) data, err := json.Marshal(funcInlHeur.props) if err != nil { return fmt.Errorf("marshal error %v\n", err) } fmt.Fprintf(w, "// %s\n", string(data)) dumpCallSiteComments(w, funcInlHeur.cstab, ecst) fmt.Fprintf(w, "// %s\n", fnDelimiter) return nil } // sortFnInlHeurSlice sorts a slice of fnInlHeur based on // the starting line of the function definition, then by name. func sortFnInlHeurSlice(sl []fnInlHeur) []fnInlHeur { sort.SliceStable(sl, func(i, j int) bool { if sl[i].line != sl[j].line { return sl[i].line < sl[j].line } return sl[i].fname < sl[j].fname }) return sl } // delimiters written to various preambles to make parsing of // dumps easier. const preambleDelimiter = "<endfilepreamble>" const fnDelimiter = "<endfuncpreamble>" const comDelimiter = "<endpropsdump>" const csDelimiter = "<endcallsites>" // dumpBuffer stores up function properties dumps when // "-d=dumpinlfuncprops=..." is in effect. var dumpBuffer map[*ir.Func]fnInlHeur
go/src/cmd/compile/internal/inline/inlheur/analyze.go/0
{ "file_path": "go/src/cmd/compile/internal/inline/inlheur/analyze.go", "repo_id": "go", "token_count": 4396 }
90
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by "stringer -type pstate"; DO NOT EDIT. package inlheur import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[psNoInfo-0] _ = x[psCallsPanic-1] _ = x[psMayReturn-2] _ = x[psTop-3] } const _pstate_name = "psNoInfopsCallsPanicpsMayReturnpsTop" var _pstate_index = [...]uint8{0, 8, 20, 31, 36} func (i pstate) String() string { if i < 0 || i >= pstate(len(_pstate_index)-1) { return "pstate(" + strconv.FormatInt(int64(i), 10) + ")" } return _pstate_name[_pstate_index[i]:_pstate_index[i+1]] }
go/src/cmd/compile/internal/inline/inlheur/pstate_string.go/0
{ "file_path": "go/src/cmd/compile/internal/inline/inlheur/pstate_string.go", "repo_id": "go", "token_count": 312 }
91
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build debugtrace package inlheur import ( "os" "strconv" ) var debugTrace = 0 func enableDebugTrace(x int) { debugTrace = x } func enableDebugTraceIfEnv() { v := os.Getenv("DEBUG_TRACE_INLHEUR") if v == "" { return } if v[0] == '*' { if !UnitTesting() { return } v = v[1:] } i, err := strconv.Atoi(v) if err != nil { return } debugTrace = i } func disableDebugTrace() { debugTrace = 0 }
go/src/cmd/compile/internal/inline/inlheur/trace_on.go/0
{ "file_path": "go/src/cmd/compile/internal/inline/inlheur/trace_on.go", "repo_id": "go", "token_count": 245 }
92
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // IR visitors for walking the IR tree. // // The lowest level helpers are DoChildren and EditChildren, which // nodes help implement and provide control over whether and when // recursion happens during the walk of the IR. // // Although these are both useful directly, two simpler patterns // are fairly common and also provided: Visit and Any. package ir // DoChildren calls do(x) on each of n's non-nil child nodes x. // If any call returns true, DoChildren stops and returns true. // Otherwise, DoChildren returns false. // // Note that DoChildren(n, do) only calls do(x) for n's immediate children. // If x's children should be processed, then do(x) must call DoChildren(x, do). // // DoChildren allows constructing general traversals of the IR graph // that can stop early if needed. The most general usage is: // // var do func(ir.Node) bool // do = func(x ir.Node) bool { // ... processing BEFORE visiting children ... // if ... should visit children ... { // ir.DoChildren(x, do) // ... processing AFTER visiting children ... // } // if ... should stop parent DoChildren call from visiting siblings ... { // return true // } // return false // } // do(root) // // Since DoChildren does not return true itself, if the do function // never wants to stop the traversal, it can assume that DoChildren // itself will always return false, simplifying to: // // var do func(ir.Node) bool // do = func(x ir.Node) bool { // ... processing BEFORE visiting children ... // if ... should visit children ... { // ir.DoChildren(x, do) // } // ... processing AFTER visiting children ... // return false // } // do(root) // // The Visit function illustrates a further simplification of the pattern, // only processing before visiting children and never stopping: // // func Visit(n ir.Node, visit func(ir.Node)) { // if n == nil { // return // } // var do func(ir.Node) bool // do = func(x ir.Node) bool { // visit(x) // return ir.DoChildren(x, do) // } // do(n) // } // // The Any function illustrates a different simplification of the pattern, // visiting each node and then its children, recursively, until finding // a node x for which cond(x) returns true, at which point the entire // traversal stops and returns true. // // func Any(n ir.Node, cond(ir.Node) bool) bool { // if n == nil { // return false // } // var do func(ir.Node) bool // do = func(x ir.Node) bool { // return cond(x) || ir.DoChildren(x, do) // } // return do(n) // } // // Visit and Any are presented above as examples of how to use // DoChildren effectively, but of course, usage that fits within the // simplifications captured by Visit or Any will be best served // by directly calling the ones provided by this package. func DoChildren(n Node, do func(Node) bool) bool { if n == nil { return false } return n.doChildren(do) } // Visit visits each non-nil node x in the IR tree rooted at n // in a depth-first preorder traversal, calling visit on each node visited. func Visit(n Node, visit func(Node)) { if n == nil { return } var do func(Node) bool do = func(x Node) bool { visit(x) return DoChildren(x, do) } do(n) } // VisitList calls Visit(x, visit) for each node x in the list. func VisitList(list Nodes, visit func(Node)) { for _, x := range list { Visit(x, visit) } } // VisitFuncAndClosures calls visit on each non-nil node in fn.Body, // including any nested closure bodies. func VisitFuncAndClosures(fn *Func, visit func(n Node)) { VisitList(fn.Body, func(n Node) { visit(n) if n, ok := n.(*ClosureExpr); ok && n.Op() == OCLOSURE { VisitFuncAndClosures(n.Func, visit) } }) } // Any looks for a non-nil node x in the IR tree rooted at n // for which cond(x) returns true. // Any considers nodes in a depth-first, preorder traversal. // When Any finds a node x such that cond(x) is true, // Any ends the traversal and returns true immediately. // Otherwise Any returns false after completing the entire traversal. func Any(n Node, cond func(Node) bool) bool { if n == nil { return false } var do func(Node) bool do = func(x Node) bool { return cond(x) || DoChildren(x, do) } return do(n) } // AnyList calls Any(x, cond) for each node x in the list, in order. // If any call returns true, AnyList stops and returns true. // Otherwise, AnyList returns false after calling Any(x, cond) // for every x in the list. func AnyList(list Nodes, cond func(Node) bool) bool { for _, x := range list { if Any(x, cond) { return true } } return false } // EditChildren edits the child nodes of n, replacing each child x with edit(x). // // Note that EditChildren(n, edit) only calls edit(x) for n's immediate children. // If x's children should be processed, then edit(x) must call EditChildren(x, edit). // // EditChildren allows constructing general editing passes of the IR graph. // The most general usage is: // // var edit func(ir.Node) ir.Node // edit = func(x ir.Node) ir.Node { // ... processing BEFORE editing children ... // if ... should edit children ... { // EditChildren(x, edit) // ... processing AFTER editing children ... // } // ... return x ... // } // n = edit(n) // // EditChildren edits the node in place. To edit a copy, call Copy first. // As an example, a simple deep copy implementation would be: // // func deepCopy(n ir.Node) ir.Node { // var edit func(ir.Node) ir.Node // edit = func(x ir.Node) ir.Node { // x = ir.Copy(x) // ir.EditChildren(x, edit) // return x // } // return edit(n) // } // // Of course, in this case it is better to call ir.DeepCopy than to build one anew. func EditChildren(n Node, edit func(Node) Node) { if n == nil { return } n.editChildren(edit) } // EditChildrenWithHidden is like EditChildren, but also edits // Node-typed fields tagged with `mknode:"-"`. // // TODO(mdempsky): Remove the `mknode:"-"` tags so this function can // go away. func EditChildrenWithHidden(n Node, edit func(Node) Node) { if n == nil { return } n.editChildrenWithHidden(edit) }
go/src/cmd/compile/internal/ir/visit.go/0
{ "file_path": "go/src/cmd/compile/internal/ir/visit.go", "repo_id": "go", "token_count": 2015 }
93
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package mips import ( "cmd/compile/internal/base" "cmd/compile/internal/objw" "cmd/compile/internal/types" "cmd/internal/obj" "cmd/internal/obj/mips" ) // TODO(mips): implement DUFFZERO func zerorange(pp *objw.Progs, p *obj.Prog, off, cnt int64, _ *uint32) *obj.Prog { if cnt == 0 { return p } if cnt < int64(4*types.PtrSize) { for i := int64(0); i < cnt; i += int64(types.PtrSize) { p = pp.Append(p, mips.AMOVW, obj.TYPE_REG, mips.REGZERO, 0, obj.TYPE_MEM, mips.REGSP, base.Ctxt.Arch.FixedFrameSize+off+i) } } else { //fmt.Printf("zerorange frame:%v, lo: %v, hi:%v \n", frame ,lo, hi) // ADD $(FIXED_FRAME+frame+lo-4), SP, r1 // ADD $cnt, r1, r2 // loop: // MOVW R0, (Widthptr)r1 // ADD $Widthptr, r1 // BNE r1, r2, loop p = pp.Append(p, mips.AADD, obj.TYPE_CONST, 0, base.Ctxt.Arch.FixedFrameSize+off-4, obj.TYPE_REG, mips.REGRT1, 0) p.Reg = mips.REGSP p = pp.Append(p, mips.AADD, obj.TYPE_CONST, 0, cnt, obj.TYPE_REG, mips.REGRT2, 0) p.Reg = mips.REGRT1 p = pp.Append(p, mips.AMOVW, obj.TYPE_REG, mips.REGZERO, 0, obj.TYPE_MEM, mips.REGRT1, int64(types.PtrSize)) p1 := p p = pp.Append(p, mips.AADD, obj.TYPE_CONST, 0, int64(types.PtrSize), obj.TYPE_REG, mips.REGRT1, 0) p = pp.Append(p, mips.ABNE, obj.TYPE_REG, mips.REGRT1, 0, obj.TYPE_BRANCH, 0, 0) p.Reg = mips.REGRT2 p.To.SetTarget(p1) } return p } func ginsnop(pp *objw.Progs) *obj.Prog { p := pp.Prog(mips.ANOOP) return p }
go/src/cmd/compile/internal/mips/ggen.go/0
{ "file_path": "go/src/cmd/compile/internal/mips/ggen.go", "repo_id": "go", "token_count": 797 }
94
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package noder import ( "encoding/hex" "fmt" "go/constant" "internal/buildcfg" "internal/pkgbits" "path/filepath" "strings" "cmd/compile/internal/base" "cmd/compile/internal/dwarfgen" "cmd/compile/internal/inline" "cmd/compile/internal/inline/interleaved" "cmd/compile/internal/ir" "cmd/compile/internal/objw" "cmd/compile/internal/reflectdata" "cmd/compile/internal/staticinit" "cmd/compile/internal/typecheck" "cmd/compile/internal/types" "cmd/internal/notsha256" "cmd/internal/obj" "cmd/internal/objabi" "cmd/internal/src" ) // This file implements cmd/compile backend's reader for the Unified // IR export data. // A pkgReader reads Unified IR export data. type pkgReader struct { pkgbits.PkgDecoder // Indices for encoded things; lazily populated as needed. // // Note: Objects (i.e., ir.Names) are lazily instantiated by // populating their types.Sym.Def; see objReader below. posBases []*src.PosBase pkgs []*types.Pkg typs []*types.Type // offset for rewriting the given (absolute!) index into the output, // but bitwise inverted so we can detect if we're missing the entry // or not. newindex []pkgbits.Index } func newPkgReader(pr pkgbits.PkgDecoder) *pkgReader { return &pkgReader{ PkgDecoder: pr, posBases: make([]*src.PosBase, pr.NumElems(pkgbits.RelocPosBase)), pkgs: make([]*types.Pkg, pr.NumElems(pkgbits.RelocPkg)), typs: make([]*types.Type, pr.NumElems(pkgbits.RelocType)), newindex: make([]pkgbits.Index, pr.TotalElems()), } } // A pkgReaderIndex compactly identifies an index (and its // corresponding dictionary) within a package's export data. type pkgReaderIndex struct { pr *pkgReader idx pkgbits.Index dict *readerDict methodSym *types.Sym synthetic func(pos src.XPos, r *reader) } func (pri pkgReaderIndex) asReader(k pkgbits.RelocKind, marker pkgbits.SyncMarker) *reader { if pri.synthetic != nil { return &reader{synthetic: pri.synthetic} } r := pri.pr.newReader(k, pri.idx, marker) r.dict = pri.dict r.methodSym = pri.methodSym return r } func (pr *pkgReader) newReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader { return &reader{ Decoder: pr.NewDecoder(k, idx, marker), p: pr, } } // A reader provides APIs for reading an individual element. type reader struct { pkgbits.Decoder p *pkgReader dict *readerDict // TODO(mdempsky): The state below is all specific to reading // function bodies. It probably makes sense to split it out // separately so that it doesn't take up space in every reader // instance. curfn *ir.Func locals []*ir.Name closureVars []*ir.Name // funarghack is used during inlining to suppress setting // Field.Nname to the inlined copies of the parameters. This is // necessary because we reuse the same types.Type as the original // function, and most of the compiler still relies on field.Nname to // find parameters/results. funarghack bool // methodSym is the name of method's name, if reading a method. // It's nil if reading a normal function or closure body. methodSym *types.Sym // dictParam is the .dict param, if any. dictParam *ir.Name // synthetic is a callback function to construct a synthetic // function body. It's used for creating the bodies of function // literals used to curry arguments to shaped functions. synthetic func(pos src.XPos, r *reader) // scopeVars is a stack tracking the number of variables declared in // the current function at the moment each open scope was opened. scopeVars []int marker dwarfgen.ScopeMarker lastCloseScopePos src.XPos // === details for handling inline body expansion === // If we're reading in a function body because of inlining, this is // the call that we're inlining for. inlCaller *ir.Func inlCall *ir.CallExpr inlFunc *ir.Func inlTreeIndex int inlPosBases map[*src.PosBase]*src.PosBase // suppressInlPos tracks whether position base rewriting for // inlining should be suppressed. See funcLit. suppressInlPos int delayResults bool // Label to return to. retlabel *types.Sym } // A readerDict represents an instantiated "compile-time dictionary," // used for resolving any derived types needed for instantiating a // generic object. // // A compile-time dictionary can either be "shaped" or "non-shaped." // Shaped compile-time dictionaries are only used for instantiating // shaped type definitions and function bodies, while non-shaped // compile-time dictionaries are used for instantiating runtime // dictionaries. type readerDict struct { shaped bool // whether this is a shaped dictionary // baseSym is the symbol for the object this dictionary belongs to. // If the object is an instantiated function or defined type, then // baseSym is the mangled symbol, including any type arguments. baseSym *types.Sym // For non-shaped dictionaries, shapedObj is a reference to the // corresponding shaped object (always a function or defined type). shapedObj *ir.Name // targs holds the implicit and explicit type arguments in use for // reading the current object. For example: // // func F[T any]() { // type X[U any] struct { t T; u U } // var _ X[string] // } // // var _ = F[int] // // While instantiating F[int], we need to in turn instantiate // X[string]. [int] and [string] are explicit type arguments for F // and X, respectively; but [int] is also the implicit type // arguments for X. // // (As an analogy to function literals, explicits are the function // literal's formal parameters, while implicits are variables // captured by the function literal.) targs []*types.Type // implicits counts how many of types within targs are implicit type // arguments; the rest are explicit. implicits int derived []derivedInfo // reloc index of the derived type's descriptor derivedTypes []*types.Type // slice of previously computed derived types // These slices correspond to entries in the runtime dictionary. typeParamMethodExprs []readerMethodExprInfo subdicts []objInfo rtypes []typeInfo itabs []itabInfo } type readerMethodExprInfo struct { typeParamIdx int method *types.Sym } func setType(n ir.Node, typ *types.Type) { n.SetType(typ) n.SetTypecheck(1) } func setValue(name *ir.Name, val constant.Value) { name.SetVal(val) name.Defn = nil } // @@@ Positions // pos reads a position from the bitstream. func (r *reader) pos() src.XPos { return base.Ctxt.PosTable.XPos(r.pos0()) } // origPos reads a position from the bitstream, and returns both the // original raw position and an inlining-adjusted position. func (r *reader) origPos() (origPos, inlPos src.XPos) { r.suppressInlPos++ origPos = r.pos() r.suppressInlPos-- inlPos = r.inlPos(origPos) return } func (r *reader) pos0() src.Pos { r.Sync(pkgbits.SyncPos) if !r.Bool() { return src.NoPos } posBase := r.posBase() line := r.Uint() col := r.Uint() return src.MakePos(posBase, line, col) } // posBase reads a position base from the bitstream. func (r *reader) posBase() *src.PosBase { return r.inlPosBase(r.p.posBaseIdx(r.Reloc(pkgbits.RelocPosBase))) } // posBaseIdx returns the specified position base, reading it first if // needed. func (pr *pkgReader) posBaseIdx(idx pkgbits.Index) *src.PosBase { if b := pr.posBases[idx]; b != nil { return b } r := pr.newReader(pkgbits.RelocPosBase, idx, pkgbits.SyncPosBase) var b *src.PosBase absFilename := r.String() filename := absFilename // For build artifact stability, the export data format only // contains the "absolute" filename as returned by objabi.AbsFile. // However, some tests (e.g., test/run.go's asmcheck tests) expect // to see the full, original filename printed out. Re-expanding // "$GOROOT" to buildcfg.GOROOT is a close-enough approximation to // satisfy this. // // The export data format only ever uses slash paths // (for cross-operating-system reproducible builds), // but error messages need to use native paths (backslash on Windows) // as if they had been specified on the command line. // (The go command always passes native paths to the compiler.) const dollarGOROOT = "$GOROOT" if buildcfg.GOROOT != "" && strings.HasPrefix(filename, dollarGOROOT) { filename = filepath.FromSlash(buildcfg.GOROOT + filename[len(dollarGOROOT):]) } if r.Bool() { b = src.NewFileBase(filename, absFilename) } else { pos := r.pos0() line := r.Uint() col := r.Uint() b = src.NewLinePragmaBase(pos, filename, absFilename, line, col) } pr.posBases[idx] = b return b } // inlPosBase returns the inlining-adjusted src.PosBase corresponding // to oldBase, which must be a non-inlined position. When not // inlining, this is just oldBase. func (r *reader) inlPosBase(oldBase *src.PosBase) *src.PosBase { if index := oldBase.InliningIndex(); index >= 0 { base.Fatalf("oldBase %v already has inlining index %v", oldBase, index) } if r.inlCall == nil || r.suppressInlPos != 0 { return oldBase } if newBase, ok := r.inlPosBases[oldBase]; ok { return newBase } newBase := src.NewInliningBase(oldBase, r.inlTreeIndex) r.inlPosBases[oldBase] = newBase return newBase } // inlPos returns the inlining-adjusted src.XPos corresponding to // xpos, which must be a non-inlined position. When not inlining, this // is just xpos. func (r *reader) inlPos(xpos src.XPos) src.XPos { pos := base.Ctxt.PosTable.Pos(xpos) pos.SetBase(r.inlPosBase(pos.Base())) return base.Ctxt.PosTable.XPos(pos) } // @@@ Packages // pkg reads a package reference from the bitstream. func (r *reader) pkg() *types.Pkg { r.Sync(pkgbits.SyncPkg) return r.p.pkgIdx(r.Reloc(pkgbits.RelocPkg)) } // pkgIdx returns the specified package from the export data, reading // it first if needed. func (pr *pkgReader) pkgIdx(idx pkgbits.Index) *types.Pkg { if pkg := pr.pkgs[idx]; pkg != nil { return pkg } pkg := pr.newReader(pkgbits.RelocPkg, idx, pkgbits.SyncPkgDef).doPkg() pr.pkgs[idx] = pkg return pkg } // doPkg reads a package definition from the bitstream. func (r *reader) doPkg() *types.Pkg { path := r.String() switch path { case "": path = r.p.PkgPath() case "builtin": return types.BuiltinPkg case "unsafe": return types.UnsafePkg } name := r.String() pkg := types.NewPkg(path, "") if pkg.Name == "" { pkg.Name = name } else { base.Assertf(pkg.Name == name, "package %q has name %q, but want %q", pkg.Path, pkg.Name, name) } return pkg } // @@@ Types func (r *reader) typ() *types.Type { return r.typWrapped(true) } // typWrapped is like typ, but allows suppressing generation of // unnecessary wrappers as a compile-time optimization. func (r *reader) typWrapped(wrapped bool) *types.Type { return r.p.typIdx(r.typInfo(), r.dict, wrapped) } func (r *reader) typInfo() typeInfo { r.Sync(pkgbits.SyncType) if r.Bool() { return typeInfo{idx: pkgbits.Index(r.Len()), derived: true} } return typeInfo{idx: r.Reloc(pkgbits.RelocType), derived: false} } // typListIdx returns a list of the specified types, resolving derived // types within the given dictionary. func (pr *pkgReader) typListIdx(infos []typeInfo, dict *readerDict) []*types.Type { typs := make([]*types.Type, len(infos)) for i, info := range infos { typs[i] = pr.typIdx(info, dict, true) } return typs } // typIdx returns the specified type. If info specifies a derived // type, it's resolved within the given dictionary. If wrapped is // true, then method wrappers will be generated, if appropriate. func (pr *pkgReader) typIdx(info typeInfo, dict *readerDict, wrapped bool) *types.Type { idx := info.idx var where **types.Type if info.derived { where = &dict.derivedTypes[idx] idx = dict.derived[idx].idx } else { where = &pr.typs[idx] } if typ := *where; typ != nil { return typ } r := pr.newReader(pkgbits.RelocType, idx, pkgbits.SyncTypeIdx) r.dict = dict typ := r.doTyp() if typ == nil { base.Fatalf("doTyp returned nil for info=%v", info) } // For recursive type declarations involving interfaces and aliases, // above r.doTyp() call may have already set pr.typs[idx], so just // double check and return the type. // // Example: // // type F = func(I) // // type I interface { // m(F) // } // // The writer writes data types in following index order: // // 0: func(I) // 1: I // 2: interface{m(func(I))} // // The reader resolves it in following index order: // // 0 -> 1 -> 2 -> 0 -> 1 // // and can divide in logically 2 steps: // // - 0 -> 1 : first time the reader reach type I, // it creates new named type with symbol I. // // - 2 -> 0 -> 1: the reader ends up reaching symbol I again, // now the symbol I was setup in above step, so // the reader just return the named type. // // Now, the functions called return, the pr.typs looks like below: // // - 0 -> 1 -> 2 -> 0 : [<T> I <T>] // - 0 -> 1 -> 2 : [func(I) I <T>] // - 0 -> 1 : [func(I) I interface { "".m(func("".I)) }] // // The idx 1, corresponding with type I was resolved successfully // after r.doTyp() call. if prev := *where; prev != nil { return prev } if wrapped { // Only cache if we're adding wrappers, so that other callers that // find a cached type know it was wrapped. *where = typ r.needWrapper(typ) } if !typ.IsUntyped() { types.CheckSize(typ) } return typ } func (r *reader) doTyp() *types.Type { switch tag := pkgbits.CodeType(r.Code(pkgbits.SyncType)); tag { default: panic(fmt.Sprintf("unexpected type: %v", tag)) case pkgbits.TypeBasic: return *basics[r.Len()] case pkgbits.TypeNamed: obj := r.obj() assert(obj.Op() == ir.OTYPE) return obj.Type() case pkgbits.TypeTypeParam: return r.dict.targs[r.Len()] case pkgbits.TypeArray: len := int64(r.Uint64()) return types.NewArray(r.typ(), len) case pkgbits.TypeChan: dir := dirs[r.Len()] return types.NewChan(r.typ(), dir) case pkgbits.TypeMap: return types.NewMap(r.typ(), r.typ()) case pkgbits.TypePointer: return types.NewPtr(r.typ()) case pkgbits.TypeSignature: return r.signature(nil) case pkgbits.TypeSlice: return types.NewSlice(r.typ()) case pkgbits.TypeStruct: return r.structType() case pkgbits.TypeInterface: return r.interfaceType() case pkgbits.TypeUnion: return r.unionType() } } func (r *reader) unionType() *types.Type { // In the types1 universe, we only need to handle value types. // Impure interfaces (i.e., interfaces with non-trivial type sets // like "int | string") can only appear as type parameter bounds, // and this is enforced by the types2 type checker. // // However, type unions can still appear in pure interfaces if the // type union is equivalent to "any". E.g., typeparam/issue52124.go // declares variables with the type "interface { any | int }". // // To avoid needing to represent type unions in types1 (since we // don't have any uses for that today anyway), we simply fold them // to "any". // TODO(mdempsky): Restore consistency check to make sure folding to // "any" is safe. This is unfortunately tricky, because a pure // interface can reference impure interfaces too, including // cyclically (#60117). if false { pure := false for i, n := 0, r.Len(); i < n; i++ { _ = r.Bool() // tilde term := r.typ() if term.IsEmptyInterface() { pure = true } } if !pure { base.Fatalf("impure type set used in value type") } } return types.Types[types.TINTER] } func (r *reader) interfaceType() *types.Type { nmethods, nembeddeds := r.Len(), r.Len() implicit := nmethods == 0 && nembeddeds == 1 && r.Bool() assert(!implicit) // implicit interfaces only appear in constraints fields := make([]*types.Field, nmethods+nembeddeds) methods, embeddeds := fields[:nmethods], fields[nmethods:] for i := range methods { methods[i] = types.NewField(r.pos(), r.selector(), r.signature(types.FakeRecv())) } for i := range embeddeds { embeddeds[i] = types.NewField(src.NoXPos, nil, r.typ()) } if len(fields) == 0 { return types.Types[types.TINTER] // empty interface } return types.NewInterface(fields) } func (r *reader) structType() *types.Type { fields := make([]*types.Field, r.Len()) for i := range fields { field := types.NewField(r.pos(), r.selector(), r.typ()) field.Note = r.String() if r.Bool() { field.Embedded = 1 } fields[i] = field } return types.NewStruct(fields) } func (r *reader) signature(recv *types.Field) *types.Type { r.Sync(pkgbits.SyncSignature) params := r.params() results := r.params() if r.Bool() { // variadic params[len(params)-1].SetIsDDD(true) } return types.NewSignature(recv, params, results) } func (r *reader) params() []*types.Field { r.Sync(pkgbits.SyncParams) params := make([]*types.Field, r.Len()) for i := range params { params[i] = r.param() } return params } func (r *reader) param() *types.Field { r.Sync(pkgbits.SyncParam) return types.NewField(r.pos(), r.localIdent(), r.typ()) } // @@@ Objects // objReader maps qualified identifiers (represented as *types.Sym) to // a pkgReader and corresponding index that can be used for reading // that object's definition. var objReader = map[*types.Sym]pkgReaderIndex{} // obj reads an instantiated object reference from the bitstream. func (r *reader) obj() ir.Node { return r.p.objInstIdx(r.objInfo(), r.dict, false) } // objInfo reads an instantiated object reference from the bitstream // and returns the encoded reference to it, without instantiating it. func (r *reader) objInfo() objInfo { r.Sync(pkgbits.SyncObject) assert(!r.Bool()) // TODO(mdempsky): Remove; was derived func inst. idx := r.Reloc(pkgbits.RelocObj) explicits := make([]typeInfo, r.Len()) for i := range explicits { explicits[i] = r.typInfo() } return objInfo{idx, explicits} } // objInstIdx returns the encoded, instantiated object. If shaped is // true, then the shaped variant of the object is returned instead. func (pr *pkgReader) objInstIdx(info objInfo, dict *readerDict, shaped bool) ir.Node { explicits := pr.typListIdx(info.explicits, dict) var implicits []*types.Type if dict != nil { implicits = dict.targs } return pr.objIdx(info.idx, implicits, explicits, shaped) } // objIdx returns the specified object, instantiated with the given // type arguments, if any. // If shaped is true, then the shaped variant of the object is returned // instead. func (pr *pkgReader) objIdx(idx pkgbits.Index, implicits, explicits []*types.Type, shaped bool) ir.Node { n, err := pr.objIdxMayFail(idx, implicits, explicits, shaped) if err != nil { base.Fatalf("%v", err) } return n } // objIdxMayFail is equivalent to objIdx, but returns an error rather than // failing the build if this object requires type arguments and the incorrect // number of type arguments were passed. // // Other sources of internal failure (such as duplicate definitions) still fail // the build. func (pr *pkgReader) objIdxMayFail(idx pkgbits.Index, implicits, explicits []*types.Type, shaped bool) (ir.Node, error) { rname := pr.newReader(pkgbits.RelocName, idx, pkgbits.SyncObject1) _, sym := rname.qualifiedIdent() tag := pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj)) if tag == pkgbits.ObjStub { assert(!sym.IsBlank()) switch sym.Pkg { case types.BuiltinPkg, types.UnsafePkg: return sym.Def.(ir.Node), nil } if pri, ok := objReader[sym]; ok { return pri.pr.objIdxMayFail(pri.idx, nil, explicits, shaped) } if sym.Pkg.Path == "runtime" { return typecheck.LookupRuntime(sym.Name), nil } base.Fatalf("unresolved stub: %v", sym) } dict, err := pr.objDictIdx(sym, idx, implicits, explicits, shaped) if err != nil { return nil, err } sym = dict.baseSym if !sym.IsBlank() && sym.Def != nil { return sym.Def.(*ir.Name), nil } r := pr.newReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1) rext := pr.newReader(pkgbits.RelocObjExt, idx, pkgbits.SyncObject1) r.dict = dict rext.dict = dict do := func(op ir.Op, hasTParams bool) *ir.Name { pos := r.pos() setBasePos(pos) if hasTParams { r.typeParamNames() } name := ir.NewDeclNameAt(pos, op, sym) name.Class = ir.PEXTERN // may be overridden later if !sym.IsBlank() { if sym.Def != nil { base.FatalfAt(name.Pos(), "already have a definition for %v", name) } assert(sym.Def == nil) sym.Def = name } return name } switch tag { default: panic("unexpected object") case pkgbits.ObjAlias: name := do(ir.OTYPE, false) // Clumsy dance: the r.typ() call here might recursively find this // type alias name, before we've set its type (#66873). So we // temporarily clear sym.Def and then restore it later, if still // unset. hack := sym.Def == name if hack { sym.Def = nil } typ := r.typ() if hack { if sym.Def != nil { name = sym.Def.(*ir.Name) assert(name.Type() == typ) return name, nil } sym.Def = name } setType(name, typ) name.SetAlias(true) return name, nil case pkgbits.ObjConst: name := do(ir.OLITERAL, false) typ := r.typ() val := FixValue(typ, r.Value()) setType(name, typ) setValue(name, val) return name, nil case pkgbits.ObjFunc: if sym.Name == "init" { sym = Renameinit() } npos := r.pos() setBasePos(npos) r.typeParamNames() typ := r.signature(nil) fpos := r.pos() fn := ir.NewFunc(fpos, npos, sym, typ) name := fn.Nname if !sym.IsBlank() { if sym.Def != nil { base.FatalfAt(name.Pos(), "already have a definition for %v", name) } assert(sym.Def == nil) sym.Def = name } if r.hasTypeParams() { name.Func.SetDupok(true) if r.dict.shaped { setType(name, shapeSig(name.Func, r.dict)) } else { todoDicts = append(todoDicts, func() { r.dict.shapedObj = pr.objIdx(idx, implicits, explicits, true).(*ir.Name) }) } } rext.funcExt(name, nil) return name, nil case pkgbits.ObjType: name := do(ir.OTYPE, true) typ := types.NewNamed(name) setType(name, typ) if r.hasTypeParams() && r.dict.shaped { typ.SetHasShape(true) } // Important: We need to do this before SetUnderlying. rext.typeExt(name) // We need to defer CheckSize until we've called SetUnderlying to // handle recursive types. types.DeferCheckSize() typ.SetUnderlying(r.typWrapped(false)) types.ResumeCheckSize() if r.hasTypeParams() && !r.dict.shaped { todoDicts = append(todoDicts, func() { r.dict.shapedObj = pr.objIdx(idx, implicits, explicits, true).(*ir.Name) }) } methods := make([]*types.Field, r.Len()) for i := range methods { methods[i] = r.method(rext) } if len(methods) != 0 { typ.SetMethods(methods) } if !r.dict.shaped { r.needWrapper(typ) } return name, nil case pkgbits.ObjVar: name := do(ir.ONAME, false) setType(name, r.typ()) rext.varExt(name) return name, nil } } func (dict *readerDict) mangle(sym *types.Sym) *types.Sym { if !dict.hasTypeParams() { return sym } // If sym is a locally defined generic type, we need the suffix to // stay at the end after mangling so that types/fmt.go can strip it // out again when writing the type's runtime descriptor (#54456). base, suffix := types.SplitVargenSuffix(sym.Name) var buf strings.Builder buf.WriteString(base) buf.WriteByte('[') for i, targ := range dict.targs { if i > 0 { if i == dict.implicits { buf.WriteByte(';') } else { buf.WriteByte(',') } } buf.WriteString(targ.LinkString()) } buf.WriteByte(']') buf.WriteString(suffix) return sym.Pkg.Lookup(buf.String()) } // shapify returns the shape type for targ. // // If basic is true, then the type argument is used to instantiate a // type parameter whose constraint is a basic interface. func shapify(targ *types.Type, basic bool) *types.Type { if targ.Kind() == types.TFORW { if targ.IsFullyInstantiated() { // For recursive instantiated type argument, it may still be a TFORW // when shapifying happens. If we don't have targ's underlying type, // shapify won't work. The worst case is we end up not reusing code // optimally in some tricky cases. if base.Debug.Shapify != 0 { base.Warn("skipping shaping of recursive type %v", targ) } if targ.HasShape() { return targ } } else { base.Fatalf("%v is missing its underlying type", targ) } } // For fully instantiated shape interface type, use it as-is. Otherwise, the instantiation // involved recursive generic interface may cause mismatching in function signature, see issue #65362. if targ.Kind() == types.TINTER && targ.IsFullyInstantiated() && targ.HasShape() { return targ } // When a pointer type is used to instantiate a type parameter // constrained by a basic interface, we know the pointer's element // type can't matter to the generated code. In this case, we can use // an arbitrary pointer type as the shape type. (To match the // non-unified frontend, we use `*byte`.) // // Otherwise, we simply use the type's underlying type as its shape. // // TODO(mdempsky): It should be possible to do much more aggressive // shaping still; e.g., collapsing all pointer-shaped types into a // common type, collapsing scalars of the same size/alignment into a // common type, recursively shaping the element types of composite // types, and discarding struct field names and tags. However, we'll // need to start tracking how type parameters are actually used to // implement some of these optimizations. under := targ.Underlying() if basic && targ.IsPtr() && !targ.Elem().NotInHeap() { under = types.NewPtr(types.Types[types.TUINT8]) } // Hash long type names to bound symbol name length seen by users, // particularly for large protobuf structs (#65030). uls := under.LinkString() if base.Debug.MaxShapeLen != 0 && len(uls) > base.Debug.MaxShapeLen { h := notsha256.Sum256([]byte(uls)) uls = hex.EncodeToString(h[:]) } sym := types.ShapePkg.Lookup(uls) if sym.Def == nil { name := ir.NewDeclNameAt(under.Pos(), ir.OTYPE, sym) typ := types.NewNamed(name) typ.SetUnderlying(under) sym.Def = typed(typ, name) } res := sym.Def.Type() assert(res.IsShape()) assert(res.HasShape()) return res } // objDictIdx reads and returns the specified object dictionary. func (pr *pkgReader) objDictIdx(sym *types.Sym, idx pkgbits.Index, implicits, explicits []*types.Type, shaped bool) (*readerDict, error) { r := pr.newReader(pkgbits.RelocObjDict, idx, pkgbits.SyncObject1) dict := readerDict{ shaped: shaped, } nimplicits := r.Len() nexplicits := r.Len() if nimplicits > len(implicits) || nexplicits != len(explicits) { return nil, fmt.Errorf("%v has %v+%v params, but instantiated with %v+%v args", sym, nimplicits, nexplicits, len(implicits), len(explicits)) } dict.targs = append(implicits[:nimplicits:nimplicits], explicits...) dict.implicits = nimplicits // Within the compiler, we can just skip over the type parameters. for range dict.targs[dict.implicits:] { // Skip past bounds without actually evaluating them. r.typInfo() } dict.derived = make([]derivedInfo, r.Len()) dict.derivedTypes = make([]*types.Type, len(dict.derived)) for i := range dict.derived { dict.derived[i] = derivedInfo{r.Reloc(pkgbits.RelocType), r.Bool()} } // Runtime dictionary information; private to the compiler. // If any type argument is already shaped, then we're constructing a // shaped object, even if not explicitly requested (i.e., calling // objIdx with shaped==true). This can happen with instantiating // types that are referenced within a function body. for _, targ := range dict.targs { if targ.HasShape() { dict.shaped = true break } } // And if we're constructing a shaped object, then shapify all type // arguments. for i, targ := range dict.targs { basic := r.Bool() if dict.shaped { dict.targs[i] = shapify(targ, basic) } } dict.baseSym = dict.mangle(sym) dict.typeParamMethodExprs = make([]readerMethodExprInfo, r.Len()) for i := range dict.typeParamMethodExprs { typeParamIdx := r.Len() method := r.selector() dict.typeParamMethodExprs[i] = readerMethodExprInfo{typeParamIdx, method} } dict.subdicts = make([]objInfo, r.Len()) for i := range dict.subdicts { dict.subdicts[i] = r.objInfo() } dict.rtypes = make([]typeInfo, r.Len()) for i := range dict.rtypes { dict.rtypes[i] = r.typInfo() } dict.itabs = make([]itabInfo, r.Len()) for i := range dict.itabs { dict.itabs[i] = itabInfo{typ: r.typInfo(), iface: r.typInfo()} } return &dict, nil } func (r *reader) typeParamNames() { r.Sync(pkgbits.SyncTypeParamNames) for range r.dict.targs[r.dict.implicits:] { r.pos() r.localIdent() } } func (r *reader) method(rext *reader) *types.Field { r.Sync(pkgbits.SyncMethod) npos := r.pos() sym := r.selector() r.typeParamNames() recv := r.param() typ := r.signature(recv) fpos := r.pos() fn := ir.NewFunc(fpos, npos, ir.MethodSym(recv.Type, sym), typ) name := fn.Nname if r.hasTypeParams() { name.Func.SetDupok(true) if r.dict.shaped { typ = shapeSig(name.Func, r.dict) setType(name, typ) } } rext.funcExt(name, sym) meth := types.NewField(name.Func.Pos(), sym, typ) meth.Nname = name meth.SetNointerface(name.Func.Pragma&ir.Nointerface != 0) return meth } func (r *reader) qualifiedIdent() (pkg *types.Pkg, sym *types.Sym) { r.Sync(pkgbits.SyncSym) pkg = r.pkg() if name := r.String(); name != "" { sym = pkg.Lookup(name) } return } func (r *reader) localIdent() *types.Sym { r.Sync(pkgbits.SyncLocalIdent) pkg := r.pkg() if name := r.String(); name != "" { return pkg.Lookup(name) } return nil } func (r *reader) selector() *types.Sym { r.Sync(pkgbits.SyncSelector) pkg := r.pkg() name := r.String() if types.IsExported(name) { pkg = types.LocalPkg } return pkg.Lookup(name) } func (r *reader) hasTypeParams() bool { return r.dict.hasTypeParams() } func (dict *readerDict) hasTypeParams() bool { return dict != nil && len(dict.targs) != 0 } // @@@ Compiler extensions func (r *reader) funcExt(name *ir.Name, method *types.Sym) { r.Sync(pkgbits.SyncFuncExt) fn := name.Func // XXX: Workaround because linker doesn't know how to copy Pos. if !fn.Pos().IsKnown() { fn.SetPos(name.Pos()) } // Normally, we only compile local functions, which saves redundant compilation work. // n.Defn is not nil for local functions, and is nil for imported function. But for // generic functions, we might have an instantiation that no other package has seen before. // So we need to be conservative and compile it again. // // That's why name.Defn is set here, so ir.VisitFuncsBottomUp can analyze function. // TODO(mdempsky,cuonglm): find a cleaner way to handle this. if name.Sym().Pkg == types.LocalPkg || r.hasTypeParams() { name.Defn = fn } fn.Pragma = r.pragmaFlag() r.linkname(name) if buildcfg.GOARCH == "wasm" { xmod := r.String() xname := r.String() if xmod != "" && xname != "" { fn.WasmImport = &ir.WasmImport{ Module: xmod, Name: xname, } } } if r.Bool() { assert(name.Defn == nil) fn.ABI = obj.ABI(r.Uint64()) // Escape analysis. for _, f := range name.Type().RecvParams() { f.Note = r.String() } if r.Bool() { fn.Inl = &ir.Inline{ Cost: int32(r.Len()), CanDelayResults: r.Bool(), } if buildcfg.Experiment.NewInliner { fn.Inl.Properties = r.String() } } } else { r.addBody(name.Func, method) } r.Sync(pkgbits.SyncEOF) } func (r *reader) typeExt(name *ir.Name) { r.Sync(pkgbits.SyncTypeExt) typ := name.Type() if r.hasTypeParams() { // Set "RParams" (really type arguments here, not parameters) so // this type is treated as "fully instantiated". This ensures the // type descriptor is written out as DUPOK and method wrappers are // generated even for imported types. var targs []*types.Type targs = append(targs, r.dict.targs...) typ.SetRParams(targs) } name.SetPragma(r.pragmaFlag()) typecheck.SetBaseTypeIndex(typ, r.Int64(), r.Int64()) } func (r *reader) varExt(name *ir.Name) { r.Sync(pkgbits.SyncVarExt) r.linkname(name) } func (r *reader) linkname(name *ir.Name) { assert(name.Op() == ir.ONAME) r.Sync(pkgbits.SyncLinkname) if idx := r.Int64(); idx >= 0 { lsym := name.Linksym() lsym.SymIdx = int32(idx) lsym.Set(obj.AttrIndexed, true) } else { linkname := r.String() sym := name.Sym() sym.Linkname = linkname if sym.Pkg == types.LocalPkg && linkname != "" { // Mark linkname in the current package. We don't mark the // ones that are imported and propagated (e.g. through // inlining or instantiation, which are marked in their // corresponding packages). So we can tell in which package // the linkname is used (pulled), and the linker can // make a decision for allowing or disallowing it. sym.Linksym().Set(obj.AttrLinkname, true) } } } func (r *reader) pragmaFlag() ir.PragmaFlag { r.Sync(pkgbits.SyncPragma) return ir.PragmaFlag(r.Int()) } // @@@ Function bodies // bodyReader tracks where the serialized IR for a local or imported, // generic function's body can be found. var bodyReader = map[*ir.Func]pkgReaderIndex{} // importBodyReader tracks where the serialized IR for an imported, // static (i.e., non-generic) function body can be read. var importBodyReader = map[*types.Sym]pkgReaderIndex{} // bodyReaderFor returns the pkgReaderIndex for reading fn's // serialized IR, and whether one was found. func bodyReaderFor(fn *ir.Func) (pri pkgReaderIndex, ok bool) { if fn.Nname.Defn != nil { pri, ok = bodyReader[fn] base.AssertfAt(ok, base.Pos, "must have bodyReader for %v", fn) // must always be available } else { pri, ok = importBodyReader[fn.Sym()] } return } // todoDicts holds the list of dictionaries that still need their // runtime dictionary objects constructed. var todoDicts []func() // todoBodies holds the list of function bodies that still need to be // constructed. var todoBodies []*ir.Func // addBody reads a function body reference from the element bitstream, // and associates it with fn. func (r *reader) addBody(fn *ir.Func, method *types.Sym) { // addBody should only be called for local functions or imported // generic functions; see comment in funcExt. assert(fn.Nname.Defn != nil) idx := r.Reloc(pkgbits.RelocBody) pri := pkgReaderIndex{r.p, idx, r.dict, method, nil} bodyReader[fn] = pri if r.curfn == nil { todoBodies = append(todoBodies, fn) return } pri.funcBody(fn) } func (pri pkgReaderIndex) funcBody(fn *ir.Func) { r := pri.asReader(pkgbits.RelocBody, pkgbits.SyncFuncBody) r.funcBody(fn) } // funcBody reads a function body definition from the element // bitstream, and populates fn with it. func (r *reader) funcBody(fn *ir.Func) { r.curfn = fn r.closureVars = fn.ClosureVars if len(r.closureVars) != 0 && r.hasTypeParams() { r.dictParam = r.closureVars[len(r.closureVars)-1] // dictParam is last; see reader.funcLit } ir.WithFunc(fn, func() { r.declareParams() if r.syntheticBody(fn.Pos()) { return } if !r.Bool() { return } body := r.stmts() if body == nil { body = []ir.Node{typecheck.Stmt(ir.NewBlockStmt(src.NoXPos, nil))} } fn.Body = body fn.Endlineno = r.pos() }) r.marker.WriteTo(fn) } // syntheticBody adds a synthetic body to r.curfn if appropriate, and // reports whether it did. func (r *reader) syntheticBody(pos src.XPos) bool { if r.synthetic != nil { r.synthetic(pos, r) return true } // If this function has type parameters and isn't shaped, then we // just tail call its corresponding shaped variant. if r.hasTypeParams() && !r.dict.shaped { r.callShaped(pos) return true } return false } // callShaped emits a tail call to r.shapedFn, passing along the // arguments to the current function. func (r *reader) callShaped(pos src.XPos) { shapedObj := r.dict.shapedObj assert(shapedObj != nil) var shapedFn ir.Node if r.methodSym == nil { // Instantiating a generic function; shapedObj is the shaped // function itself. assert(shapedObj.Op() == ir.ONAME && shapedObj.Class == ir.PFUNC) shapedFn = shapedObj } else { // Instantiating a generic type's method; shapedObj is the shaped // type, so we need to select it's corresponding method. shapedFn = shapedMethodExpr(pos, shapedObj, r.methodSym) } params := r.syntheticArgs() // Construct the arguments list: receiver (if any), then runtime // dictionary, and finally normal parameters. // // Note: For simplicity, shaped methods are added as normal methods // on their shaped types. So existing code (e.g., packages ir and // typecheck) expects the shaped type to appear as the receiver // parameter (or first parameter, as a method expression). Hence // putting the dictionary parameter after that is the least invasive // solution at the moment. var args ir.Nodes if r.methodSym != nil { args.Append(params[0]) params = params[1:] } args.Append(typecheck.Expr(ir.NewAddrExpr(pos, r.p.dictNameOf(r.dict)))) args.Append(params...) r.syntheticTailCall(pos, shapedFn, args) } // syntheticArgs returns the recvs and params arguments passed to the // current function. func (r *reader) syntheticArgs() ir.Nodes { sig := r.curfn.Nname.Type() return ir.ToNodes(r.curfn.Dcl[:sig.NumRecvs()+sig.NumParams()]) } // syntheticTailCall emits a tail call to fn, passing the given // arguments list. func (r *reader) syntheticTailCall(pos src.XPos, fn ir.Node, args ir.Nodes) { // Mark the function as a wrapper so it doesn't show up in stack // traces. r.curfn.SetWrapper(true) call := typecheck.Call(pos, fn, args, fn.Type().IsVariadic()).(*ir.CallExpr) var stmt ir.Node if fn.Type().NumResults() != 0 { stmt = typecheck.Stmt(ir.NewReturnStmt(pos, []ir.Node{call})) } else { stmt = call } r.curfn.Body.Append(stmt) } // dictNameOf returns the runtime dictionary corresponding to dict. func (pr *pkgReader) dictNameOf(dict *readerDict) *ir.Name { pos := base.AutogeneratedPos // Check that we only instantiate runtime dictionaries with real types. base.AssertfAt(!dict.shaped, pos, "runtime dictionary of shaped object %v", dict.baseSym) sym := dict.baseSym.Pkg.Lookup(objabi.GlobalDictPrefix + "." + dict.baseSym.Name) if sym.Def != nil { return sym.Def.(*ir.Name) } name := ir.NewNameAt(pos, sym, dict.varType()) name.Class = ir.PEXTERN sym.Def = name // break cycles with mutual subdictionaries lsym := name.Linksym() ot := 0 assertOffset := func(section string, offset int) { base.AssertfAt(ot == offset*types.PtrSize, pos, "writing section %v at offset %v, but it should be at %v*%v", section, ot, offset, types.PtrSize) } assertOffset("type param method exprs", dict.typeParamMethodExprsOffset()) for _, info := range dict.typeParamMethodExprs { typeParam := dict.targs[info.typeParamIdx] method := typecheck.NewMethodExpr(pos, typeParam, info.method) rsym := method.FuncName().Linksym() assert(rsym.ABI() == obj.ABIInternal) // must be ABIInternal; see ir.OCFUNC in ssagen/ssa.go ot = objw.SymPtr(lsym, ot, rsym, 0) } assertOffset("subdictionaries", dict.subdictsOffset()) for _, info := range dict.subdicts { explicits := pr.typListIdx(info.explicits, dict) // Careful: Due to subdictionary cycles, name may not be fully // initialized yet. name := pr.objDictName(info.idx, dict.targs, explicits) ot = objw.SymPtr(lsym, ot, name.Linksym(), 0) } assertOffset("rtypes", dict.rtypesOffset()) for _, info := range dict.rtypes { typ := pr.typIdx(info, dict, true) ot = objw.SymPtr(lsym, ot, reflectdata.TypeLinksym(typ), 0) // TODO(mdempsky): Double check this. reflectdata.MarkTypeUsedInInterface(typ, lsym) } // For each (typ, iface) pair, we write the *runtime.itab pointer // for the pair. For pairs that don't actually require an itab // (i.e., typ is an interface, or iface is an empty interface), we // write a nil pointer instead. This is wasteful, but rare in // practice (e.g., instantiating a type parameter with an interface // type). assertOffset("itabs", dict.itabsOffset()) for _, info := range dict.itabs { typ := pr.typIdx(info.typ, dict, true) iface := pr.typIdx(info.iface, dict, true) if !typ.IsInterface() && iface.IsInterface() && !iface.IsEmptyInterface() { ot = objw.SymPtr(lsym, ot, reflectdata.ITabLsym(typ, iface), 0) } else { ot += types.PtrSize } // TODO(mdempsky): Double check this. reflectdata.MarkTypeUsedInInterface(typ, lsym) reflectdata.MarkTypeUsedInInterface(iface, lsym) } objw.Global(lsym, int32(ot), obj.DUPOK|obj.RODATA) return name } // typeParamMethodExprsOffset returns the offset of the runtime // dictionary's type parameter method expressions section, in words. func (dict *readerDict) typeParamMethodExprsOffset() int { return 0 } // subdictsOffset returns the offset of the runtime dictionary's // subdictionary section, in words. func (dict *readerDict) subdictsOffset() int { return dict.typeParamMethodExprsOffset() + len(dict.typeParamMethodExprs) } // rtypesOffset returns the offset of the runtime dictionary's rtypes // section, in words. func (dict *readerDict) rtypesOffset() int { return dict.subdictsOffset() + len(dict.subdicts) } // itabsOffset returns the offset of the runtime dictionary's itabs // section, in words. func (dict *readerDict) itabsOffset() int { return dict.rtypesOffset() + len(dict.rtypes) } // numWords returns the total number of words that comprise dict's // runtime dictionary variable. func (dict *readerDict) numWords() int64 { return int64(dict.itabsOffset() + len(dict.itabs)) } // varType returns the type of dict's runtime dictionary variable. func (dict *readerDict) varType() *types.Type { return types.NewArray(types.Types[types.TUINTPTR], dict.numWords()) } func (r *reader) declareParams() { r.curfn.DeclareParams(!r.funarghack) for _, name := range r.curfn.Dcl { if name.Sym().Name == dictParamName { r.dictParam = name continue } r.addLocal(name) } } func (r *reader) addLocal(name *ir.Name) { if r.synthetic == nil { r.Sync(pkgbits.SyncAddLocal) if r.p.SyncMarkers() { want := r.Int() if have := len(r.locals); have != want { base.FatalfAt(name.Pos(), "locals table has desynced") } } r.varDictIndex(name) } r.locals = append(r.locals, name) } func (r *reader) useLocal() *ir.Name { r.Sync(pkgbits.SyncUseObjLocal) if r.Bool() { return r.locals[r.Len()] } return r.closureVars[r.Len()] } func (r *reader) openScope() { r.Sync(pkgbits.SyncOpenScope) pos := r.pos() if base.Flag.Dwarf { r.scopeVars = append(r.scopeVars, len(r.curfn.Dcl)) r.marker.Push(pos) } } func (r *reader) closeScope() { r.Sync(pkgbits.SyncCloseScope) r.lastCloseScopePos = r.pos() r.closeAnotherScope() } // closeAnotherScope is like closeScope, but it reuses the same mark // position as the last closeScope call. This is useful for "for" and // "if" statements, as their implicit blocks always end at the same // position as an explicit block. func (r *reader) closeAnotherScope() { r.Sync(pkgbits.SyncCloseAnotherScope) if base.Flag.Dwarf { scopeVars := r.scopeVars[len(r.scopeVars)-1] r.scopeVars = r.scopeVars[:len(r.scopeVars)-1] // Quirkish: noder decides which scopes to keep before // typechecking, whereas incremental typechecking during IR // construction can result in new autotemps being allocated. To // produce identical output, we ignore autotemps here for the // purpose of deciding whether to retract the scope. // // This is important for net/http/fcgi, because it contains: // // var body io.ReadCloser // if len(content) > 0 { // body, req.pw = io.Pipe() // } else { … } // // Notably, io.Pipe is inlinable, and inlining it introduces a ~R0 // variable at the call site. // // Noder does not preserve the scope where the io.Pipe() call // resides, because it doesn't contain any declared variables in // source. So the ~R0 variable ends up being assigned to the // enclosing scope instead. // // However, typechecking this assignment also introduces // autotemps, because io.Pipe's results need conversion before // they can be assigned to their respective destination variables. // // TODO(mdempsky): We should probably just keep all scopes, and // let dwarfgen take care of pruning them instead. retract := true for _, n := range r.curfn.Dcl[scopeVars:] { if !n.AutoTemp() { retract = false break } } if retract { // no variables were declared in this scope, so we can retract it. r.marker.Unpush() } else { r.marker.Pop(r.lastCloseScopePos) } } } // @@@ Statements func (r *reader) stmt() ir.Node { return block(r.stmts()) } func block(stmts []ir.Node) ir.Node { switch len(stmts) { case 0: return nil case 1: return stmts[0] default: return ir.NewBlockStmt(stmts[0].Pos(), stmts) } } func (r *reader) stmts() ir.Nodes { assert(ir.CurFunc == r.curfn) var res ir.Nodes r.Sync(pkgbits.SyncStmts) for { tag := codeStmt(r.Code(pkgbits.SyncStmt1)) if tag == stmtEnd { r.Sync(pkgbits.SyncStmtsEnd) return res } if n := r.stmt1(tag, &res); n != nil { res.Append(typecheck.Stmt(n)) } } } func (r *reader) stmt1(tag codeStmt, out *ir.Nodes) ir.Node { var label *types.Sym if n := len(*out); n > 0 { if ls, ok := (*out)[n-1].(*ir.LabelStmt); ok { label = ls.Label } } switch tag { default: panic("unexpected statement") case stmtAssign: pos := r.pos() names, lhs := r.assignList() rhs := r.multiExpr() if len(rhs) == 0 { for _, name := range names { as := ir.NewAssignStmt(pos, name, nil) as.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, name)) out.Append(typecheck.Stmt(as)) } return nil } if len(lhs) == 1 && len(rhs) == 1 { n := ir.NewAssignStmt(pos, lhs[0], rhs[0]) n.Def = r.initDefn(n, names) return n } n := ir.NewAssignListStmt(pos, ir.OAS2, lhs, rhs) n.Def = r.initDefn(n, names) return n case stmtAssignOp: op := r.op() lhs := r.expr() pos := r.pos() rhs := r.expr() return ir.NewAssignOpStmt(pos, op, lhs, rhs) case stmtIncDec: op := r.op() lhs := r.expr() pos := r.pos() n := ir.NewAssignOpStmt(pos, op, lhs, ir.NewOne(pos, lhs.Type())) n.IncDec = true return n case stmtBlock: out.Append(r.blockStmt()...) return nil case stmtBranch: pos := r.pos() op := r.op() sym := r.optLabel() return ir.NewBranchStmt(pos, op, sym) case stmtCall: pos := r.pos() op := r.op() call := r.expr() stmt := ir.NewGoDeferStmt(pos, op, call) if op == ir.ODEFER { x := r.optExpr() if x != nil { stmt.DeferAt = x.(ir.Expr) } } return stmt case stmtExpr: return r.expr() case stmtFor: return r.forStmt(label) case stmtIf: return r.ifStmt() case stmtLabel: pos := r.pos() sym := r.label() return ir.NewLabelStmt(pos, sym) case stmtReturn: pos := r.pos() results := r.multiExpr() return ir.NewReturnStmt(pos, results) case stmtSelect: return r.selectStmt(label) case stmtSend: pos := r.pos() ch := r.expr() value := r.expr() return ir.NewSendStmt(pos, ch, value) case stmtSwitch: return r.switchStmt(label) } } func (r *reader) assignList() ([]*ir.Name, []ir.Node) { lhs := make([]ir.Node, r.Len()) var names []*ir.Name for i := range lhs { expr, def := r.assign() lhs[i] = expr if def { names = append(names, expr.(*ir.Name)) } } return names, lhs } // assign returns an assignee expression. It also reports whether the // returned expression is a newly declared variable. func (r *reader) assign() (ir.Node, bool) { switch tag := codeAssign(r.Code(pkgbits.SyncAssign)); tag { default: panic("unhandled assignee expression") case assignBlank: return typecheck.AssignExpr(ir.BlankNode), false case assignDef: pos := r.pos() setBasePos(pos) // test/fixedbugs/issue49767.go depends on base.Pos being set for the r.typ() call here, ugh name := r.curfn.NewLocal(pos, r.localIdent(), r.typ()) r.addLocal(name) return name, true case assignExpr: return r.expr(), false } } func (r *reader) blockStmt() []ir.Node { r.Sync(pkgbits.SyncBlockStmt) r.openScope() stmts := r.stmts() r.closeScope() return stmts } func (r *reader) forStmt(label *types.Sym) ir.Node { r.Sync(pkgbits.SyncForStmt) r.openScope() if r.Bool() { pos := r.pos() rang := ir.NewRangeStmt(pos, nil, nil, nil, nil, false) rang.Label = label names, lhs := r.assignList() if len(lhs) >= 1 { rang.Key = lhs[0] if len(lhs) >= 2 { rang.Value = lhs[1] } } rang.Def = r.initDefn(rang, names) rang.X = r.expr() if rang.X.Type().IsMap() { rang.RType = r.rtype(pos) } if rang.Key != nil && !ir.IsBlank(rang.Key) { rang.KeyTypeWord, rang.KeySrcRType = r.convRTTI(pos) } if rang.Value != nil && !ir.IsBlank(rang.Value) { rang.ValueTypeWord, rang.ValueSrcRType = r.convRTTI(pos) } rang.Body = r.blockStmt() rang.DistinctVars = r.Bool() r.closeAnotherScope() return rang } pos := r.pos() init := r.stmt() cond := r.optExpr() post := r.stmt() body := r.blockStmt() perLoopVars := r.Bool() r.closeAnotherScope() if ir.IsConst(cond, constant.Bool) && !ir.BoolVal(cond) { return init // simplify "for init; false; post { ... }" into "init" } stmt := ir.NewForStmt(pos, init, cond, post, body, perLoopVars) stmt.Label = label return stmt } func (r *reader) ifStmt() ir.Node { r.Sync(pkgbits.SyncIfStmt) r.openScope() pos := r.pos() init := r.stmts() cond := r.expr() staticCond := r.Int() var then, els []ir.Node if staticCond >= 0 { then = r.blockStmt() } else { r.lastCloseScopePos = r.pos() } if staticCond <= 0 { els = r.stmts() } r.closeAnotherScope() if staticCond != 0 { // We may have removed a dead return statement, which can trip up // later passes (#62211). To avoid confusion, we instead flatten // the if statement into a block. if cond.Op() != ir.OLITERAL { init.Append(typecheck.Stmt(ir.NewAssignStmt(pos, ir.BlankNode, cond))) // for side effects } init.Append(then...) init.Append(els...) return block(init) } n := ir.NewIfStmt(pos, cond, then, els) n.SetInit(init) return n } func (r *reader) selectStmt(label *types.Sym) ir.Node { r.Sync(pkgbits.SyncSelectStmt) pos := r.pos() clauses := make([]*ir.CommClause, r.Len()) for i := range clauses { if i > 0 { r.closeScope() } r.openScope() pos := r.pos() comm := r.stmt() body := r.stmts() // "case i = <-c: ..." may require an implicit conversion (e.g., // see fixedbugs/bug312.go). Currently, typecheck throws away the // implicit conversion and relies on it being reinserted later, // but that would lose any explicit RTTI operands too. To preserve // RTTI, we rewrite this as "case tmp := <-c: i = tmp; ...". if as, ok := comm.(*ir.AssignStmt); ok && as.Op() == ir.OAS && !as.Def { if conv, ok := as.Y.(*ir.ConvExpr); ok && conv.Op() == ir.OCONVIFACE { base.AssertfAt(conv.Implicit(), conv.Pos(), "expected implicit conversion: %v", conv) recv := conv.X base.AssertfAt(recv.Op() == ir.ORECV, recv.Pos(), "expected receive expression: %v", recv) tmp := r.temp(pos, recv.Type()) // Replace comm with `tmp := <-c`. tmpAs := ir.NewAssignStmt(pos, tmp, recv) tmpAs.Def = true tmpAs.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, tmp)) comm = tmpAs // Change original assignment to `i = tmp`, and prepend to body. conv.X = tmp body = append([]ir.Node{as}, body...) } } // multiExpr will have desugared a comma-ok receive expression // into a separate statement. However, the rest of the compiler // expects comm to be the OAS2RECV statement itself, so we need to // shuffle things around to fit that pattern. if as2, ok := comm.(*ir.AssignListStmt); ok && as2.Op() == ir.OAS2 { init := ir.TakeInit(as2.Rhs[0]) base.AssertfAt(len(init) == 1 && init[0].Op() == ir.OAS2RECV, as2.Pos(), "unexpected assignment: %+v", as2) comm = init[0] body = append([]ir.Node{as2}, body...) } clauses[i] = ir.NewCommStmt(pos, comm, body) } if len(clauses) > 0 { r.closeScope() } n := ir.NewSelectStmt(pos, clauses) n.Label = label return n } func (r *reader) switchStmt(label *types.Sym) ir.Node { r.Sync(pkgbits.SyncSwitchStmt) r.openScope() pos := r.pos() init := r.stmt() var tag ir.Node var ident *ir.Ident var iface *types.Type if r.Bool() { pos := r.pos() if r.Bool() { ident = ir.NewIdent(r.pos(), r.localIdent()) } x := r.expr() iface = x.Type() tag = ir.NewTypeSwitchGuard(pos, ident, x) } else { tag = r.optExpr() } clauses := make([]*ir.CaseClause, r.Len()) for i := range clauses { if i > 0 { r.closeScope() } r.openScope() pos := r.pos() var cases, rtypes []ir.Node if iface != nil { cases = make([]ir.Node, r.Len()) if len(cases) == 0 { cases = nil // TODO(mdempsky): Unclear if this matters. } for i := range cases { if r.Bool() { // case nil cases[i] = typecheck.Expr(types.BuiltinPkg.Lookup("nil").Def.(*ir.NilExpr)) } else { cases[i] = r.exprType() } } } else { cases = r.exprList() // For `switch { case any(true): }` (e.g., issue 3980 in // test/switch.go), the backend still creates a mixed bool/any // comparison, and we need to explicitly supply the RTTI for the // comparison. // // TODO(mdempsky): Change writer.go to desugar "switch {" into // "switch true {", which we already handle correctly. if tag == nil { for i, cas := range cases { if cas.Type().IsEmptyInterface() { for len(rtypes) < i { rtypes = append(rtypes, nil) } rtypes = append(rtypes, reflectdata.TypePtrAt(cas.Pos(), types.Types[types.TBOOL])) } } } } clause := ir.NewCaseStmt(pos, cases, nil) clause.RTypes = rtypes if ident != nil { name := r.curfn.NewLocal(r.pos(), ident.Sym(), r.typ()) r.addLocal(name) clause.Var = name name.Defn = tag } clause.Body = r.stmts() clauses[i] = clause } if len(clauses) > 0 { r.closeScope() } r.closeScope() n := ir.NewSwitchStmt(pos, tag, clauses) n.Label = label if init != nil { n.SetInit([]ir.Node{init}) } return n } func (r *reader) label() *types.Sym { r.Sync(pkgbits.SyncLabel) name := r.String() if r.inlCall != nil { name = fmt.Sprintf("~%s·%d", name, inlgen) } return typecheck.Lookup(name) } func (r *reader) optLabel() *types.Sym { r.Sync(pkgbits.SyncOptLabel) if r.Bool() { return r.label() } return nil } // initDefn marks the given names as declared by defn and populates // its Init field with ODCL nodes. It then reports whether any names // were so declared, which can be used to initialize defn.Def. func (r *reader) initDefn(defn ir.InitNode, names []*ir.Name) bool { if len(names) == 0 { return false } init := make([]ir.Node, len(names)) for i, name := range names { name.Defn = defn init[i] = ir.NewDecl(name.Pos(), ir.ODCL, name) } defn.SetInit(init) return true } // @@@ Expressions // expr reads and returns a typechecked expression. func (r *reader) expr() (res ir.Node) { defer func() { if res != nil && res.Typecheck() == 0 { base.FatalfAt(res.Pos(), "%v missed typecheck", res) } }() switch tag := codeExpr(r.Code(pkgbits.SyncExpr)); tag { default: panic("unhandled expression") case exprLocal: return typecheck.Expr(r.useLocal()) case exprGlobal: // Callee instead of Expr allows builtins // TODO(mdempsky): Handle builtins directly in exprCall, like method calls? return typecheck.Callee(r.obj()) case exprFuncInst: origPos, pos := r.origPos() wrapperFn, baseFn, dictPtr := r.funcInst(pos) if wrapperFn != nil { return wrapperFn } return r.curry(origPos, false, baseFn, dictPtr, nil) case exprConst: pos := r.pos() typ := r.typ() val := FixValue(typ, r.Value()) return ir.NewBasicLit(pos, typ, val) case exprZero: pos := r.pos() typ := r.typ() return ir.NewZero(pos, typ) case exprCompLit: return r.compLit() case exprFuncLit: return r.funcLit() case exprFieldVal: x := r.expr() pos := r.pos() sym := r.selector() return typecheck.XDotField(pos, x, sym) case exprMethodVal: recv := r.expr() origPos, pos := r.origPos() wrapperFn, baseFn, dictPtr := r.methodExpr() // For simple wrapperFn values, the existing machinery for creating // and deduplicating wrapperFn value wrappers still works fine. if wrapperFn, ok := wrapperFn.(*ir.SelectorExpr); ok && wrapperFn.Op() == ir.OMETHEXPR { // The receiver expression we constructed may have a shape type. // For example, in fixedbugs/issue54343.go, `New[int]()` is // constructed as `New[go.shape.int](&.dict.New[int])`, which // has type `*T[go.shape.int]`, not `*T[int]`. // // However, the method we want to select here is `(*T[int]).M`, // not `(*T[go.shape.int]).M`, so we need to manually convert // the type back so that the OXDOT resolves correctly. // // TODO(mdempsky): Logically it might make more sense for // exprCall to take responsibility for setting a non-shaped // result type, but this is the only place where we care // currently. And only because existing ir.OMETHVALUE backend // code relies on n.X.Type() instead of n.Selection.Recv().Type // (because the latter is types.FakeRecvType() in the case of // interface method values). // if recv.Type().HasShape() { typ := wrapperFn.Type().Param(0).Type if !types.Identical(typ, recv.Type()) { base.FatalfAt(wrapperFn.Pos(), "receiver %L does not match %L", recv, wrapperFn) } recv = typecheck.Expr(ir.NewConvExpr(recv.Pos(), ir.OCONVNOP, typ, recv)) } n := typecheck.XDotMethod(pos, recv, wrapperFn.Sel, false) // As a consistency check here, we make sure "n" selected the // same method (represented by a types.Field) that wrapperFn // selected. However, for anonymous receiver types, there can be // multiple such types.Field instances (#58563). So we may need // to fallback to making sure Sym and Type (including the // receiver parameter's type) match. if n.Selection != wrapperFn.Selection { assert(n.Selection.Sym == wrapperFn.Selection.Sym) assert(types.Identical(n.Selection.Type, wrapperFn.Selection.Type)) assert(types.Identical(n.Selection.Type.Recv().Type, wrapperFn.Selection.Type.Recv().Type)) } wrapper := methodValueWrapper{ rcvr: n.X.Type(), method: n.Selection, } if r.importedDef() { haveMethodValueWrappers = append(haveMethodValueWrappers, wrapper) } else { needMethodValueWrappers = append(needMethodValueWrappers, wrapper) } return n } // For more complicated method expressions, we construct a // function literal wrapper. return r.curry(origPos, true, baseFn, recv, dictPtr) case exprMethodExpr: recv := r.typ() implicits := make([]int, r.Len()) for i := range implicits { implicits[i] = r.Len() } var deref, addr bool if r.Bool() { deref = true } else if r.Bool() { addr = true } origPos, pos := r.origPos() wrapperFn, baseFn, dictPtr := r.methodExpr() // If we already have a wrapper and don't need to do anything with // it, we can just return the wrapper directly. // // N.B., we use implicits/deref/addr here as the source of truth // rather than types.Identical, because the latter can be confused // by tricky promoted methods (e.g., typeparam/mdempsky/21.go). if wrapperFn != nil && len(implicits) == 0 && !deref && !addr { if !types.Identical(recv, wrapperFn.Type().Param(0).Type) { base.FatalfAt(pos, "want receiver type %v, but have method %L", recv, wrapperFn) } return wrapperFn } // Otherwise, if the wrapper function is a static method // expression (OMETHEXPR) and the receiver type is unshaped, then // we can rely on a statically generated wrapper being available. if method, ok := wrapperFn.(*ir.SelectorExpr); ok && method.Op() == ir.OMETHEXPR && !recv.HasShape() { return typecheck.NewMethodExpr(pos, recv, method.Sel) } return r.methodExprWrap(origPos, recv, implicits, deref, addr, baseFn, dictPtr) case exprIndex: x := r.expr() pos := r.pos() index := r.expr() n := typecheck.Expr(ir.NewIndexExpr(pos, x, index)) switch n.Op() { case ir.OINDEXMAP: n := n.(*ir.IndexExpr) n.RType = r.rtype(pos) } return n case exprSlice: x := r.expr() pos := r.pos() var index [3]ir.Node for i := range index { index[i] = r.optExpr() } op := ir.OSLICE if index[2] != nil { op = ir.OSLICE3 } return typecheck.Expr(ir.NewSliceExpr(pos, op, x, index[0], index[1], index[2])) case exprAssert: x := r.expr() pos := r.pos() typ := r.exprType() srcRType := r.rtype(pos) // TODO(mdempsky): Always emit ODYNAMICDOTTYPE for uniformity? if typ, ok := typ.(*ir.DynamicType); ok && typ.Op() == ir.ODYNAMICTYPE { assert := ir.NewDynamicTypeAssertExpr(pos, ir.ODYNAMICDOTTYPE, x, typ.RType) assert.SrcRType = srcRType assert.ITab = typ.ITab return typed(typ.Type(), assert) } return typecheck.Expr(ir.NewTypeAssertExpr(pos, x, typ.Type())) case exprUnaryOp: op := r.op() pos := r.pos() x := r.expr() switch op { case ir.OADDR: return typecheck.Expr(typecheck.NodAddrAt(pos, x)) case ir.ODEREF: return typecheck.Expr(ir.NewStarExpr(pos, x)) } return typecheck.Expr(ir.NewUnaryExpr(pos, op, x)) case exprBinaryOp: op := r.op() x := r.expr() pos := r.pos() y := r.expr() switch op { case ir.OANDAND, ir.OOROR: return typecheck.Expr(ir.NewLogicalExpr(pos, op, x, y)) case ir.OLSH, ir.ORSH: // Untyped rhs of non-constant shift, e.g. x << 1.0. // If we have a constant value, it must be an int >= 0. if ir.IsConstNode(y) { val := constant.ToInt(y.Val()) assert(val.Kind() == constant.Int && constant.Sign(val) >= 0) } } return typecheck.Expr(ir.NewBinaryExpr(pos, op, x, y)) case exprRecv: x := r.expr() pos := r.pos() for i, n := 0, r.Len(); i < n; i++ { x = Implicit(typecheck.DotField(pos, x, r.Len())) } if r.Bool() { // needs deref x = Implicit(Deref(pos, x.Type().Elem(), x)) } else if r.Bool() { // needs addr x = Implicit(Addr(pos, x)) } return x case exprCall: var fun ir.Node var args ir.Nodes if r.Bool() { // method call recv := r.expr() _, method, dictPtr := r.methodExpr() if recv.Type().IsInterface() && method.Op() == ir.OMETHEXPR { method := method.(*ir.SelectorExpr) // The compiler backend (e.g., devirtualization) handle // OCALLINTER/ODOTINTER better than OCALLFUNC/OMETHEXPR for // interface calls, so we prefer to continue constructing // calls that way where possible. // // There are also corner cases where semantically it's perhaps // significant; e.g., fixedbugs/issue15975.go, #38634, #52025. fun = typecheck.XDotMethod(method.Pos(), recv, method.Sel, true) } else { if recv.Type().IsInterface() { // N.B., this happens currently for typeparam/issue51521.go // and typeparam/typeswitch3.go. if base.Flag.LowerM != 0 { base.WarnfAt(method.Pos(), "imprecise interface call") } } fun = method args.Append(recv) } if dictPtr != nil { args.Append(dictPtr) } } else if r.Bool() { // call to instanced function pos := r.pos() _, shapedFn, dictPtr := r.funcInst(pos) fun = shapedFn args.Append(dictPtr) } else { fun = r.expr() } pos := r.pos() args.Append(r.multiExpr()...) dots := r.Bool() n := typecheck.Call(pos, fun, args, dots) switch n.Op() { case ir.OAPPEND: n := n.(*ir.CallExpr) n.RType = r.rtype(pos) // For append(a, b...), we don't need the implicit conversion. The typechecker already // ensured that a and b are both slices with the same base type, or []byte and string. if n.IsDDD { if conv, ok := n.Args[1].(*ir.ConvExpr); ok && conv.Op() == ir.OCONVNOP && conv.Implicit() { n.Args[1] = conv.X } } case ir.OCOPY: n := n.(*ir.BinaryExpr) n.RType = r.rtype(pos) case ir.ODELETE: n := n.(*ir.CallExpr) n.RType = r.rtype(pos) case ir.OUNSAFESLICE: n := n.(*ir.BinaryExpr) n.RType = r.rtype(pos) } return n case exprMake: pos := r.pos() typ := r.exprType() extra := r.exprs() n := typecheck.Expr(ir.NewCallExpr(pos, ir.OMAKE, nil, append([]ir.Node{typ}, extra...))).(*ir.MakeExpr) n.RType = r.rtype(pos) return n case exprNew: pos := r.pos() typ := r.exprType() return typecheck.Expr(ir.NewUnaryExpr(pos, ir.ONEW, typ)) case exprSizeof: return ir.NewUintptr(r.pos(), r.typ().Size()) case exprAlignof: return ir.NewUintptr(r.pos(), r.typ().Alignment()) case exprOffsetof: pos := r.pos() typ := r.typ() types.CalcSize(typ) var offset int64 for i := r.Len(); i >= 0; i-- { field := typ.Field(r.Len()) offset += field.Offset typ = field.Type } return ir.NewUintptr(pos, offset) case exprReshape: typ := r.typ() x := r.expr() if types.IdenticalStrict(x.Type(), typ) { return x } // Comparison expressions are constructed as "untyped bool" still. // // TODO(mdempsky): It should be safe to reshape them here too, but // maybe it's better to construct them with the proper type // instead. if x.Type() == types.UntypedBool && typ.IsBoolean() { return x } base.AssertfAt(x.Type().HasShape() || typ.HasShape(), x.Pos(), "%L and %v are not shape types", x, typ) base.AssertfAt(types.Identical(x.Type(), typ), x.Pos(), "%L is not shape-identical to %v", x, typ) // We use ir.HasUniquePos here as a check that x only appears once // in the AST, so it's okay for us to call SetType without // breaking any other uses of it. // // Notably, any ONAMEs should already have the exactly right shape // type and been caught by types.IdenticalStrict above. base.AssertfAt(ir.HasUniquePos(x), x.Pos(), "cannot call SetType(%v) on %L", typ, x) if base.Debug.Reshape != 0 { base.WarnfAt(x.Pos(), "reshaping %L to %v", x, typ) } x.SetType(typ) return x case exprConvert: implicit := r.Bool() typ := r.typ() pos := r.pos() typeWord, srcRType := r.convRTTI(pos) dstTypeParam := r.Bool() identical := r.Bool() x := r.expr() // TODO(mdempsky): Stop constructing expressions of untyped type. x = typecheck.DefaultLit(x, typ) ce := ir.NewConvExpr(pos, ir.OCONV, typ, x) ce.TypeWord, ce.SrcRType = typeWord, srcRType if implicit { ce.SetImplicit(true) } n := typecheck.Expr(ce) // Conversions between non-identical, non-empty interfaces always // requires a runtime call, even if they have identical underlying // interfaces. This is because we create separate itab instances // for each unique interface type, not merely each unique // interface shape. // // However, due to shape types, typecheck.Expr might mistakenly // think a conversion between two non-empty interfaces are // identical and set ir.OCONVNOP, instead of ir.OCONVIFACE. To // ensure we update the itab field appropriately, we force it to // ir.OCONVIFACE instead when shape types are involved. // // TODO(mdempsky): Are there other places we might get this wrong? // Should this be moved down into typecheck.{Assign,Convert}op? // This would be a non-issue if itabs were unique for each // *underlying* interface type instead. if !identical { if n, ok := n.(*ir.ConvExpr); ok && n.Op() == ir.OCONVNOP && n.Type().IsInterface() && !n.Type().IsEmptyInterface() && (n.Type().HasShape() || n.X.Type().HasShape()) { n.SetOp(ir.OCONVIFACE) } } // spec: "If the type is a type parameter, the constant is converted // into a non-constant value of the type parameter." if dstTypeParam && ir.IsConstNode(n) { // Wrap in an OCONVNOP node to ensure result is non-constant. n = Implicit(ir.NewConvExpr(pos, ir.OCONVNOP, n.Type(), n)) n.SetTypecheck(1) } return n case exprRuntimeBuiltin: builtin := typecheck.LookupRuntime(r.String()) return builtin } } // funcInst reads an instantiated function reference, and returns // three (possibly nil) expressions related to it: // // baseFn is always non-nil: it's either a function of the appropriate // type already, or it has an extra dictionary parameter as the first // parameter. // // If dictPtr is non-nil, then it's a dictionary argument that must be // passed as the first argument to baseFn. // // If wrapperFn is non-nil, then it's either the same as baseFn (if // dictPtr is nil), or it's semantically equivalent to currying baseFn // to pass dictPtr. (wrapperFn is nil when dictPtr is an expression // that needs to be computed dynamically.) // // For callers that are creating a call to the returned function, it's // best to emit a call to baseFn, and include dictPtr in the arguments // list as appropriate. // // For callers that want to return the function without invoking it, // they may return wrapperFn if it's non-nil; but otherwise, they need // to create their own wrapper. func (r *reader) funcInst(pos src.XPos) (wrapperFn, baseFn, dictPtr ir.Node) { // Like in methodExpr, I'm pretty sure this isn't needed. var implicits []*types.Type if r.dict != nil { implicits = r.dict.targs } if r.Bool() { // dynamic subdictionary idx := r.Len() info := r.dict.subdicts[idx] explicits := r.p.typListIdx(info.explicits, r.dict) baseFn = r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name) // TODO(mdempsky): Is there a more robust way to get the // dictionary pointer type here? dictPtrType := baseFn.Type().Param(0).Type dictPtr = typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, dictPtrType, r.dictWord(pos, r.dict.subdictsOffset()+idx))) return } info := r.objInfo() explicits := r.p.typListIdx(info.explicits, r.dict) wrapperFn = r.p.objIdx(info.idx, implicits, explicits, false).(*ir.Name) baseFn = r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name) dictName := r.p.objDictName(info.idx, implicits, explicits) dictPtr = typecheck.Expr(ir.NewAddrExpr(pos, dictName)) return } func (pr *pkgReader) objDictName(idx pkgbits.Index, implicits, explicits []*types.Type) *ir.Name { rname := pr.newReader(pkgbits.RelocName, idx, pkgbits.SyncObject1) _, sym := rname.qualifiedIdent() tag := pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj)) if tag == pkgbits.ObjStub { assert(!sym.IsBlank()) if pri, ok := objReader[sym]; ok { return pri.pr.objDictName(pri.idx, nil, explicits) } base.Fatalf("unresolved stub: %v", sym) } dict, err := pr.objDictIdx(sym, idx, implicits, explicits, false) if err != nil { base.Fatalf("%v", err) } return pr.dictNameOf(dict) } // curry returns a function literal that calls fun with arg0 and // (optionally) arg1, accepting additional arguments to the function // literal as necessary to satisfy fun's signature. // // If nilCheck is true and arg0 is an interface value, then it's // checked to be non-nil as an initial step at the point of evaluating // the function literal itself. func (r *reader) curry(origPos src.XPos, ifaceHack bool, fun ir.Node, arg0, arg1 ir.Node) ir.Node { var captured ir.Nodes captured.Append(fun, arg0) if arg1 != nil { captured.Append(arg1) } params, results := syntheticSig(fun.Type()) params = params[len(captured)-1:] // skip curried parameters typ := types.NewSignature(nil, params, results) addBody := func(pos src.XPos, r *reader, captured []ir.Node) { fun := captured[0] var args ir.Nodes args.Append(captured[1:]...) args.Append(r.syntheticArgs()...) r.syntheticTailCall(pos, fun, args) } return r.syntheticClosure(origPos, typ, ifaceHack, captured, addBody) } // methodExprWrap returns a function literal that changes method's // first parameter's type to recv, and uses implicits/deref/addr to // select the appropriate receiver parameter to pass to method. func (r *reader) methodExprWrap(origPos src.XPos, recv *types.Type, implicits []int, deref, addr bool, method, dictPtr ir.Node) ir.Node { var captured ir.Nodes captured.Append(method) params, results := syntheticSig(method.Type()) // Change first parameter to recv. params[0].Type = recv // If we have a dictionary pointer argument to pass, then omit the // underlying method expression's dictionary parameter from the // returned signature too. if dictPtr != nil { captured.Append(dictPtr) params = append(params[:1], params[2:]...) } typ := types.NewSignature(nil, params, results) addBody := func(pos src.XPos, r *reader, captured []ir.Node) { fn := captured[0] args := r.syntheticArgs() // Rewrite first argument based on implicits/deref/addr. { arg := args[0] for _, ix := range implicits { arg = Implicit(typecheck.DotField(pos, arg, ix)) } if deref { arg = Implicit(Deref(pos, arg.Type().Elem(), arg)) } else if addr { arg = Implicit(Addr(pos, arg)) } args[0] = arg } // Insert dictionary argument, if provided. if dictPtr != nil { newArgs := make([]ir.Node, len(args)+1) newArgs[0] = args[0] newArgs[1] = captured[1] copy(newArgs[2:], args[1:]) args = newArgs } r.syntheticTailCall(pos, fn, args) } return r.syntheticClosure(origPos, typ, false, captured, addBody) } // syntheticClosure constructs a synthetic function literal for // currying dictionary arguments. origPos is the position used for the // closure, which must be a non-inlined position. typ is the function // literal's signature type. // // captures is a list of expressions that need to be evaluated at the // point of function literal evaluation and captured by the function // literal. If ifaceHack is true and captures[1] is an interface type, // it's checked to be non-nil after evaluation. // // addBody is a callback function to populate the function body. The // list of captured values passed back has the captured variables for // use within the function literal, corresponding to the expressions // in captures. func (r *reader) syntheticClosure(origPos src.XPos, typ *types.Type, ifaceHack bool, captures ir.Nodes, addBody func(pos src.XPos, r *reader, captured []ir.Node)) ir.Node { // isSafe reports whether n is an expression that we can safely // defer to evaluating inside the closure instead, to avoid storing // them into the closure. // // In practice this is always (and only) the wrappee function. isSafe := func(n ir.Node) bool { if n.Op() == ir.ONAME && n.(*ir.Name).Class == ir.PFUNC { return true } if n.Op() == ir.OMETHEXPR { return true } return false } fn := r.inlClosureFunc(origPos, typ, ir.OCLOSURE) fn.SetWrapper(true) clo := fn.OClosure inlPos := clo.Pos() var init ir.Nodes for i, n := range captures { if isSafe(n) { continue // skip capture; can reference directly } tmp := r.tempCopy(inlPos, n, &init) ir.NewClosureVar(origPos, fn, tmp) // We need to nil check interface receivers at the point of method // value evaluation, ugh. if ifaceHack && i == 1 && n.Type().IsInterface() { check := ir.NewUnaryExpr(inlPos, ir.OCHECKNIL, ir.NewUnaryExpr(inlPos, ir.OITAB, tmp)) init.Append(typecheck.Stmt(check)) } } pri := pkgReaderIndex{synthetic: func(pos src.XPos, r *reader) { captured := make([]ir.Node, len(captures)) next := 0 for i, n := range captures { if isSafe(n) { captured[i] = n } else { captured[i] = r.closureVars[next] next++ } } assert(next == len(r.closureVars)) addBody(origPos, r, captured) }} bodyReader[fn] = pri pri.funcBody(fn) return ir.InitExpr(init, clo) } // syntheticSig duplicates and returns the params and results lists // for sig, but renaming anonymous parameters so they can be assigned // ir.Names. func syntheticSig(sig *types.Type) (params, results []*types.Field) { clone := func(params []*types.Field) []*types.Field { res := make([]*types.Field, len(params)) for i, param := range params { // TODO(mdempsky): It would be nice to preserve the original // parameter positions here instead, but at least // typecheck.NewMethodType replaces them with base.Pos, making // them useless. Worse, the positions copied from base.Pos may // have inlining contexts, which we definitely don't want here // (e.g., #54625). res[i] = types.NewField(base.AutogeneratedPos, param.Sym, param.Type) res[i].SetIsDDD(param.IsDDD()) } return res } return clone(sig.Params()), clone(sig.Results()) } func (r *reader) optExpr() ir.Node { if r.Bool() { return r.expr() } return nil } // methodExpr reads a method expression reference, and returns three // (possibly nil) expressions related to it: // // baseFn is always non-nil: it's either a function of the appropriate // type already, or it has an extra dictionary parameter as the second // parameter (i.e., immediately after the promoted receiver // parameter). // // If dictPtr is non-nil, then it's a dictionary argument that must be // passed as the second argument to baseFn. // // If wrapperFn is non-nil, then it's either the same as baseFn (if // dictPtr is nil), or it's semantically equivalent to currying baseFn // to pass dictPtr. (wrapperFn is nil when dictPtr is an expression // that needs to be computed dynamically.) // // For callers that are creating a call to the returned method, it's // best to emit a call to baseFn, and include dictPtr in the arguments // list as appropriate. // // For callers that want to return a method expression without // invoking it, they may return wrapperFn if it's non-nil; but // otherwise, they need to create their own wrapper. func (r *reader) methodExpr() (wrapperFn, baseFn, dictPtr ir.Node) { recv := r.typ() sig0 := r.typ() pos := r.pos() sym := r.selector() // Signature type to return (i.e., recv prepended to the method's // normal parameters list). sig := typecheck.NewMethodType(sig0, recv) if r.Bool() { // type parameter method expression idx := r.Len() word := r.dictWord(pos, r.dict.typeParamMethodExprsOffset()+idx) // TODO(mdempsky): If the type parameter was instantiated with an // interface type (i.e., embed.IsInterface()), then we could // return the OMETHEXPR instead and save an indirection. // We wrote the method expression's entry point PC into the // dictionary, but for Go `func` values we need to return a // closure (i.e., pointer to a structure with the PC as the first // field). Because method expressions don't have any closure // variables, we pun the dictionary entry as the closure struct. fn := typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, sig, ir.NewAddrExpr(pos, word))) return fn, fn, nil } // TODO(mdempsky): I'm pretty sure this isn't needed: implicits is // only relevant to locally defined types, but they can't have // (non-promoted) methods. var implicits []*types.Type if r.dict != nil { implicits = r.dict.targs } if r.Bool() { // dynamic subdictionary idx := r.Len() info := r.dict.subdicts[idx] explicits := r.p.typListIdx(info.explicits, r.dict) shapedObj := r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name) shapedFn := shapedMethodExpr(pos, shapedObj, sym) // TODO(mdempsky): Is there a more robust way to get the // dictionary pointer type here? dictPtrType := shapedFn.Type().Param(1).Type dictPtr := typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, dictPtrType, r.dictWord(pos, r.dict.subdictsOffset()+idx))) return nil, shapedFn, dictPtr } if r.Bool() { // static dictionary info := r.objInfo() explicits := r.p.typListIdx(info.explicits, r.dict) shapedObj := r.p.objIdx(info.idx, implicits, explicits, true).(*ir.Name) shapedFn := shapedMethodExpr(pos, shapedObj, sym) dict := r.p.objDictName(info.idx, implicits, explicits) dictPtr := typecheck.Expr(ir.NewAddrExpr(pos, dict)) // Check that dictPtr matches shapedFn's dictionary parameter. if !types.Identical(dictPtr.Type(), shapedFn.Type().Param(1).Type) { base.FatalfAt(pos, "dict %L, but shaped method %L", dict, shapedFn) } // For statically known instantiations, we can take advantage of // the stenciled wrapper. base.AssertfAt(!recv.HasShape(), pos, "shaped receiver %v", recv) wrapperFn := typecheck.NewMethodExpr(pos, recv, sym) base.AssertfAt(types.Identical(sig, wrapperFn.Type()), pos, "wrapper %L does not have type %v", wrapperFn, sig) return wrapperFn, shapedFn, dictPtr } // Simple method expression; no dictionary needed. base.AssertfAt(!recv.HasShape() || recv.IsInterface(), pos, "shaped receiver %v", recv) fn := typecheck.NewMethodExpr(pos, recv, sym) return fn, fn, nil } // shapedMethodExpr returns the specified method on the given shaped // type. func shapedMethodExpr(pos src.XPos, obj *ir.Name, sym *types.Sym) *ir.SelectorExpr { assert(obj.Op() == ir.OTYPE) typ := obj.Type() assert(typ.HasShape()) method := func() *types.Field { for _, method := range typ.Methods() { if method.Sym == sym { return method } } base.FatalfAt(pos, "failed to find method %v in shaped type %v", sym, typ) panic("unreachable") }() // Construct an OMETHEXPR node. recv := method.Type.Recv().Type return typecheck.NewMethodExpr(pos, recv, sym) } func (r *reader) multiExpr() []ir.Node { r.Sync(pkgbits.SyncMultiExpr) if r.Bool() { // N:1 pos := r.pos() expr := r.expr() results := make([]ir.Node, r.Len()) as := ir.NewAssignListStmt(pos, ir.OAS2, nil, []ir.Node{expr}) as.Def = true for i := range results { tmp := r.temp(pos, r.typ()) as.PtrInit().Append(ir.NewDecl(pos, ir.ODCL, tmp)) as.Lhs.Append(tmp) res := ir.Node(tmp) if r.Bool() { n := ir.NewConvExpr(pos, ir.OCONV, r.typ(), res) n.TypeWord, n.SrcRType = r.convRTTI(pos) n.SetImplicit(true) res = typecheck.Expr(n) } results[i] = res } // TODO(mdempsky): Could use ir.InlinedCallExpr instead? results[0] = ir.InitExpr([]ir.Node{typecheck.Stmt(as)}, results[0]) return results } // N:N exprs := make([]ir.Node, r.Len()) if len(exprs) == 0 { return nil } for i := range exprs { exprs[i] = r.expr() } return exprs } // temp returns a new autotemp of the specified type. func (r *reader) temp(pos src.XPos, typ *types.Type) *ir.Name { return typecheck.TempAt(pos, r.curfn, typ) } // tempCopy declares and returns a new autotemp initialized to the // value of expr. func (r *reader) tempCopy(pos src.XPos, expr ir.Node, init *ir.Nodes) *ir.Name { tmp := r.temp(pos, expr.Type()) init.Append(typecheck.Stmt(ir.NewDecl(pos, ir.ODCL, tmp))) assign := ir.NewAssignStmt(pos, tmp, expr) assign.Def = true init.Append(typecheck.Stmt(ir.NewAssignStmt(pos, tmp, expr))) tmp.Defn = assign return tmp } func (r *reader) compLit() ir.Node { r.Sync(pkgbits.SyncCompLit) pos := r.pos() typ0 := r.typ() typ := typ0 if typ.IsPtr() { typ = typ.Elem() } if typ.Kind() == types.TFORW { base.FatalfAt(pos, "unresolved composite literal type: %v", typ) } var rtype ir.Node if typ.IsMap() { rtype = r.rtype(pos) } isStruct := typ.Kind() == types.TSTRUCT elems := make([]ir.Node, r.Len()) for i := range elems { elemp := &elems[i] if isStruct { sk := ir.NewStructKeyExpr(r.pos(), typ.Field(r.Len()), nil) *elemp, elemp = sk, &sk.Value } else if r.Bool() { kv := ir.NewKeyExpr(r.pos(), r.expr(), nil) *elemp, elemp = kv, &kv.Value } *elemp = r.expr() } lit := typecheck.Expr(ir.NewCompLitExpr(pos, ir.OCOMPLIT, typ, elems)) if rtype != nil { lit := lit.(*ir.CompLitExpr) lit.RType = rtype } if typ0.IsPtr() { lit = typecheck.Expr(typecheck.NodAddrAt(pos, lit)) lit.SetType(typ0) } return lit } func (r *reader) funcLit() ir.Node { r.Sync(pkgbits.SyncFuncLit) // The underlying function declaration (including its parameters' // positions, if any) need to remain the original, uninlined // positions. This is because we track inlining-context on nodes so // we can synthesize the extra implied stack frames dynamically when // generating tracebacks, whereas those stack frames don't make // sense *within* the function literal. (Any necessary inlining // adjustments will have been applied to the call expression // instead.) // // This is subtle, and getting it wrong leads to cycles in the // inlining tree, which lead to infinite loops during stack // unwinding (#46234, #54625). // // Note that we *do* want the inline-adjusted position for the // OCLOSURE node, because that position represents where any heap // allocation of the closure is credited (#49171). r.suppressInlPos++ origPos := r.pos() sig := r.signature(nil) r.suppressInlPos-- why := ir.OCLOSURE if r.Bool() { why = ir.ORANGE } fn := r.inlClosureFunc(origPos, sig, why) fn.ClosureVars = make([]*ir.Name, 0, r.Len()) for len(fn.ClosureVars) < cap(fn.ClosureVars) { // TODO(mdempsky): I think these should be original positions too // (i.e., not inline-adjusted). ir.NewClosureVar(r.pos(), fn, r.useLocal()) } if param := r.dictParam; param != nil { // If we have a dictionary parameter, capture it too. For // simplicity, we capture it last and unconditionally. ir.NewClosureVar(param.Pos(), fn, param) } r.addBody(fn, nil) return fn.OClosure } // inlClosureFunc constructs a new closure function, but correctly // handles inlining. func (r *reader) inlClosureFunc(origPos src.XPos, sig *types.Type, why ir.Op) *ir.Func { curfn := r.inlCaller if curfn == nil { curfn = r.curfn } // TODO(mdempsky): Remove hard-coding of typecheck.Target. return ir.NewClosureFunc(origPos, r.inlPos(origPos), why, sig, curfn, typecheck.Target) } func (r *reader) exprList() []ir.Node { r.Sync(pkgbits.SyncExprList) return r.exprs() } func (r *reader) exprs() []ir.Node { r.Sync(pkgbits.SyncExprs) nodes := make([]ir.Node, r.Len()) if len(nodes) == 0 { return nil // TODO(mdempsky): Unclear if this matters. } for i := range nodes { nodes[i] = r.expr() } return nodes } // dictWord returns an expression to return the specified // uintptr-typed word from the dictionary parameter. func (r *reader) dictWord(pos src.XPos, idx int) ir.Node { base.AssertfAt(r.dictParam != nil, pos, "expected dictParam in %v", r.curfn) return typecheck.Expr(ir.NewIndexExpr(pos, r.dictParam, ir.NewInt(pos, int64(idx)))) } // rttiWord is like dictWord, but converts it to *byte (the type used // internally to represent *runtime._type and *runtime.itab). func (r *reader) rttiWord(pos src.XPos, idx int) ir.Node { return typecheck.Expr(ir.NewConvExpr(pos, ir.OCONVNOP, types.NewPtr(types.Types[types.TUINT8]), r.dictWord(pos, idx))) } // rtype reads a type reference from the element bitstream, and // returns an expression of type *runtime._type representing that // type. func (r *reader) rtype(pos src.XPos) ir.Node { _, rtype := r.rtype0(pos) return rtype } func (r *reader) rtype0(pos src.XPos) (typ *types.Type, rtype ir.Node) { r.Sync(pkgbits.SyncRType) if r.Bool() { // derived type idx := r.Len() info := r.dict.rtypes[idx] typ = r.p.typIdx(info, r.dict, true) rtype = r.rttiWord(pos, r.dict.rtypesOffset()+idx) return } typ = r.typ() rtype = reflectdata.TypePtrAt(pos, typ) return } // varDictIndex populates name.DictIndex if name is a derived type. func (r *reader) varDictIndex(name *ir.Name) { if r.Bool() { idx := 1 + r.dict.rtypesOffset() + r.Len() if int(uint16(idx)) != idx { base.FatalfAt(name.Pos(), "DictIndex overflow for %v: %v", name, idx) } name.DictIndex = uint16(idx) } } // itab returns a (typ, iface) pair of types. // // typRType and ifaceRType are expressions that evaluate to the // *runtime._type for typ and iface, respectively. // // If typ is a concrete type and iface is a non-empty interface type, // then itab is an expression that evaluates to the *runtime.itab for // the pair. Otherwise, itab is nil. func (r *reader) itab(pos src.XPos) (typ *types.Type, typRType ir.Node, iface *types.Type, ifaceRType ir.Node, itab ir.Node) { typ, typRType = r.rtype0(pos) iface, ifaceRType = r.rtype0(pos) idx := -1 if r.Bool() { idx = r.Len() } if !typ.IsInterface() && iface.IsInterface() && !iface.IsEmptyInterface() { if idx >= 0 { itab = r.rttiWord(pos, r.dict.itabsOffset()+idx) } else { base.AssertfAt(!typ.HasShape(), pos, "%v is a shape type", typ) base.AssertfAt(!iface.HasShape(), pos, "%v is a shape type", iface) lsym := reflectdata.ITabLsym(typ, iface) itab = typecheck.LinksymAddr(pos, lsym, types.Types[types.TUINT8]) } } return } // convRTTI returns expressions appropriate for populating an // ir.ConvExpr's TypeWord and SrcRType fields, respectively. func (r *reader) convRTTI(pos src.XPos) (typeWord, srcRType ir.Node) { r.Sync(pkgbits.SyncConvRTTI) src, srcRType0, dst, dstRType, itab := r.itab(pos) if !dst.IsInterface() { return } // See reflectdata.ConvIfaceTypeWord. switch { case dst.IsEmptyInterface(): if !src.IsInterface() { typeWord = srcRType0 // direct eface construction } case !src.IsInterface(): typeWord = itab // direct iface construction default: typeWord = dstRType // convI2I } // See reflectdata.ConvIfaceSrcRType. if !src.IsInterface() { srcRType = srcRType0 } return } func (r *reader) exprType() ir.Node { r.Sync(pkgbits.SyncExprType) pos := r.pos() var typ *types.Type var rtype, itab ir.Node if r.Bool() { typ, rtype, _, _, itab = r.itab(pos) if !typ.IsInterface() { rtype = nil // TODO(mdempsky): Leave set? } } else { typ, rtype = r.rtype0(pos) if !r.Bool() { // not derived return ir.TypeNode(typ) } } dt := ir.NewDynamicType(pos, rtype) dt.ITab = itab return typed(typ, dt) } func (r *reader) op() ir.Op { r.Sync(pkgbits.SyncOp) return ir.Op(r.Len()) } // @@@ Package initialization func (r *reader) pkgInit(self *types.Pkg, target *ir.Package) { cgoPragmas := make([][]string, r.Len()) for i := range cgoPragmas { cgoPragmas[i] = r.Strings() } target.CgoPragmas = cgoPragmas r.pkgInitOrder(target) r.pkgDecls(target) r.Sync(pkgbits.SyncEOF) } // pkgInitOrder creates a synthetic init function to handle any // package-scope initialization statements. func (r *reader) pkgInitOrder(target *ir.Package) { initOrder := make([]ir.Node, r.Len()) if len(initOrder) == 0 { return } // Make a function that contains all the initialization statements. pos := base.AutogeneratedPos base.Pos = pos fn := ir.NewFunc(pos, pos, typecheck.Lookup("init"), types.NewSignature(nil, nil, nil)) fn.SetIsPackageInit(true) fn.SetInlinabilityChecked(true) // suppress useless "can inline" diagnostics typecheck.DeclFunc(fn) r.curfn = fn for i := range initOrder { lhs := make([]ir.Node, r.Len()) for j := range lhs { lhs[j] = r.obj() } rhs := r.expr() pos := lhs[0].Pos() var as ir.Node if len(lhs) == 1 { as = typecheck.Stmt(ir.NewAssignStmt(pos, lhs[0], rhs)) } else { as = typecheck.Stmt(ir.NewAssignListStmt(pos, ir.OAS2, lhs, []ir.Node{rhs})) } for _, v := range lhs { v.(*ir.Name).Defn = as } initOrder[i] = as } fn.Body = initOrder typecheck.FinishFuncBody() r.curfn = nil r.locals = nil // Outline (if legal/profitable) global map inits. staticinit.OutlineMapInits(fn) target.Inits = append(target.Inits, fn) } func (r *reader) pkgDecls(target *ir.Package) { r.Sync(pkgbits.SyncDecls) for { switch code := codeDecl(r.Code(pkgbits.SyncDecl)); code { default: panic(fmt.Sprintf("unhandled decl: %v", code)) case declEnd: return case declFunc: names := r.pkgObjs(target) assert(len(names) == 1) target.Funcs = append(target.Funcs, names[0].Func) case declMethod: typ := r.typ() sym := r.selector() method := typecheck.Lookdot1(nil, sym, typ, typ.Methods(), 0) target.Funcs = append(target.Funcs, method.Nname.(*ir.Name).Func) case declVar: names := r.pkgObjs(target) if n := r.Len(); n > 0 { assert(len(names) == 1) embeds := make([]ir.Embed, n) for i := range embeds { embeds[i] = ir.Embed{Pos: r.pos(), Patterns: r.Strings()} } names[0].Embed = &embeds target.Embeds = append(target.Embeds, names[0]) } case declOther: r.pkgObjs(target) } } } func (r *reader) pkgObjs(target *ir.Package) []*ir.Name { r.Sync(pkgbits.SyncDeclNames) nodes := make([]*ir.Name, r.Len()) for i := range nodes { r.Sync(pkgbits.SyncDeclName) name := r.obj().(*ir.Name) nodes[i] = name sym := name.Sym() if sym.IsBlank() { continue } switch name.Class { default: base.FatalfAt(name.Pos(), "unexpected class: %v", name.Class) case ir.PEXTERN: target.Externs = append(target.Externs, name) case ir.PFUNC: assert(name.Type().Recv() == nil) // TODO(mdempsky): Cleaner way to recognize init? if strings.HasPrefix(sym.Name, "init.") { target.Inits = append(target.Inits, name.Func) } } if base.Ctxt.Flag_dynlink && types.LocalPkg.Name == "main" && types.IsExported(sym.Name) && name.Op() == ir.ONAME { assert(!sym.OnExportList()) target.PluginExports = append(target.PluginExports, name) sym.SetOnExportList(true) } if base.Flag.AsmHdr != "" && (name.Op() == ir.OLITERAL || name.Op() == ir.OTYPE) { assert(!sym.Asm()) target.AsmHdrDecls = append(target.AsmHdrDecls, name) sym.SetAsm(true) } } return nodes } // @@@ Inlining // unifiedHaveInlineBody reports whether we have the function body for // fn, so we can inline it. func unifiedHaveInlineBody(fn *ir.Func) bool { if fn.Inl == nil { return false } _, ok := bodyReaderFor(fn) return ok } var inlgen = 0 // unifiedInlineCall implements inline.NewInline by re-reading the function // body from its Unified IR export data. func unifiedInlineCall(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr { pri, ok := bodyReaderFor(fn) if !ok { base.FatalfAt(call.Pos(), "cannot inline call to %v: missing inline body", fn) } if !fn.Inl.HaveDcl { expandInline(fn, pri) } r := pri.asReader(pkgbits.RelocBody, pkgbits.SyncFuncBody) tmpfn := ir.NewFunc(fn.Pos(), fn.Nname.Pos(), callerfn.Sym(), fn.Type()) r.curfn = tmpfn r.inlCaller = callerfn r.inlCall = call r.inlFunc = fn r.inlTreeIndex = inlIndex r.inlPosBases = make(map[*src.PosBase]*src.PosBase) r.funarghack = true r.closureVars = make([]*ir.Name, len(r.inlFunc.ClosureVars)) for i, cv := range r.inlFunc.ClosureVars { // TODO(mdempsky): It should be possible to support this case, but // for now we rely on the inliner avoiding it. if cv.Outer.Curfn != callerfn { base.FatalfAt(call.Pos(), "inlining closure call across frames") } r.closureVars[i] = cv.Outer } if len(r.closureVars) != 0 && r.hasTypeParams() { r.dictParam = r.closureVars[len(r.closureVars)-1] // dictParam is last; see reader.funcLit } r.declareParams() var inlvars, retvars []*ir.Name { sig := r.curfn.Type() endParams := sig.NumRecvs() + sig.NumParams() endResults := endParams + sig.NumResults() inlvars = r.curfn.Dcl[:endParams] retvars = r.curfn.Dcl[endParams:endResults] } r.delayResults = fn.Inl.CanDelayResults r.retlabel = typecheck.AutoLabel(".i") inlgen++ init := ir.TakeInit(call) // For normal function calls, the function callee expression // may contain side effects. Make sure to preserve these, // if necessary (#42703). if call.Op() == ir.OCALLFUNC { inline.CalleeEffects(&init, call.Fun) } var args ir.Nodes if call.Op() == ir.OCALLMETH { base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck") } args.Append(call.Args...) // Create assignment to declare and initialize inlvars. as2 := ir.NewAssignListStmt(call.Pos(), ir.OAS2, ir.ToNodes(inlvars), args) as2.Def = true var as2init ir.Nodes for _, name := range inlvars { if ir.IsBlank(name) { continue } // TODO(mdempsky): Use inlined position of name.Pos() instead? as2init.Append(ir.NewDecl(call.Pos(), ir.ODCL, name)) name.Defn = as2 } as2.SetInit(as2init) init.Append(typecheck.Stmt(as2)) if !r.delayResults { // If not delaying retvars, declare and zero initialize the // result variables now. for _, name := range retvars { // TODO(mdempsky): Use inlined position of name.Pos() instead? init.Append(ir.NewDecl(call.Pos(), ir.ODCL, name)) ras := ir.NewAssignStmt(call.Pos(), name, nil) init.Append(typecheck.Stmt(ras)) } } // Add an inline mark just before the inlined body. // This mark is inline in the code so that it's a reasonable spot // to put a breakpoint. Not sure if that's really necessary or not // (in which case it could go at the end of the function instead). // Note issue 28603. init.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(r.inlTreeIndex))) ir.WithFunc(r.curfn, func() { if !r.syntheticBody(call.Pos()) { assert(r.Bool()) // have body r.curfn.Body = r.stmts() r.curfn.Endlineno = r.pos() } // TODO(mdempsky): This shouldn't be necessary. Inlining might // read in new function/method declarations, which could // potentially be recursively inlined themselves; but we shouldn't // need to read in the non-inlined bodies for the declarations // themselves. But currently it's an easy fix to #50552. readBodies(typecheck.Target, true) // Replace any "return" statements within the function body. var edit func(ir.Node) ir.Node edit = func(n ir.Node) ir.Node { if ret, ok := n.(*ir.ReturnStmt); ok { n = typecheck.Stmt(r.inlReturn(ret, retvars)) } ir.EditChildren(n, edit) return n } edit(r.curfn) }) body := ir.Nodes(r.curfn.Body) // Reparent any declarations into the caller function. for _, name := range r.curfn.Dcl { name.Curfn = callerfn if name.Class != ir.PAUTO { name.SetPos(r.inlPos(name.Pos())) name.SetInlFormal(true) name.Class = ir.PAUTO } else { name.SetInlLocal(true) } } callerfn.Dcl = append(callerfn.Dcl, r.curfn.Dcl...) body.Append(ir.NewLabelStmt(call.Pos(), r.retlabel)) res := ir.NewInlinedCallExpr(call.Pos(), body, ir.ToNodes(retvars)) res.SetInit(init) res.SetType(call.Type()) res.SetTypecheck(1) // Inlining shouldn't add any functions to todoBodies. assert(len(todoBodies) == 0) return res } // inlReturn returns a statement that can substitute for the given // return statement when inlining. func (r *reader) inlReturn(ret *ir.ReturnStmt, retvars []*ir.Name) *ir.BlockStmt { pos := r.inlCall.Pos() block := ir.TakeInit(ret) if results := ret.Results; len(results) != 0 { assert(len(retvars) == len(results)) as2 := ir.NewAssignListStmt(pos, ir.OAS2, ir.ToNodes(retvars), ret.Results) if r.delayResults { for _, name := range retvars { // TODO(mdempsky): Use inlined position of name.Pos() instead? block.Append(ir.NewDecl(pos, ir.ODCL, name)) name.Defn = as2 } } block.Append(as2) } block.Append(ir.NewBranchStmt(pos, ir.OGOTO, r.retlabel)) return ir.NewBlockStmt(pos, block) } // expandInline reads in an extra copy of IR to populate // fn.Inl.Dcl. func expandInline(fn *ir.Func, pri pkgReaderIndex) { // TODO(mdempsky): Remove this function. It's currently needed by // dwarfgen/dwarf.go:preInliningDcls, which requires fn.Inl.Dcl to // create abstract function DIEs. But we should be able to provide it // with the same information some other way. fndcls := len(fn.Dcl) topdcls := len(typecheck.Target.Funcs) tmpfn := ir.NewFunc(fn.Pos(), fn.Nname.Pos(), fn.Sym(), fn.Type()) tmpfn.ClosureVars = fn.ClosureVars { r := pri.asReader(pkgbits.RelocBody, pkgbits.SyncFuncBody) // Don't change parameter's Sym/Nname fields. r.funarghack = true r.funcBody(tmpfn) } // Move tmpfn's params to fn.Inl.Dcl, and reparent under fn. for _, name := range tmpfn.Dcl { name.Curfn = fn } fn.Inl.Dcl = tmpfn.Dcl fn.Inl.HaveDcl = true // Double check that we didn't change fn.Dcl by accident. assert(fndcls == len(fn.Dcl)) // typecheck.Stmts may have added function literals to // typecheck.Target.Decls. Remove them again so we don't risk trying // to compile them multiple times. typecheck.Target.Funcs = typecheck.Target.Funcs[:topdcls] } // usedLocals returns a set of local variables that are used within body. func usedLocals(body []ir.Node) ir.NameSet { var used ir.NameSet ir.VisitList(body, func(n ir.Node) { if n, ok := n.(*ir.Name); ok && n.Op() == ir.ONAME && n.Class == ir.PAUTO { used.Add(n) } }) return used } // @@@ Method wrappers // // Here we handle constructing "method wrappers," alternative entry // points that adapt methods to different calling conventions. Given a // user-declared method "func (T) M(i int) bool { ... }", there are a // few wrappers we may need to construct: // // - Implicit dereferencing. Methods declared with a value receiver T // are also included in the method set of the pointer type *T, so // we need to construct a wrapper like "func (recv *T) M(i int) // bool { return (*recv).M(i) }". // // - Promoted methods. If struct type U contains an embedded field of // type T or *T, we need to construct a wrapper like "func (recv U) // M(i int) bool { return recv.T.M(i) }". // // - Method values. If x is an expression of type T, then "x.M" is // roughly "tmp := x; func(i int) bool { return tmp.M(i) }". // // At call sites, we always prefer to call the user-declared method // directly, if known, so wrappers are only needed for indirect calls // (for example, interface method calls that can't be devirtualized). // Consequently, we can save some compile time by skipping // construction of wrappers that are never needed. // // Alternatively, because the linker doesn't care which compilation // unit constructed a particular wrapper, we can instead construct // them as needed. However, if a wrapper is needed in multiple // downstream packages, we may end up needing to compile it multiple // times, costing us more compile time and object file size. (We mark // the wrappers as DUPOK, so the linker doesn't complain about the // duplicate symbols.) // // The current heuristics we use to balance these trade offs are: // // - For a (non-parameterized) defined type T, we construct wrappers // for *T and any promoted methods on T (and *T) in the same // compilation unit as the type declaration. // // - For a parameterized defined type, we construct wrappers in the // compilation units in which the type is instantiated. We // similarly handle wrappers for anonymous types with methods and // compilation units where their type literals appear in source. // // - Method value expressions are relatively uncommon, so we // construct their wrappers in the compilation units that they // appear in. // // Finally, as an opportunistic compile-time optimization, if we know // a wrapper was constructed in any imported package's compilation // unit, then we skip constructing a duplicate one. However, currently // this is only done on a best-effort basis. // needWrapperTypes lists types for which we may need to generate // method wrappers. var needWrapperTypes []*types.Type // haveWrapperTypes lists types for which we know we already have // method wrappers, because we found the type in an imported package. var haveWrapperTypes []*types.Type // needMethodValueWrappers lists methods for which we may need to // generate method value wrappers. var needMethodValueWrappers []methodValueWrapper // haveMethodValueWrappers lists methods for which we know we already // have method value wrappers, because we found it in an imported // package. var haveMethodValueWrappers []methodValueWrapper type methodValueWrapper struct { rcvr *types.Type method *types.Field } // needWrapper records that wrapper methods may be needed at link // time. func (r *reader) needWrapper(typ *types.Type) { if typ.IsPtr() { return } // Special case: runtime must define error even if imported packages mention it (#29304). forceNeed := typ == types.ErrorType && base.Ctxt.Pkgpath == "runtime" // If a type was found in an imported package, then we can assume // that package (or one of its transitive dependencies) already // generated method wrappers for it. if r.importedDef() && !forceNeed { haveWrapperTypes = append(haveWrapperTypes, typ) } else { needWrapperTypes = append(needWrapperTypes, typ) } } // importedDef reports whether r is reading from an imported and // non-generic element. // // If a type was found in an imported package, then we can assume that // package (or one of its transitive dependencies) already generated // method wrappers for it. // // Exception: If we're instantiating an imported generic type or // function, we might be instantiating it with type arguments not // previously seen before. // // TODO(mdempsky): Distinguish when a generic function or type was // instantiated in an imported package so that we can add types to // haveWrapperTypes instead. func (r *reader) importedDef() bool { return r.p != localPkgReader && !r.hasTypeParams() } // MakeWrappers constructs all wrapper methods needed for the target // compilation unit. func MakeWrappers(target *ir.Package) { // always generate a wrapper for error.Error (#29304) needWrapperTypes = append(needWrapperTypes, types.ErrorType) seen := make(map[string]*types.Type) for _, typ := range haveWrapperTypes { wrapType(typ, target, seen, false) } haveWrapperTypes = nil for _, typ := range needWrapperTypes { wrapType(typ, target, seen, true) } needWrapperTypes = nil for _, wrapper := range haveMethodValueWrappers { wrapMethodValue(wrapper.rcvr, wrapper.method, target, false) } haveMethodValueWrappers = nil for _, wrapper := range needMethodValueWrappers { wrapMethodValue(wrapper.rcvr, wrapper.method, target, true) } needMethodValueWrappers = nil } func wrapType(typ *types.Type, target *ir.Package, seen map[string]*types.Type, needed bool) { key := typ.LinkString() if prev := seen[key]; prev != nil { if !types.Identical(typ, prev) { base.Fatalf("collision: types %v and %v have link string %q", typ, prev, key) } return } seen[key] = typ if !needed { // Only called to add to 'seen'. return } if !typ.IsInterface() { typecheck.CalcMethods(typ) } for _, meth := range typ.AllMethods() { if meth.Sym.IsBlank() || !meth.IsMethod() { base.FatalfAt(meth.Pos, "invalid method: %v", meth) } methodWrapper(0, typ, meth, target) // For non-interface types, we also want *T wrappers. if !typ.IsInterface() { methodWrapper(1, typ, meth, target) // For not-in-heap types, *T is a scalar, not pointer shaped, // so the interface wrappers use **T. if typ.NotInHeap() { methodWrapper(2, typ, meth, target) } } } } func methodWrapper(derefs int, tbase *types.Type, method *types.Field, target *ir.Package) { wrapper := tbase for i := 0; i < derefs; i++ { wrapper = types.NewPtr(wrapper) } sym := ir.MethodSym(wrapper, method.Sym) base.Assertf(!sym.Siggen(), "already generated wrapper %v", sym) sym.SetSiggen(true) wrappee := method.Type.Recv().Type if types.Identical(wrapper, wrappee) || !types.IsMethodApplicable(wrapper, method) || !reflectdata.NeedEmit(tbase) { return } // TODO(mdempsky): Use method.Pos instead? pos := base.AutogeneratedPos fn := newWrapperFunc(pos, sym, wrapper, method) var recv ir.Node = fn.Nname.Type().Recv().Nname.(*ir.Name) // For simple *T wrappers around T methods, panicwrap produces a // nicer panic message. if wrapper.IsPtr() && types.Identical(wrapper.Elem(), wrappee) { cond := ir.NewBinaryExpr(pos, ir.OEQ, recv, types.BuiltinPkg.Lookup("nil").Def.(ir.Node)) then := []ir.Node{ir.NewCallExpr(pos, ir.OCALL, typecheck.LookupRuntime("panicwrap"), nil)} fn.Body.Append(ir.NewIfStmt(pos, cond, then, nil)) } // typecheck will add one implicit deref, if necessary, // but not-in-heap types require more for their **T wrappers. for i := 1; i < derefs; i++ { recv = Implicit(ir.NewStarExpr(pos, recv)) } addTailCall(pos, fn, recv, method) finishWrapperFunc(fn, target) } func wrapMethodValue(recvType *types.Type, method *types.Field, target *ir.Package, needed bool) { sym := ir.MethodSymSuffix(recvType, method.Sym, "-fm") if sym.Uniq() { return } sym.SetUniq(true) // TODO(mdempsky): Use method.Pos instead? pos := base.AutogeneratedPos fn := newWrapperFunc(pos, sym, nil, method) sym.Def = fn.Nname // Declare and initialize variable holding receiver. recv := ir.NewHiddenParam(pos, fn, typecheck.Lookup(".this"), recvType) if !needed { return } addTailCall(pos, fn, recv, method) finishWrapperFunc(fn, target) } func newWrapperFunc(pos src.XPos, sym *types.Sym, wrapper *types.Type, method *types.Field) *ir.Func { sig := newWrapperType(wrapper, method) fn := ir.NewFunc(pos, pos, sym, sig) fn.DeclareParams(true) fn.SetDupok(true) // TODO(mdempsky): Leave unset for local, non-generic wrappers? return fn } func finishWrapperFunc(fn *ir.Func, target *ir.Package) { ir.WithFunc(fn, func() { typecheck.Stmts(fn.Body) }) // We generate wrappers after the global inlining pass, // so we're responsible for applying inlining ourselves here. // TODO(prattmic): plumb PGO. interleaved.DevirtualizeAndInlineFunc(fn, nil) // The body of wrapper function after inlining may reveal new ir.OMETHVALUE node, // we don't know whether wrapper function has been generated for it or not, so // generate one immediately here. // // Further, after CL 492017, function that construct closures is allowed to be inlined, // even though the closure itself can't be inline. So we also need to visit body of any // closure that we see when visiting body of the wrapper function. ir.VisitFuncAndClosures(fn, func(n ir.Node) { if n, ok := n.(*ir.SelectorExpr); ok && n.Op() == ir.OMETHVALUE { wrapMethodValue(n.X.Type(), n.Selection, target, true) } }) fn.Nname.Defn = fn target.Funcs = append(target.Funcs, fn) } // newWrapperType returns a copy of the given signature type, but with // the receiver parameter type substituted with recvType. // If recvType is nil, newWrapperType returns a signature // without a receiver parameter. func newWrapperType(recvType *types.Type, method *types.Field) *types.Type { clone := func(params []*types.Field) []*types.Field { res := make([]*types.Field, len(params)) for i, param := range params { res[i] = types.NewField(param.Pos, param.Sym, param.Type) res[i].SetIsDDD(param.IsDDD()) } return res } sig := method.Type var recv *types.Field if recvType != nil { recv = types.NewField(sig.Recv().Pos, sig.Recv().Sym, recvType) } params := clone(sig.Params()) results := clone(sig.Results()) return types.NewSignature(recv, params, results) } func addTailCall(pos src.XPos, fn *ir.Func, recv ir.Node, method *types.Field) { sig := fn.Nname.Type() args := make([]ir.Node, sig.NumParams()) for i, param := range sig.Params() { args[i] = param.Nname.(*ir.Name) } // TODO(mdempsky): Support creating OTAILCALL, when possible. See reflectdata.methodWrapper. // Not urgent though, because tail calls are currently incompatible with regabi anyway. fn.SetWrapper(true) // TODO(mdempsky): Leave unset for tail calls? dot := typecheck.XDotMethod(pos, recv, method.Sym, true) call := typecheck.Call(pos, dot, args, method.Type.IsVariadic()).(*ir.CallExpr) if method.Type.NumResults() == 0 { fn.Body.Append(call) return } ret := ir.NewReturnStmt(pos, nil) ret.Results = []ir.Node{call} fn.Body.Append(ret) } func setBasePos(pos src.XPos) { // Set the position for any error messages we might print (e.g. too large types). base.Pos = pos } // dictParamName is the name of the synthetic dictionary parameter // added to shaped functions. // // N.B., this variable name is known to Delve: // https://github.com/go-delve/delve/blob/cb91509630529e6055be845688fd21eb89ae8714/pkg/proc/eval.go#L28 const dictParamName = typecheck.LocalDictName // shapeSig returns a copy of fn's signature, except adding a // dictionary parameter and promoting the receiver parameter (if any) // to a normal parameter. // // The parameter types.Fields are all copied too, so their Nname // fields can be initialized for use by the shape function. func shapeSig(fn *ir.Func, dict *readerDict) *types.Type { sig := fn.Nname.Type() oldRecv := sig.Recv() var recv *types.Field if oldRecv != nil { recv = types.NewField(oldRecv.Pos, oldRecv.Sym, oldRecv.Type) } params := make([]*types.Field, 1+sig.NumParams()) params[0] = types.NewField(fn.Pos(), fn.Sym().Pkg.Lookup(dictParamName), types.NewPtr(dict.varType())) for i, param := range sig.Params() { d := types.NewField(param.Pos, param.Sym, param.Type) d.SetIsDDD(param.IsDDD()) params[1+i] = d } results := make([]*types.Field, sig.NumResults()) for i, result := range sig.Results() { results[i] = types.NewField(result.Pos, result.Sym, result.Type) } return types.NewSignature(recv, params, results) }
go/src/cmd/compile/internal/noder/reader.go/0
{ "file_path": "go/src/cmd/compile/internal/noder/reader.go", "repo_id": "go", "token_count": 43070 }
95
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* Package rangefunc rewrites range-over-func to code that doesn't use range-over-funcs. Rewriting the construct in the front end, before noder, means the functions generated during the rewrite are available in a noder-generated representation for inlining by the back end. # Theory of Operation The basic idea is to rewrite for x := range f { ... } into f(func(x T) bool { ... }) But it's not usually that easy. # Range variables For a range not using :=, the assigned variables cannot be function parameters in the generated body function. Instead, we allocate fake parameters and start the body with an assignment. For example: for expr1, expr2 = range f { ... } becomes f(func(#p1 T1, #p2 T2) bool { expr1, expr2 = #p1, #p2 ... }) (All the generated variables have a # at the start to signal that they are internal variables when looking at the generated code in a debugger. Because variables have all been resolved to the specific objects they represent, there is no danger of using plain "p1" and colliding with a Go variable named "p1"; the # is just nice to have, not for correctness.) It can also happen that there are fewer range variables than function arguments, in which case we end up with something like f(func(x T1, _ T2) bool { ... }) or f(func(#p1 T1, #p2 T2, _ T3) bool { expr1, expr2 = #p1, #p2 ... }) # Return If the body contains a "break", that break turns into "return false", to tell f to stop. And if the body contains a "continue", that turns into "return true", to tell f to proceed with the next value. Those are the easy cases. If the body contains a return or a break/continue/goto L, then we need to rewrite that into code that breaks out of the loop and then triggers that control flow. In general we rewrite for x := range f { ... } into { var #next int f(func(x T1) bool { ... return true }) ... check #next ... } The variable #next is an integer code that says what to do when f returns. Each difficult statement sets #next and then returns false to stop f. A plain "return" rewrites to {#next = -1; return false}. The return false breaks the loop. Then when f returns, the "check #next" section includes if #next == -1 { return } which causes the return we want. Return with arguments is more involved, and has to deal with corner cases involving panic, defer, and recover. The results of the enclosing function or closure are rewritten to give them names if they don't have them already, and the names are assigned at the return site. func foo() (#rv1 A, #rv2 B) { { var ( #next int ) f(func(x T1) bool { ... { // return a, b #rv1, #rv2 = a, b #next = -1 return false } ... return true }) if #next == -1 { return } } # Checking To permit checking that an iterator is well-behaved -- that is, that it does not call the loop body again after it has returned false or after the entire loop has exited (it might retain a copy of the body function, or pass it to another goroutine) -- each generated loop has its own #stateK variable that is used to check for permitted call patterns to the yield function for a loop body. The state values are: abi.RF_DONE = 0 // body of loop has exited in a non-panic way abi.RF_READY = 1 // body of loop has not exited yet, is not running abi.RF_PANIC = 2 // body of loop is either currently running, or has panicked abi.RF_EXHAUSTED = 3 // iterator function call, e.g. f(func(x t){...}), returned so the sequence is "exhausted". abi.RF_MISSING_PANIC = 4 // used to report errors. The value of #stateK transitions (1) before calling the iterator function, var #stateN = abi.RF_READY (2) after the iterator function call returns, if #stateN == abi.RF_PANIC { panic(runtime.panicrangestate(abi.RF_MISSING_PANIC)) } #stateN = abi.RF_EXHAUSTED (3) at the beginning of the iteration of the loop body, if #stateN != abi.RF_READY { runtime.panicrangestate(#stateN) } #stateN = abi.RF_PANIC (4) when loop iteration continues, #stateN = abi.RF_READY [return true] (5) when control flow exits the loop body. #stateN = abi.RF_DONE [return false] For example: for x := range f { ... if ... { break } ... } becomes { var #state1 = abi.RF_READY f(func(x T1) bool { if #state1 != abi.RF_READY { runtime.panicrangestate(#state1) } #state1 = abi.RF_PANIC ... if ... { #state1 = abi.RF_DONE ; return false } ... #state1 = abi.RF_READY return true }) if #state1 == abi.RF_PANIC { // the code for the loop body did not return normally panic(runtime.panicrangestate(abi.RF_MISSING_PANIC)) } #state1 = abi.RF_EXHAUSTED } # Nested Loops So far we've only considered a single loop. If a function contains a sequence of loops, each can be translated individually. But loops can be nested. It would work to translate the innermost loop and then translate the loop around it, and so on, except that there'd be a lot of rewriting of rewritten code and the overall traversals could end up taking time quadratic in the depth of the nesting. To avoid all that, we use a single rewriting pass that handles a top-most range-over-func loop and all the range-over-func loops it contains at the same time. If we need to return from inside a doubly-nested loop, the rewrites above stay the same, but the check after the inner loop only says if #next < 0 { return false } to stop the outer loop so it can do the actual return. That is, for range f { for range g { ... return a, b ... } } becomes { var ( #next int ) var #state1 = abi.RF_READY f(func() bool { if #state1 != abi.RF_READY { runtime.panicrangestate(#state1) } #state1 = abi.RF_PANIC var #state2 = abi.RF_READY g(func() bool { if #state2 != abi.RF_READY { runtime.panicrangestate(#state2) } ... { // return a, b #rv1, #rv2 = a, b #next = -1 #state2 = abi.RF_DONE return false } ... #state2 = abi.RF_READY return true }) if #state2 == abi.RF_PANIC { panic(runtime.panicrangestate(abi.RF_MISSING_PANIC)) } #state2 = abi.RF_EXHAUSTED if #next < 0 { #state1 = abi.RF_DONE return false } #state1 = abi.RF_READY return true }) if #state1 == abi.RF_PANIC { panic(runtime.panicrangestate(abi.RF_MISSING_PANIC)) } #state1 = abi.RF_EXHAUSTED if #next == -1 { return } } # Labeled break/continue of range-over-func loops For a labeled break or continue of an outer range-over-func, we use positive #next values. Any such labeled break or continue really means "do N breaks" or "do N breaks and 1 continue". The positive #next value tells which level of loop N to target with a break or continue, where perLoopStep*N means break out of level N and perLoopStep*N-1 means continue into level N. The outermost loop has level 1, therefore #next == perLoopStep means to break from the outermost loop, and #next == perLoopStep-1 means to continue the outermost loop. Loops that might need to propagate a labeled break or continue add one or both of these to the #next checks: // N == depth of this loop, one less than the one just exited. if #next != 0 { if #next >= perLoopStep*N-1 { // break or continue this loop if #next >= perLoopStep*N+1 { // error checking // TODO reason about what exactly can appear // here given full or partial checking. runtime.panicrangestate(abi.RF_DONE) } rv := #next & 1 == 1 // code generates into #next&1 #next = 0 return rv } return false // or handle returns and gotos } For example (with perLoopStep == 2) F: for range f { // 1, 2 for range g { // 3, 4 for range h { ... break F ... ... continue F ... } } ... } becomes { var #next int var #state1 = abi.RF_READY f(func() { // 1,2 if #state1 != abi.RF_READY { runtime.panicrangestate(#state1) } #state1 = abi.RF_PANIC var #state2 = abi.RF_READY g(func() { // 3,4 if #state2 != abi.RF_READY { runtime.panicrangestate(#state2) } #state2 = abi.RF_PANIC var #state3 = abi.RF_READY h(func() { // 5,6 if #state3 != abi.RF_READY { runtime.panicrangestate(#state3) } #state3 = abi.RF_PANIC ... { // break F #next = 2 #state3 = abi.RF_DONE return false } ... { // continue F #next = 1 #state3 = abi.RF_DONE return false } ... #state3 = abi.RF_READY return true }) if #state3 == abi.RF_PANIC { panic(runtime.panicrangestate(abi.RF_MISSING_PANIC)) } #state3 = abi.RF_EXHAUSTED if #next != 0 { // no breaks or continues targeting this loop #state2 = abi.RF_DONE return false } return true }) if #state2 == abi.RF_PANIC { panic(runtime.panicrangestate(abi.RF_MISSING_PANIC)) } #state2 = abi.RF_EXHAUSTED if #next != 0 { // just exited g, test for break/continue applied to f/F if #next >= 1 { if #next >= 3 { runtime.panicrangestate(abi.RF_DONE) } // error rv := #next&1 == 1 #next = 0 return rv } #state1 = abi.RF_DONE return false } ... return true }) if #state1 == abi.RF_PANIC { panic(runtime.panicrangestate(abi.RF_MISSING_PANIC)) } #state1 = abi.RF_EXHAUSTED } Note that the post-h checks only consider a break, since no generated code tries to continue g. # Gotos and other labeled break/continue The final control flow translations are goto and break/continue of a non-range-over-func statement. In both cases, we may need to break out of one or more range-over-func loops before we can do the actual control flow statement. Each such break/continue/goto L statement is assigned a unique negative #next value (since -1 is return). Then the post-checks for a given loop test for the specific codes that refer to labels directly targetable from that block. Otherwise, the generic if #next < 0 { return false } check handles stopping the next loop to get one step closer to the label. For example Top: print("start\n") for range f { for range g { ... for range h { ... goto Top ... } } } becomes Top: print("start\n") { var #next int var #state1 = abi.RF_READY f(func() { if #state1 != abi.RF_READY{ runtime.panicrangestate(#state1) } #state1 = abi.RF_PANIC var #state2 = abi.RF_READY g(func() { if #state2 != abi.RF_READY { runtime.panicrangestate(#state2) } #state2 = abi.RF_PANIC ... var #state3 bool = abi.RF_READY h(func() { if #state3 != abi.RF_READY { runtime.panicrangestate(#state3) } #state3 = abi.RF_PANIC ... { // goto Top #next = -3 #state3 = abi.RF_DONE return false } ... #state3 = abi.RF_READY return true }) if #state3 == abi.RF_PANIC {runtime.panicrangestate(abi.RF_MISSING_PANIC)} #state3 = abi.RF_EXHAUSTED if #next < 0 { #state2 = abi.RF_DONE return false } #state2 = abi.RF_READY return true }) if #state2 == abi.RF_PANIC {runtime.panicrangestate(abi.RF_MISSING_PANIC)} #state2 = abi.RF_EXHAUSTED if #next < 0 { #state1 = abi.RF_DONE return false } #state1 = abi.RF_READY return true }) if #state1 == abi.RF_PANIC {runtime.panicrangestate(abi.RF_MISSING_PANIC)} #state1 = abi.RF_EXHAUSTED if #next == -3 { #next = 0 goto Top } } Labeled break/continue to non-range-over-funcs are handled the same way as goto. # Defers The last wrinkle is handling defer statements. If we have for range f { defer print("A") } we cannot rewrite that into f(func() { defer print("A") }) because the deferred code will run at the end of the iteration, not the end of the containing function. To fix that, the runtime provides a special hook that lets us obtain a defer "token" representing the outer function and then use it in a later defer to attach the deferred code to that outer function. Normally, defer print("A") compiles to runtime.deferproc(func() { print("A") }) This changes in a range-over-func. For example: for range f { defer print("A") } compiles to var #defers = runtime.deferrangefunc() f(func() { runtime.deferprocat(func() { print("A") }, #defers) }) For this rewriting phase, we insert the explicit initialization of #defers and then attach the #defers variable to the CallStmt representing the defer. That variable will be propagated to the backend and will cause the backend to compile the defer using deferprocat instead of an ordinary deferproc. TODO: Could call runtime.deferrangefuncend after f. */ package rangefunc import ( "cmd/compile/internal/base" "cmd/compile/internal/syntax" "cmd/compile/internal/types2" "fmt" "go/constant" "internal/abi" "os" ) // nopos is the zero syntax.Pos. var nopos syntax.Pos // A rewriter implements rewriting the range-over-funcs in a given function. type rewriter struct { pkg *types2.Package info *types2.Info sig *types2.Signature outer *syntax.FuncType body *syntax.BlockStmt // References to important types and values. any types2.Object bool types2.Object int types2.Object true types2.Object false types2.Object // Branch numbering, computed as needed. branchNext map[branch]int // branch -> #next value labelLoop map[string]*syntax.ForStmt // label -> innermost rangefunc loop it is declared inside (nil for no loop) // Stack of nodes being visited. stack []syntax.Node // all nodes forStack []*forLoop // range-over-func loops rewritten map[*syntax.ForStmt]syntax.Stmt // Declared variables in generated code for outermost loop. declStmt *syntax.DeclStmt nextVar types2.Object defers types2.Object stateVarCount int // stateVars are referenced from their respective loops bodyClosureCount int // to help the debugger, the closures generated for loop bodies get names rangefuncBodyClosures map[*syntax.FuncLit]bool } // A branch is a single labeled branch. type branch struct { tok syntax.Token label string } // A forLoop describes a single range-over-func loop being processed. type forLoop struct { nfor *syntax.ForStmt // actual syntax stateVar *types2.Var // #state variable for this loop stateVarDecl *syntax.VarDecl depth int // outermost loop has depth 1, otherwise depth = depth(parent)+1 checkRet bool // add check for "return" after loop checkBreak bool // add check for "break" after loop checkContinue bool // add check for "continue" after loop checkBranch []branch // add check for labeled branch after loop } type State int // Rewrite rewrites all the range-over-funcs in the files. // It returns the set of function literals generated from rangefunc loop bodies. // This allows for rangefunc loop bodies to be distinguished by debuggers. func Rewrite(pkg *types2.Package, info *types2.Info, files []*syntax.File) map[*syntax.FuncLit]bool { ri := make(map[*syntax.FuncLit]bool) for _, file := range files { syntax.Inspect(file, func(n syntax.Node) bool { switch n := n.(type) { case *syntax.FuncDecl: sig, _ := info.Defs[n.Name].Type().(*types2.Signature) rewriteFunc(pkg, info, n.Type, n.Body, sig, ri) return false case *syntax.FuncLit: sig, _ := info.Types[n].Type.(*types2.Signature) if sig == nil { tv := n.GetTypeInfo() sig = tv.Type.(*types2.Signature) } rewriteFunc(pkg, info, n.Type, n.Body, sig, ri) return false } return true }) } return ri } // rewriteFunc rewrites all the range-over-funcs in a single function (a top-level func or a func literal). // The typ and body are the function's type and body. func rewriteFunc(pkg *types2.Package, info *types2.Info, typ *syntax.FuncType, body *syntax.BlockStmt, sig *types2.Signature, ri map[*syntax.FuncLit]bool) { if body == nil { return } r := &rewriter{ pkg: pkg, info: info, outer: typ, body: body, sig: sig, rangefuncBodyClosures: ri, } syntax.Inspect(body, r.inspect) if (base.Flag.W != 0) && r.forStack != nil { syntax.Fdump(os.Stderr, body) } } // checkFuncMisuse reports whether to check for misuse of iterator callbacks functions. func (r *rewriter) checkFuncMisuse() bool { return base.Debug.RangeFuncCheck != 0 } // inspect is a callback for syntax.Inspect that drives the actual rewriting. // If it sees a func literal, it kicks off a separate rewrite for that literal. // Otherwise, it maintains a stack of range-over-func loops and // converts each in turn. func (r *rewriter) inspect(n syntax.Node) bool { switch n := n.(type) { case *syntax.FuncLit: sig, _ := r.info.Types[n].Type.(*types2.Signature) if sig == nil { tv := n.GetTypeInfo() sig = tv.Type.(*types2.Signature) } rewriteFunc(r.pkg, r.info, n.Type, n.Body, sig, r.rangefuncBodyClosures) return false default: // Push n onto stack. r.stack = append(r.stack, n) if nfor, ok := forRangeFunc(n); ok { loop := &forLoop{nfor: nfor, depth: 1 + len(r.forStack)} r.forStack = append(r.forStack, loop) r.startLoop(loop) } case nil: // n == nil signals that we are done visiting // the top-of-stack node's children. Find it. n = r.stack[len(r.stack)-1] // If we are inside a range-over-func, // take this moment to replace any break/continue/goto/return // statements directly contained in this node. // Also replace any converted for statements // with the rewritten block. switch n := n.(type) { case *syntax.BlockStmt: for i, s := range n.List { n.List[i] = r.editStmt(s) } case *syntax.CaseClause: for i, s := range n.Body { n.Body[i] = r.editStmt(s) } case *syntax.CommClause: for i, s := range n.Body { n.Body[i] = r.editStmt(s) } case *syntax.LabeledStmt: n.Stmt = r.editStmt(n.Stmt) } // Pop n. if len(r.forStack) > 0 && r.stack[len(r.stack)-1] == r.forStack[len(r.forStack)-1].nfor { r.endLoop(r.forStack[len(r.forStack)-1]) r.forStack = r.forStack[:len(r.forStack)-1] } r.stack = r.stack[:len(r.stack)-1] } return true } // startLoop sets up for converting a range-over-func loop. func (r *rewriter) startLoop(loop *forLoop) { // For first loop in function, allocate syntax for any, bool, int, true, and false. if r.any == nil { r.any = types2.Universe.Lookup("any") r.bool = types2.Universe.Lookup("bool") r.int = types2.Universe.Lookup("int") r.true = types2.Universe.Lookup("true") r.false = types2.Universe.Lookup("false") r.rewritten = make(map[*syntax.ForStmt]syntax.Stmt) } if r.checkFuncMisuse() { // declare the state flag for this loop's body loop.stateVar, loop.stateVarDecl = r.stateVar(loop.nfor.Pos()) } } // editStmt returns the replacement for the statement x, // or x itself if it should be left alone. // This includes the for loops we are converting, // as left in x.rewritten by r.endLoop. func (r *rewriter) editStmt(x syntax.Stmt) syntax.Stmt { if x, ok := x.(*syntax.ForStmt); ok { if s := r.rewritten[x]; s != nil { return s } } if len(r.forStack) > 0 { switch x := x.(type) { case *syntax.BranchStmt: return r.editBranch(x) case *syntax.CallStmt: if x.Tok == syntax.Defer { return r.editDefer(x) } case *syntax.ReturnStmt: return r.editReturn(x) } } return x } // editDefer returns the replacement for the defer statement x. // See the "Defers" section in the package doc comment above for more context. func (r *rewriter) editDefer(x *syntax.CallStmt) syntax.Stmt { if r.defers == nil { // Declare and initialize the #defers token. init := &syntax.CallExpr{ Fun: runtimeSym(r.info, "deferrangefunc"), } tv := syntax.TypeAndValue{Type: r.any.Type()} tv.SetIsValue() init.SetTypeInfo(tv) r.defers = r.declOuterVar("#defers", r.any.Type(), init) } // Attach the token as an "extra" argument to the defer. x.DeferAt = r.useObj(r.defers) setPos(x.DeferAt, x.Pos()) return x } func (r *rewriter) stateVar(pos syntax.Pos) (*types2.Var, *syntax.VarDecl) { r.stateVarCount++ name := fmt.Sprintf("#state%d", r.stateVarCount) typ := r.int.Type() obj := types2.NewVar(pos, r.pkg, name, typ) n := syntax.NewName(pos, name) setValueType(n, typ) r.info.Defs[n] = obj return obj, &syntax.VarDecl{NameList: []*syntax.Name{n}, Values: r.stateConst(abi.RF_READY)} } // editReturn returns the replacement for the return statement x. // See the "Return" section in the package doc comment above for more context. func (r *rewriter) editReturn(x *syntax.ReturnStmt) syntax.Stmt { bl := &syntax.BlockStmt{} if x.Results != nil { // rewrite "return val" into "assign to named result; return" if len(r.outer.ResultList) > 0 { // Make sure that result parameters all have names for i, a := range r.outer.ResultList { if a.Name == nil || a.Name.Value == "_" { r.generateParamName(r.outer.ResultList, i) // updates a.Name } } } // Assign to named results results := []types2.Object{} for _, a := range r.outer.ResultList { results = append(results, r.info.Defs[a.Name]) } bl.List = append(bl.List, &syntax.AssignStmt{Lhs: r.useList(results), Rhs: x.Results}) x.Results = nil } next := -1 // return // Tell the loops along the way to check for a return. for _, loop := range r.forStack { loop.checkRet = true } // Set #next, and return false. bl.List = append(bl.List, &syntax.AssignStmt{Lhs: r.next(), Rhs: r.intConst(next)}) if r.checkFuncMisuse() { // mark this loop as exited, the others (which will be exited if iterators do not interfere) have not, yet. bl.List = append(bl.List, r.setState(abi.RF_DONE, x.Pos())) } bl.List = append(bl.List, &syntax.ReturnStmt{Results: r.useObj(r.false)}) setPos(bl, x.Pos()) return bl } // perLoopStep is part of the encoding of loop-spanning control flow // for function range iterators. Each multiple of two encodes a "return false" // passing control to an enclosing iterator; a terminal value of 1 encodes // "return true" (i.e., local continue) from the body function, and a terminal // value of 0 encodes executing the remainder of the body function. const perLoopStep = 2 // editBranch returns the replacement for the branch statement x, // or x itself if it should be left alone. // See the package doc comment above for more context. func (r *rewriter) editBranch(x *syntax.BranchStmt) syntax.Stmt { if x.Tok == syntax.Fallthrough { // Fallthrough is unaffected by the rewrite. return x } // Find target of break/continue/goto in r.forStack. // (The target may not be in r.forStack at all.) targ := x.Target i := len(r.forStack) - 1 if x.Label == nil && r.forStack[i].nfor != targ { // Unlabeled break or continue that's not nfor must be inside nfor. Leave alone. return x } for i >= 0 && r.forStack[i].nfor != targ { i-- } // exitFrom is the index of the loop interior to the target of the control flow, // if such a loop exists (it does not if i == len(r.forStack) - 1) exitFrom := i + 1 // Compute the value to assign to #next and the specific return to use. var next int var ret *syntax.ReturnStmt if x.Tok == syntax.Goto || i < 0 { // goto Label // or break/continue of labeled non-range-over-func loop (x.Label != nil). // We may be able to leave it alone, or we may have to break // out of one or more nested loops and then use #next to signal // to complete the break/continue/goto. // Figure out which range-over-func loop contains the label. r.computeBranchNext() nfor := r.forStack[len(r.forStack)-1].nfor label := x.Label.Value targ := r.labelLoop[label] if nfor == targ { // Label is in the innermost range-over-func loop; use it directly. return x } // Set #next to the code meaning break/continue/goto label. next = r.branchNext[branch{x.Tok, label}] // Break out of nested loops up to targ. i := len(r.forStack) - 1 for i >= 0 && r.forStack[i].nfor != targ { i-- } exitFrom = i + 1 // Mark loop we exit to get to targ to check for that branch. // When i==-1 / exitFrom == 0 that's the outermost func body. top := r.forStack[exitFrom] top.checkBranch = append(top.checkBranch, branch{x.Tok, label}) // Mark loops along the way to check for a plain return, so they break. for j := exitFrom + 1; j < len(r.forStack); j++ { r.forStack[j].checkRet = true } // In the innermost loop, use a plain "return false". ret = &syntax.ReturnStmt{Results: r.useObj(r.false)} } else { // break/continue of labeled range-over-func loop. if exitFrom == len(r.forStack) { // Simple break or continue. // Continue returns true, break returns false, optionally both adjust state, // neither modifies #next. var state abi.RF_State if x.Tok == syntax.Continue { ret = &syntax.ReturnStmt{Results: r.useObj(r.true)} state = abi.RF_READY } else { ret = &syntax.ReturnStmt{Results: r.useObj(r.false)} state = abi.RF_DONE } var stmts []syntax.Stmt if r.checkFuncMisuse() { stmts = []syntax.Stmt{r.setState(state, x.Pos()), ret} } else { stmts = []syntax.Stmt{ret} } bl := &syntax.BlockStmt{ List: stmts, } setPos(bl, x.Pos()) return bl } ret = &syntax.ReturnStmt{Results: r.useObj(r.false)} // The loop inside the one we are break/continue-ing // needs to make that happen when we break out of it. if x.Tok == syntax.Continue { r.forStack[exitFrom].checkContinue = true } else { exitFrom = i // exitFrom-- r.forStack[exitFrom].checkBreak = true } // The loops along the way just need to break. for j := exitFrom + 1; j < len(r.forStack); j++ { r.forStack[j].checkBreak = true } // Set next to break the appropriate number of times; // the final time may be a continue, not a break. next = perLoopStep * (i + 1) if x.Tok == syntax.Continue { next-- } } // Assign #next = next and do the return. as := &syntax.AssignStmt{Lhs: r.next(), Rhs: r.intConst(next)} bl := &syntax.BlockStmt{ List: []syntax.Stmt{as}, } if r.checkFuncMisuse() { // Set #stateK for this loop. // The exterior loops have not exited yet, and the iterator might interfere. bl.List = append(bl.List, r.setState(abi.RF_DONE, x.Pos())) } bl.List = append(bl.List, ret) setPos(bl, x.Pos()) return bl } // computeBranchNext computes the branchNext numbering // and determines which labels end up inside which range-over-func loop bodies. func (r *rewriter) computeBranchNext() { if r.labelLoop != nil { return } r.labelLoop = make(map[string]*syntax.ForStmt) r.branchNext = make(map[branch]int) var labels []string var stack []syntax.Node var forStack []*syntax.ForStmt forStack = append(forStack, nil) syntax.Inspect(r.body, func(n syntax.Node) bool { if n != nil { stack = append(stack, n) if nfor, ok := forRangeFunc(n); ok { forStack = append(forStack, nfor) } if n, ok := n.(*syntax.LabeledStmt); ok { l := n.Label.Value labels = append(labels, l) f := forStack[len(forStack)-1] r.labelLoop[l] = f } } else { n := stack[len(stack)-1] stack = stack[:len(stack)-1] if n == forStack[len(forStack)-1] { forStack = forStack[:len(forStack)-1] } } return true }) // Assign numbers to all the labels we observed. used := -1 // returns use -1 for _, l := range labels { used -= 3 r.branchNext[branch{syntax.Break, l}] = used r.branchNext[branch{syntax.Continue, l}] = used + 1 r.branchNext[branch{syntax.Goto, l}] = used + 2 } } // endLoop finishes the conversion of a range-over-func loop. // We have inspected and rewritten the body of the loop and can now // construct the body function and rewrite the for loop into a call // bracketed by any declarations and checks it requires. func (r *rewriter) endLoop(loop *forLoop) { // Pick apart for range X { ... } nfor := loop.nfor start, end := nfor.Pos(), nfor.Body.Rbrace // start, end position of for loop rclause := nfor.Init.(*syntax.RangeClause) rfunc := types2.CoreType(rclause.X.GetTypeInfo().Type).(*types2.Signature) // type of X - func(func(...)bool) if rfunc.Params().Len() != 1 { base.Fatalf("invalid typecheck of range func") } ftyp := types2.CoreType(rfunc.Params().At(0).Type()).(*types2.Signature) // func(...) bool if ftyp.Results().Len() != 1 { base.Fatalf("invalid typecheck of range func") } // Give the closure generated for the body a name, to help the debugger connect it to its frame, if active. r.bodyClosureCount++ clo := r.bodyFunc(nfor.Body.List, syntax.UnpackListExpr(rclause.Lhs), rclause.Def, ftyp, start, end) cloDecl, cloVar := r.declSingleVar(fmt.Sprintf("#yield%d", r.bodyClosureCount), clo.GetTypeInfo().Type, clo) setPos(cloDecl, start) // Build X(bodyFunc) call := &syntax.ExprStmt{ X: &syntax.CallExpr{ Fun: rclause.X, ArgList: []syntax.Expr{ r.useObj(cloVar), }, }, } setPos(call, start) // Build checks based on #next after X(bodyFunc) checks := r.checks(loop, end) // Rewrite for vars := range X { ... } to // // { // r.declStmt // call // checks // } // // The r.declStmt can be added to by this loop or any inner loop // during the creation of r.bodyFunc; it is only emitted in the outermost // converted range loop. block := &syntax.BlockStmt{Rbrace: end} setPos(block, start) if len(r.forStack) == 1 && r.declStmt != nil { setPos(r.declStmt, start) block.List = append(block.List, r.declStmt) } // declare the state variable here so it has proper scope and initialization if r.checkFuncMisuse() { stateVarDecl := &syntax.DeclStmt{DeclList: []syntax.Decl{loop.stateVarDecl}} setPos(stateVarDecl, start) block.List = append(block.List, stateVarDecl) } // iteratorFunc(bodyFunc) block.List = append(block.List, cloDecl, call) if r.checkFuncMisuse() { // iteratorFunc has exited, check for swallowed panic, and set body state to abi.RF_EXHAUSTED nif := &syntax.IfStmt{ Cond: r.cond(syntax.Eql, r.useObj(loop.stateVar), r.stateConst(abi.RF_PANIC)), Then: &syntax.BlockStmt{ List: []syntax.Stmt{r.callPanic(start, r.stateConst(abi.RF_MISSING_PANIC))}, }, } setPos(nif, end) block.List = append(block.List, nif) block.List = append(block.List, r.setState(abi.RF_EXHAUSTED, end)) } block.List = append(block.List, checks...) if len(r.forStack) == 1 { // ending an outermost loop r.declStmt = nil r.nextVar = nil r.defers = nil } r.rewritten[nfor] = block } func (r *rewriter) cond(op syntax.Operator, x, y syntax.Expr) *syntax.Operation { cond := &syntax.Operation{Op: op, X: x, Y: y} tv := syntax.TypeAndValue{Type: r.bool.Type()} tv.SetIsValue() cond.SetTypeInfo(tv) return cond } func (r *rewriter) setState(val abi.RF_State, pos syntax.Pos) *syntax.AssignStmt { ss := r.setStateAt(len(r.forStack)-1, val) setPos(ss, pos) return ss } func (r *rewriter) setStateAt(index int, stateVal abi.RF_State) *syntax.AssignStmt { loop := r.forStack[index] return &syntax.AssignStmt{ Lhs: r.useObj(loop.stateVar), Rhs: r.stateConst(stateVal), } } // bodyFunc converts the loop body (control flow has already been updated) // to a func literal that can be passed to the range function. // // vars is the range variables from the range statement. // def indicates whether this is a := range statement. // ftyp is the type of the function we are creating // start and end are the syntax positions to use for new nodes // that should be at the start or end of the loop. func (r *rewriter) bodyFunc(body []syntax.Stmt, lhs []syntax.Expr, def bool, ftyp *types2.Signature, start, end syntax.Pos) *syntax.FuncLit { // Starting X(bodyFunc); build up bodyFunc first. var params, results []*types2.Var results = append(results, types2.NewVar(start, nil, "#r", r.bool.Type())) bodyFunc := &syntax.FuncLit{ // Note: Type is ignored but needs to be non-nil to avoid panic in syntax.Inspect. Type: &syntax.FuncType{}, Body: &syntax.BlockStmt{ List: []syntax.Stmt{}, Rbrace: end, }, } r.rangefuncBodyClosures[bodyFunc] = true setPos(bodyFunc, start) for i := 0; i < ftyp.Params().Len(); i++ { typ := ftyp.Params().At(i).Type() var paramVar *types2.Var if i < len(lhs) && def { // Reuse range variable as parameter. x := lhs[i] paramVar = r.info.Defs[x.(*syntax.Name)].(*types2.Var) } else { // Declare new parameter and assign it to range expression. paramVar = types2.NewVar(start, r.pkg, fmt.Sprintf("#p%d", 1+i), typ) if i < len(lhs) { x := lhs[i] as := &syntax.AssignStmt{Lhs: x, Rhs: r.useObj(paramVar)} as.SetPos(x.Pos()) setPos(as.Rhs, x.Pos()) bodyFunc.Body.List = append(bodyFunc.Body.List, as) } } params = append(params, paramVar) } tv := syntax.TypeAndValue{ Type: types2.NewSignatureType(nil, nil, nil, types2.NewTuple(params...), types2.NewTuple(results...), false), } tv.SetIsValue() bodyFunc.SetTypeInfo(tv) loop := r.forStack[len(r.forStack)-1] if r.checkFuncMisuse() { bodyFunc.Body.List = append(bodyFunc.Body.List, r.assertReady(start, loop)) bodyFunc.Body.List = append(bodyFunc.Body.List, r.setState(abi.RF_PANIC, start)) } // Original loop body (already rewritten by editStmt during inspect). bodyFunc.Body.List = append(bodyFunc.Body.List, body...) // end of loop body, set state to abi.RF_READY and return true to continue iteration if r.checkFuncMisuse() { bodyFunc.Body.List = append(bodyFunc.Body.List, r.setState(abi.RF_READY, end)) } ret := &syntax.ReturnStmt{Results: r.useObj(r.true)} ret.SetPos(end) bodyFunc.Body.List = append(bodyFunc.Body.List, ret) return bodyFunc } // checks returns the post-call checks that need to be done for the given loop. func (r *rewriter) checks(loop *forLoop, pos syntax.Pos) []syntax.Stmt { var list []syntax.Stmt if len(loop.checkBranch) > 0 { did := make(map[branch]bool) for _, br := range loop.checkBranch { if did[br] { continue } did[br] = true doBranch := &syntax.BranchStmt{Tok: br.tok, Label: &syntax.Name{Value: br.label}} list = append(list, r.ifNext(syntax.Eql, r.branchNext[br], true, doBranch)) } } curLoop := loop.depth - 1 curLoopIndex := curLoop - 1 if len(r.forStack) == 1 { if loop.checkRet { list = append(list, r.ifNext(syntax.Eql, -1, false, retStmt(nil))) } } else { // Idealized check, implemented more simply for now. // // N == depth of this loop, one less than the one just exited. // if #next != 0 { // if #next >= perLoopStep*N-1 { // this loop // if #next >= perLoopStep*N+1 { // error checking // runtime.panicrangestate(abi.RF_DONE) // } // rv := #next & 1 == 1 // code generates into #next&1 // #next = 0 // return rv // } // return false // or handle returns and gotos // } if loop.checkRet { // Note: next < 0 also handles gotos handled by outer loops. // We set checkRet in that case to trigger this check. if r.checkFuncMisuse() { list = append(list, r.ifNext(syntax.Lss, 0, false, r.setStateAt(curLoopIndex, abi.RF_DONE), retStmt(r.useObj(r.false)))) } else { list = append(list, r.ifNext(syntax.Lss, 0, false, retStmt(r.useObj(r.false)))) } } depthStep := perLoopStep * (curLoop) if r.checkFuncMisuse() { list = append(list, r.ifNext(syntax.Gtr, depthStep, false, r.callPanic(pos, r.stateConst(abi.RF_DONE)))) } else { list = append(list, r.ifNext(syntax.Gtr, depthStep, true)) } if r.checkFuncMisuse() { if loop.checkContinue { list = append(list, r.ifNext(syntax.Eql, depthStep-1, true, r.setStateAt(curLoopIndex, abi.RF_READY), retStmt(r.useObj(r.true)))) } if loop.checkBreak { list = append(list, r.ifNext(syntax.Eql, depthStep, true, r.setStateAt(curLoopIndex, abi.RF_DONE), retStmt(r.useObj(r.false)))) } if loop.checkContinue || loop.checkBreak { list = append(list, r.ifNext(syntax.Gtr, 0, false, r.setStateAt(curLoopIndex, abi.RF_DONE), retStmt(r.useObj(r.false)))) } } else { if loop.checkContinue { list = append(list, r.ifNext(syntax.Eql, depthStep-1, true, retStmt(r.useObj(r.true)))) } if loop.checkBreak { list = append(list, r.ifNext(syntax.Eql, depthStep, true, retStmt(r.useObj(r.false)))) } if loop.checkContinue || loop.checkBreak { list = append(list, r.ifNext(syntax.Gtr, 0, false, retStmt(r.useObj(r.false)))) } } } for _, j := range list { setPos(j, pos) } return list } // retStmt returns a return statement returning the given return values. func retStmt(results syntax.Expr) *syntax.ReturnStmt { return &syntax.ReturnStmt{Results: results} } // ifNext returns the statement: // // if #next op c { [#next = 0;] thens... } func (r *rewriter) ifNext(op syntax.Operator, c int, zeroNext bool, thens ...syntax.Stmt) syntax.Stmt { var thenList []syntax.Stmt if zeroNext { clr := &syntax.AssignStmt{ Lhs: r.next(), Rhs: r.intConst(0), } thenList = append(thenList, clr) } for _, then := range thens { thenList = append(thenList, then) } nif := &syntax.IfStmt{ Cond: r.cond(op, r.next(), r.intConst(c)), Then: &syntax.BlockStmt{ List: thenList, }, } return nif } // setValueType marks x as a value with type typ. func setValueType(x syntax.Expr, typ syntax.Type) { tv := syntax.TypeAndValue{Type: typ} tv.SetIsValue() x.SetTypeInfo(tv) } // assertReady returns the statement: // // if #stateK != abi.RF_READY { runtime.panicrangestate(#stateK) } // // where #stateK is the state variable for loop. func (r *rewriter) assertReady(start syntax.Pos, loop *forLoop) syntax.Stmt { nif := &syntax.IfStmt{ Cond: r.cond(syntax.Neq, r.useObj(loop.stateVar), r.stateConst(abi.RF_READY)), Then: &syntax.BlockStmt{ List: []syntax.Stmt{r.callPanic(start, r.useObj(loop.stateVar))}, }, } setPos(nif, start) return nif } func (r *rewriter) callPanic(start syntax.Pos, arg syntax.Expr) syntax.Stmt { callPanicExpr := &syntax.CallExpr{ Fun: runtimeSym(r.info, "panicrangestate"), ArgList: []syntax.Expr{arg}, } setValueType(callPanicExpr, nil) // no result type return &syntax.ExprStmt{X: callPanicExpr} } // next returns a reference to the #next variable. func (r *rewriter) next() *syntax.Name { if r.nextVar == nil { r.nextVar = r.declOuterVar("#next", r.int.Type(), nil) } return r.useObj(r.nextVar) } // forRangeFunc checks whether n is a range-over-func. // If so, it returns n.(*syntax.ForStmt), true. // Otherwise it returns nil, false. func forRangeFunc(n syntax.Node) (*syntax.ForStmt, bool) { nfor, ok := n.(*syntax.ForStmt) if !ok { return nil, false } nrange, ok := nfor.Init.(*syntax.RangeClause) if !ok { return nil, false } _, ok = types2.CoreType(nrange.X.GetTypeInfo().Type).(*types2.Signature) if !ok { return nil, false } return nfor, true } // intConst returns syntax for an integer literal with the given value. func (r *rewriter) intConst(c int) *syntax.BasicLit { lit := &syntax.BasicLit{ Value: fmt.Sprint(c), Kind: syntax.IntLit, } tv := syntax.TypeAndValue{Type: r.int.Type(), Value: constant.MakeInt64(int64(c))} tv.SetIsValue() lit.SetTypeInfo(tv) return lit } func (r *rewriter) stateConst(s abi.RF_State) *syntax.BasicLit { return r.intConst(int(s)) } // useObj returns syntax for a reference to decl, which should be its declaration. func (r *rewriter) useObj(obj types2.Object) *syntax.Name { n := syntax.NewName(nopos, obj.Name()) tv := syntax.TypeAndValue{Type: obj.Type()} tv.SetIsValue() n.SetTypeInfo(tv) r.info.Uses[n] = obj return n } // useList is useVar for a list of decls. func (r *rewriter) useList(vars []types2.Object) syntax.Expr { var new []syntax.Expr for _, obj := range vars { new = append(new, r.useObj(obj)) } if len(new) == 1 { return new[0] } return &syntax.ListExpr{ElemList: new} } func (r *rewriter) makeVarName(pos syntax.Pos, name string, typ types2.Type) (*types2.Var, *syntax.Name) { obj := types2.NewVar(pos, r.pkg, name, typ) n := syntax.NewName(pos, name) tv := syntax.TypeAndValue{Type: typ} tv.SetIsValue() n.SetTypeInfo(tv) r.info.Defs[n] = obj return obj, n } func (r *rewriter) generateParamName(results []*syntax.Field, i int) { obj, n := r.sig.RenameResult(results, i) r.info.Defs[n] = obj } // declOuterVar declares a variable with a given name, type, and initializer value, // in the same scope as the outermost loop in a loop nest. func (r *rewriter) declOuterVar(name string, typ types2.Type, init syntax.Expr) *types2.Var { if r.declStmt == nil { r.declStmt = &syntax.DeclStmt{} } stmt := r.declStmt obj, n := r.makeVarName(stmt.Pos(), name, typ) stmt.DeclList = append(stmt.DeclList, &syntax.VarDecl{ NameList: []*syntax.Name{n}, // Note: Type is ignored Values: init, }) return obj } // declSingleVar declares a variable with a given name, type, and initializer value, // and returns both the declaration and variable, so that the declaration can be placed // in a specific scope. func (r *rewriter) declSingleVar(name string, typ types2.Type, init syntax.Expr) (*syntax.DeclStmt, *types2.Var) { stmt := &syntax.DeclStmt{} obj, n := r.makeVarName(stmt.Pos(), name, typ) stmt.DeclList = append(stmt.DeclList, &syntax.VarDecl{ NameList: []*syntax.Name{n}, // Note: Type is ignored Values: init, }) return stmt, obj } // runtimePkg is a fake runtime package that contains what we need to refer to in package runtime. var runtimePkg = func() *types2.Package { var nopos syntax.Pos pkg := types2.NewPackage("runtime", "runtime") anyType := types2.Universe.Lookup("any").Type() intType := types2.Universe.Lookup("int").Type() // func deferrangefunc() unsafe.Pointer obj := types2.NewFunc(nopos, pkg, "deferrangefunc", types2.NewSignatureType(nil, nil, nil, nil, types2.NewTuple(types2.NewParam(nopos, pkg, "extra", anyType)), false)) pkg.Scope().Insert(obj) // func panicrangestate() obj = types2.NewFunc(nopos, pkg, "panicrangestate", types2.NewSignatureType(nil, nil, nil, types2.NewTuple(types2.NewParam(nopos, pkg, "state", intType)), nil, false)) pkg.Scope().Insert(obj) return pkg }() // runtimeSym returns a reference to a symbol in the fake runtime package. func runtimeSym(info *types2.Info, name string) *syntax.Name { obj := runtimePkg.Scope().Lookup(name) n := syntax.NewName(nopos, "runtime."+name) tv := syntax.TypeAndValue{Type: obj.Type()} tv.SetIsValue() tv.SetIsRuntimeHelper() n.SetTypeInfo(tv) info.Uses[n] = obj return n } // setPos walks the top structure of x that has no position assigned // and assigns it all to have position pos. // When setPos encounters a syntax node with a position assigned, // setPos does not look inside that node. // setPos only needs to handle syntax we create in this package; // all other syntax should have positions assigned already. func setPos(x syntax.Node, pos syntax.Pos) { if x == nil { return } syntax.Inspect(x, func(n syntax.Node) bool { if n == nil || n.Pos() != nopos { return false } n.SetPos(pos) switch n := n.(type) { case *syntax.BlockStmt: if n.Rbrace == nopos { n.Rbrace = pos } } return true }) }
go/src/cmd/compile/internal/rangefunc/rewrite.go/0
{ "file_path": "go/src/cmd/compile/internal/rangefunc/rewrite.go", "repo_id": "go", "token_count": 17148 }
96
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import "strings" // Notes: // - Integer types live in the low portion of registers. Upper portions are junk. // - Boolean types use the low-order byte of a register. 0=false, 1=true. // Upper bytes are junk. // - Floating-point types live in the low natural slot of an sse2 register. // Unused portions are junk. // - We do not use AH,BH,CH,DH registers. // - When doing sub-register operations, we try to write the whole // destination register to avoid a partial-register write. // - Unused portions of AuxInt (or the Val portion of ValAndOff) are // filled by sign-extending the used portion. Users of AuxInt which interpret // AuxInt as unsigned (e.g. shifts) must be careful. // Suffixes encode the bit width of various instructions. // L (long word) = 32 bit // W (word) = 16 bit // B (byte) = 8 bit // copied from ../../x86/reg.go var regNames386 = []string{ "AX", "CX", "DX", "BX", "SP", "BP", "SI", "DI", "X0", "X1", "X2", "X3", "X4", "X5", "X6", "X7", // If you add registers, update asyncPreempt in runtime // pseudo-registers "SB", } func init() { // Make map from reg names to reg integers. if len(regNames386) > 64 { panic("too many registers") } num := map[string]int{} for i, name := range regNames386 { num[name] = i } buildReg := func(s string) regMask { m := regMask(0) for _, r := range strings.Split(s, " ") { if n, ok := num[r]; ok { m |= regMask(1) << uint(n) continue } panic("register " + r + " not found") } return m } // Common individual register masks var ( ax = buildReg("AX") cx = buildReg("CX") dx = buildReg("DX") bx = buildReg("BX") si = buildReg("SI") gp = buildReg("AX CX DX BX BP SI DI") fp = buildReg("X0 X1 X2 X3 X4 X5 X6 X7") gpsp = gp | buildReg("SP") gpspsb = gpsp | buildReg("SB") callerSave = gp | fp ) // Common slices of register masks var ( gponly = []regMask{gp} fponly = []regMask{fp} ) // Common regInfo var ( gp01 = regInfo{inputs: nil, outputs: gponly} gp11 = regInfo{inputs: []regMask{gp}, outputs: gponly} gp11sp = regInfo{inputs: []regMask{gpsp}, outputs: gponly} gp11sb = regInfo{inputs: []regMask{gpspsb}, outputs: gponly} gp21 = regInfo{inputs: []regMask{gp, gp}, outputs: gponly} gp11carry = regInfo{inputs: []regMask{gp}, outputs: []regMask{gp, 0}} gp21carry = regInfo{inputs: []regMask{gp, gp}, outputs: []regMask{gp, 0}} gp1carry1 = regInfo{inputs: []regMask{gp}, outputs: gponly} gp2carry1 = regInfo{inputs: []regMask{gp, gp}, outputs: gponly} gp21sp = regInfo{inputs: []regMask{gpsp, gp}, outputs: gponly} gp21sb = regInfo{inputs: []regMask{gpspsb, gpsp}, outputs: gponly} gp21shift = regInfo{inputs: []regMask{gp, cx}, outputs: []regMask{gp}} gp11div = regInfo{inputs: []regMask{ax, gpsp &^ dx}, outputs: []regMask{ax}, clobbers: dx} gp21hmul = regInfo{inputs: []regMask{ax, gpsp}, outputs: []regMask{dx}, clobbers: ax} gp11mod = regInfo{inputs: []regMask{ax, gpsp &^ dx}, outputs: []regMask{dx}, clobbers: ax} gp21mul = regInfo{inputs: []regMask{ax, gpsp}, outputs: []regMask{dx, ax}} gp2flags = regInfo{inputs: []regMask{gpsp, gpsp}} gp1flags = regInfo{inputs: []regMask{gpsp}} gp0flagsLoad = regInfo{inputs: []regMask{gpspsb, 0}} gp1flagsLoad = regInfo{inputs: []regMask{gpspsb, gpsp, 0}} flagsgp = regInfo{inputs: nil, outputs: gponly} readflags = regInfo{inputs: nil, outputs: gponly} flagsgpax = regInfo{inputs: nil, clobbers: ax, outputs: []regMask{gp &^ ax}} gpload = regInfo{inputs: []regMask{gpspsb, 0}, outputs: gponly} gp21load = regInfo{inputs: []regMask{gp, gpspsb, 0}, outputs: gponly} gploadidx = regInfo{inputs: []regMask{gpspsb, gpsp, 0}, outputs: gponly} gp21loadidx = regInfo{inputs: []regMask{gp, gpspsb, gpsp, 0}, outputs: gponly} gpstore = regInfo{inputs: []regMask{gpspsb, gpsp, 0}} gpstoreconst = regInfo{inputs: []regMask{gpspsb, 0}} gpstoreidx = regInfo{inputs: []regMask{gpspsb, gpsp, gpsp, 0}} gpstoreconstidx = regInfo{inputs: []regMask{gpspsb, gpsp, 0}} fp01 = regInfo{inputs: nil, outputs: fponly} fp21 = regInfo{inputs: []regMask{fp, fp}, outputs: fponly} fp21load = regInfo{inputs: []regMask{fp, gpspsb, 0}, outputs: fponly} fpgp = regInfo{inputs: fponly, outputs: gponly} gpfp = regInfo{inputs: gponly, outputs: fponly} fp11 = regInfo{inputs: fponly, outputs: fponly} fp2flags = regInfo{inputs: []regMask{fp, fp}} fpload = regInfo{inputs: []regMask{gpspsb, 0}, outputs: fponly} fploadidx = regInfo{inputs: []regMask{gpspsb, gpsp, 0}, outputs: fponly} fpstore = regInfo{inputs: []regMask{gpspsb, fp, 0}} fpstoreidx = regInfo{inputs: []regMask{gpspsb, gpsp, fp, 0}} ) var _386ops = []opData{ // fp ops {name: "ADDSS", argLength: 2, reg: fp21, asm: "ADDSS", commutative: true, resultInArg0: true}, // fp32 add {name: "ADDSD", argLength: 2, reg: fp21, asm: "ADDSD", commutative: true, resultInArg0: true}, // fp64 add {name: "SUBSS", argLength: 2, reg: fp21, asm: "SUBSS", resultInArg0: true}, // fp32 sub {name: "SUBSD", argLength: 2, reg: fp21, asm: "SUBSD", resultInArg0: true}, // fp64 sub {name: "MULSS", argLength: 2, reg: fp21, asm: "MULSS", commutative: true, resultInArg0: true}, // fp32 mul {name: "MULSD", argLength: 2, reg: fp21, asm: "MULSD", commutative: true, resultInArg0: true}, // fp64 mul {name: "DIVSS", argLength: 2, reg: fp21, asm: "DIVSS", resultInArg0: true}, // fp32 div {name: "DIVSD", argLength: 2, reg: fp21, asm: "DIVSD", resultInArg0: true}, // fp64 div {name: "MOVSSload", argLength: 2, reg: fpload, asm: "MOVSS", aux: "SymOff", faultOnNilArg0: true, symEffect: "Read"}, // fp32 load {name: "MOVSDload", argLength: 2, reg: fpload, asm: "MOVSD", aux: "SymOff", faultOnNilArg0: true, symEffect: "Read"}, // fp64 load {name: "MOVSSconst", reg: fp01, asm: "MOVSS", aux: "Float32", rematerializeable: true}, // fp32 constant {name: "MOVSDconst", reg: fp01, asm: "MOVSD", aux: "Float64", rematerializeable: true}, // fp64 constant {name: "MOVSSloadidx1", argLength: 3, reg: fploadidx, asm: "MOVSS", aux: "SymOff", symEffect: "Read"}, // fp32 load indexed by i {name: "MOVSSloadidx4", argLength: 3, reg: fploadidx, asm: "MOVSS", aux: "SymOff", symEffect: "Read"}, // fp32 load indexed by 4*i {name: "MOVSDloadidx1", argLength: 3, reg: fploadidx, asm: "MOVSD", aux: "SymOff", symEffect: "Read"}, // fp64 load indexed by i {name: "MOVSDloadidx8", argLength: 3, reg: fploadidx, asm: "MOVSD", aux: "SymOff", symEffect: "Read"}, // fp64 load indexed by 8*i {name: "MOVSSstore", argLength: 3, reg: fpstore, asm: "MOVSS", aux: "SymOff", faultOnNilArg0: true, symEffect: "Write"}, // fp32 store {name: "MOVSDstore", argLength: 3, reg: fpstore, asm: "MOVSD", aux: "SymOff", faultOnNilArg0: true, symEffect: "Write"}, // fp64 store {name: "MOVSSstoreidx1", argLength: 4, reg: fpstoreidx, asm: "MOVSS", aux: "SymOff", symEffect: "Write"}, // fp32 indexed by i store {name: "MOVSSstoreidx4", argLength: 4, reg: fpstoreidx, asm: "MOVSS", aux: "SymOff", symEffect: "Write"}, // fp32 indexed by 4i store {name: "MOVSDstoreidx1", argLength: 4, reg: fpstoreidx, asm: "MOVSD", aux: "SymOff", symEffect: "Write"}, // fp64 indexed by i store {name: "MOVSDstoreidx8", argLength: 4, reg: fpstoreidx, asm: "MOVSD", aux: "SymOff", symEffect: "Write"}, // fp64 indexed by 8i store {name: "ADDSSload", argLength: 3, reg: fp21load, asm: "ADDSS", aux: "SymOff", resultInArg0: true, faultOnNilArg1: true, symEffect: "Read"}, // fp32 arg0 + tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "ADDSDload", argLength: 3, reg: fp21load, asm: "ADDSD", aux: "SymOff", resultInArg0: true, faultOnNilArg1: true, symEffect: "Read"}, // fp64 arg0 + tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "SUBSSload", argLength: 3, reg: fp21load, asm: "SUBSS", aux: "SymOff", resultInArg0: true, faultOnNilArg1: true, symEffect: "Read"}, // fp32 arg0 - tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "SUBSDload", argLength: 3, reg: fp21load, asm: "SUBSD", aux: "SymOff", resultInArg0: true, faultOnNilArg1: true, symEffect: "Read"}, // fp64 arg0 - tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "MULSSload", argLength: 3, reg: fp21load, asm: "MULSS", aux: "SymOff", resultInArg0: true, faultOnNilArg1: true, symEffect: "Read"}, // fp32 arg0 * tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "MULSDload", argLength: 3, reg: fp21load, asm: "MULSD", aux: "SymOff", resultInArg0: true, faultOnNilArg1: true, symEffect: "Read"}, // fp64 arg0 * tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "DIVSSload", argLength: 3, reg: fp21load, asm: "DIVSS", aux: "SymOff", resultInArg0: true, faultOnNilArg1: true, symEffect: "Read"}, // fp32 arg0 / tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "DIVSDload", argLength: 3, reg: fp21load, asm: "DIVSD", aux: "SymOff", resultInArg0: true, faultOnNilArg1: true, symEffect: "Read"}, // fp64 arg0 / tmp, tmp loaded from arg1+auxint+aux, arg2 = mem // binary ops {name: "ADDL", argLength: 2, reg: gp21sp, asm: "ADDL", commutative: true, clobberFlags: true}, // arg0 + arg1 {name: "ADDLconst", argLength: 1, reg: gp11sp, asm: "ADDL", aux: "Int32", typ: "UInt32", clobberFlags: true}, // arg0 + auxint {name: "ADDLcarry", argLength: 2, reg: gp21carry, asm: "ADDL", commutative: true, resultInArg0: true}, // arg0 + arg1, generates <carry,result> pair {name: "ADDLconstcarry", argLength: 1, reg: gp11carry, asm: "ADDL", aux: "Int32", resultInArg0: true}, // arg0 + auxint, generates <carry,result> pair {name: "ADCL", argLength: 3, reg: gp2carry1, asm: "ADCL", commutative: true, resultInArg0: true, clobberFlags: true}, // arg0+arg1+carry(arg2), where arg2 is flags {name: "ADCLconst", argLength: 2, reg: gp1carry1, asm: "ADCL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // arg0+auxint+carry(arg1), where arg1 is flags {name: "SUBL", argLength: 2, reg: gp21, asm: "SUBL", resultInArg0: true, clobberFlags: true}, // arg0 - arg1 {name: "SUBLconst", argLength: 1, reg: gp11, asm: "SUBL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // arg0 - auxint {name: "SUBLcarry", argLength: 2, reg: gp21carry, asm: "SUBL", resultInArg0: true}, // arg0-arg1, generates <borrow,result> pair {name: "SUBLconstcarry", argLength: 1, reg: gp11carry, asm: "SUBL", aux: "Int32", resultInArg0: true}, // arg0-auxint, generates <borrow,result> pair {name: "SBBL", argLength: 3, reg: gp2carry1, asm: "SBBL", resultInArg0: true, clobberFlags: true}, // arg0-arg1-borrow(arg2), where arg2 is flags {name: "SBBLconst", argLength: 2, reg: gp1carry1, asm: "SBBL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // arg0-auxint-borrow(arg1), where arg1 is flags {name: "MULL", argLength: 2, reg: gp21, asm: "IMULL", commutative: true, resultInArg0: true, clobberFlags: true}, // arg0 * arg1 {name: "MULLconst", argLength: 1, reg: gp11, asm: "IMUL3L", aux: "Int32", clobberFlags: true}, // arg0 * auxint {name: "MULLU", argLength: 2, reg: regInfo{inputs: []regMask{ax, gpsp}, outputs: []regMask{ax, 0}, clobbers: dx}, typ: "(UInt32,Flags)", asm: "MULL", commutative: true, clobberFlags: true}, // Let x = arg0*arg1 (full 32x32->64 unsigned multiply). Returns uint32(x), and flags set to overflow if uint32(x) != x. {name: "HMULL", argLength: 2, reg: gp21hmul, commutative: true, asm: "IMULL", clobberFlags: true}, // (arg0 * arg1) >> width {name: "HMULLU", argLength: 2, reg: gp21hmul, commutative: true, asm: "MULL", clobberFlags: true}, // (arg0 * arg1) >> width {name: "MULLQU", argLength: 2, reg: gp21mul, commutative: true, asm: "MULL", clobberFlags: true}, // arg0 * arg1, high 32 in result[0], low 32 in result[1] {name: "AVGLU", argLength: 2, reg: gp21, commutative: true, resultInArg0: true, clobberFlags: true}, // (arg0 + arg1) / 2 as unsigned, all 32 result bits // For DIVL, DIVW, MODL and MODW, AuxInt non-zero means that the divisor has been proved to be not -1. {name: "DIVL", argLength: 2, reg: gp11div, asm: "IDIVL", aux: "Bool", clobberFlags: true}, // arg0 / arg1 {name: "DIVW", argLength: 2, reg: gp11div, asm: "IDIVW", aux: "Bool", clobberFlags: true}, // arg0 / arg1 {name: "DIVLU", argLength: 2, reg: gp11div, asm: "DIVL", clobberFlags: true}, // arg0 / arg1 {name: "DIVWU", argLength: 2, reg: gp11div, asm: "DIVW", clobberFlags: true}, // arg0 / arg1 {name: "MODL", argLength: 2, reg: gp11mod, asm: "IDIVL", aux: "Bool", clobberFlags: true}, // arg0 % arg1 {name: "MODW", argLength: 2, reg: gp11mod, asm: "IDIVW", aux: "Bool", clobberFlags: true}, // arg0 % arg1 {name: "MODLU", argLength: 2, reg: gp11mod, asm: "DIVL", clobberFlags: true}, // arg0 % arg1 {name: "MODWU", argLength: 2, reg: gp11mod, asm: "DIVW", clobberFlags: true}, // arg0 % arg1 {name: "ANDL", argLength: 2, reg: gp21, asm: "ANDL", commutative: true, resultInArg0: true, clobberFlags: true}, // arg0 & arg1 {name: "ANDLconst", argLength: 1, reg: gp11, asm: "ANDL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // arg0 & auxint {name: "ORL", argLength: 2, reg: gp21, asm: "ORL", commutative: true, resultInArg0: true, clobberFlags: true}, // arg0 | arg1 {name: "ORLconst", argLength: 1, reg: gp11, asm: "ORL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // arg0 | auxint {name: "XORL", argLength: 2, reg: gp21, asm: "XORL", commutative: true, resultInArg0: true, clobberFlags: true}, // arg0 ^ arg1 {name: "XORLconst", argLength: 1, reg: gp11, asm: "XORL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // arg0 ^ auxint {name: "CMPL", argLength: 2, reg: gp2flags, asm: "CMPL", typ: "Flags"}, // arg0 compare to arg1 {name: "CMPW", argLength: 2, reg: gp2flags, asm: "CMPW", typ: "Flags"}, // arg0 compare to arg1 {name: "CMPB", argLength: 2, reg: gp2flags, asm: "CMPB", typ: "Flags"}, // arg0 compare to arg1 {name: "CMPLconst", argLength: 1, reg: gp1flags, asm: "CMPL", typ: "Flags", aux: "Int32"}, // arg0 compare to auxint {name: "CMPWconst", argLength: 1, reg: gp1flags, asm: "CMPW", typ: "Flags", aux: "Int16"}, // arg0 compare to auxint {name: "CMPBconst", argLength: 1, reg: gp1flags, asm: "CMPB", typ: "Flags", aux: "Int8"}, // arg0 compare to auxint // compare *(arg0+auxint+aux) to arg1 (in that order). arg2=mem. {name: "CMPLload", argLength: 3, reg: gp1flagsLoad, asm: "CMPL", aux: "SymOff", typ: "Flags", symEffect: "Read", faultOnNilArg0: true}, {name: "CMPWload", argLength: 3, reg: gp1flagsLoad, asm: "CMPW", aux: "SymOff", typ: "Flags", symEffect: "Read", faultOnNilArg0: true}, {name: "CMPBload", argLength: 3, reg: gp1flagsLoad, asm: "CMPB", aux: "SymOff", typ: "Flags", symEffect: "Read", faultOnNilArg0: true}, // compare *(arg0+ValAndOff(AuxInt).Off()+aux) to ValAndOff(AuxInt).Val() (in that order). arg1=mem. {name: "CMPLconstload", argLength: 2, reg: gp0flagsLoad, asm: "CMPL", aux: "SymValAndOff", typ: "Flags", symEffect: "Read", faultOnNilArg0: true}, {name: "CMPWconstload", argLength: 2, reg: gp0flagsLoad, asm: "CMPW", aux: "SymValAndOff", typ: "Flags", symEffect: "Read", faultOnNilArg0: true}, {name: "CMPBconstload", argLength: 2, reg: gp0flagsLoad, asm: "CMPB", aux: "SymValAndOff", typ: "Flags", symEffect: "Read", faultOnNilArg0: true}, {name: "UCOMISS", argLength: 2, reg: fp2flags, asm: "UCOMISS", typ: "Flags"}, // arg0 compare to arg1, f32 {name: "UCOMISD", argLength: 2, reg: fp2flags, asm: "UCOMISD", typ: "Flags"}, // arg0 compare to arg1, f64 {name: "TESTL", argLength: 2, reg: gp2flags, commutative: true, asm: "TESTL", typ: "Flags"}, // (arg0 & arg1) compare to 0 {name: "TESTW", argLength: 2, reg: gp2flags, commutative: true, asm: "TESTW", typ: "Flags"}, // (arg0 & arg1) compare to 0 {name: "TESTB", argLength: 2, reg: gp2flags, commutative: true, asm: "TESTB", typ: "Flags"}, // (arg0 & arg1) compare to 0 {name: "TESTLconst", argLength: 1, reg: gp1flags, asm: "TESTL", typ: "Flags", aux: "Int32"}, // (arg0 & auxint) compare to 0 {name: "TESTWconst", argLength: 1, reg: gp1flags, asm: "TESTW", typ: "Flags", aux: "Int16"}, // (arg0 & auxint) compare to 0 {name: "TESTBconst", argLength: 1, reg: gp1flags, asm: "TESTB", typ: "Flags", aux: "Int8"}, // (arg0 & auxint) compare to 0 {name: "SHLL", argLength: 2, reg: gp21shift, asm: "SHLL", resultInArg0: true, clobberFlags: true}, // arg0 << arg1, shift amount is mod 32 {name: "SHLLconst", argLength: 1, reg: gp11, asm: "SHLL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // arg0 << auxint, shift amount 0-31 // Note: x86 is weird, the 16 and 8 byte shifts still use all 5 bits of shift amount! {name: "SHRL", argLength: 2, reg: gp21shift, asm: "SHRL", resultInArg0: true, clobberFlags: true}, // unsigned arg0 >> arg1, shift amount is mod 32 {name: "SHRW", argLength: 2, reg: gp21shift, asm: "SHRW", resultInArg0: true, clobberFlags: true}, // unsigned arg0 >> arg1, shift amount is mod 32 {name: "SHRB", argLength: 2, reg: gp21shift, asm: "SHRB", resultInArg0: true, clobberFlags: true}, // unsigned arg0 >> arg1, shift amount is mod 32 {name: "SHRLconst", argLength: 1, reg: gp11, asm: "SHRL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // unsigned arg0 >> auxint, shift amount 0-31 {name: "SHRWconst", argLength: 1, reg: gp11, asm: "SHRW", aux: "Int16", resultInArg0: true, clobberFlags: true}, // unsigned arg0 >> auxint, shift amount 0-15 {name: "SHRBconst", argLength: 1, reg: gp11, asm: "SHRB", aux: "Int8", resultInArg0: true, clobberFlags: true}, // unsigned arg0 >> auxint, shift amount 0-7 {name: "SARL", argLength: 2, reg: gp21shift, asm: "SARL", resultInArg0: true, clobberFlags: true}, // signed arg0 >> arg1, shift amount is mod 32 {name: "SARW", argLength: 2, reg: gp21shift, asm: "SARW", resultInArg0: true, clobberFlags: true}, // signed arg0 >> arg1, shift amount is mod 32 {name: "SARB", argLength: 2, reg: gp21shift, asm: "SARB", resultInArg0: true, clobberFlags: true}, // signed arg0 >> arg1, shift amount is mod 32 {name: "SARLconst", argLength: 1, reg: gp11, asm: "SARL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // signed arg0 >> auxint, shift amount 0-31 {name: "SARWconst", argLength: 1, reg: gp11, asm: "SARW", aux: "Int16", resultInArg0: true, clobberFlags: true}, // signed arg0 >> auxint, shift amount 0-15 {name: "SARBconst", argLength: 1, reg: gp11, asm: "SARB", aux: "Int8", resultInArg0: true, clobberFlags: true}, // signed arg0 >> auxint, shift amount 0-7 {name: "ROLL", argLength: 2, reg: gp21shift, asm: "ROLL", resultInArg0: true, clobberFlags: true}, // 32 bits of arg0 rotate left by arg1 {name: "ROLW", argLength: 2, reg: gp21shift, asm: "ROLW", resultInArg0: true, clobberFlags: true}, // low 16 bits of arg0 rotate left by arg1 {name: "ROLB", argLength: 2, reg: gp21shift, asm: "ROLB", resultInArg0: true, clobberFlags: true}, // low 8 bits of arg0 rotate left by arg1 {name: "ROLLconst", argLength: 1, reg: gp11, asm: "ROLL", aux: "Int32", resultInArg0: true, clobberFlags: true}, // arg0 rotate left auxint, rotate amount 0-31 {name: "ROLWconst", argLength: 1, reg: gp11, asm: "ROLW", aux: "Int16", resultInArg0: true, clobberFlags: true}, // arg0 rotate left auxint, rotate amount 0-15 {name: "ROLBconst", argLength: 1, reg: gp11, asm: "ROLB", aux: "Int8", resultInArg0: true, clobberFlags: true}, // arg0 rotate left auxint, rotate amount 0-7 // binary-op with a memory source operand {name: "ADDLload", argLength: 3, reg: gp21load, asm: "ADDL", aux: "SymOff", resultInArg0: true, clobberFlags: true, faultOnNilArg1: true, symEffect: "Read"}, // arg0 + tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "SUBLload", argLength: 3, reg: gp21load, asm: "SUBL", aux: "SymOff", resultInArg0: true, clobberFlags: true, faultOnNilArg1: true, symEffect: "Read"}, // arg0 - tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "MULLload", argLength: 3, reg: gp21load, asm: "IMULL", aux: "SymOff", resultInArg0: true, clobberFlags: true, faultOnNilArg1: true, symEffect: "Read"}, // arg0 * tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "ANDLload", argLength: 3, reg: gp21load, asm: "ANDL", aux: "SymOff", resultInArg0: true, clobberFlags: true, faultOnNilArg1: true, symEffect: "Read"}, // arg0 & tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "ORLload", argLength: 3, reg: gp21load, asm: "ORL", aux: "SymOff", resultInArg0: true, clobberFlags: true, faultOnNilArg1: true, symEffect: "Read"}, // arg0 | tmp, tmp loaded from arg1+auxint+aux, arg2 = mem {name: "XORLload", argLength: 3, reg: gp21load, asm: "XORL", aux: "SymOff", resultInArg0: true, clobberFlags: true, faultOnNilArg1: true, symEffect: "Read"}, // arg0 ^ tmp, tmp loaded from arg1+auxint+aux, arg2 = mem // binary-op with an indexed memory source operand {name: "ADDLloadidx4", argLength: 4, reg: gp21loadidx, asm: "ADDL", aux: "SymOff", resultInArg0: true, clobberFlags: true, symEffect: "Read"}, // arg0 + tmp, tmp loaded from arg1+arg2*4+auxint+aux, arg3 = mem {name: "SUBLloadidx4", argLength: 4, reg: gp21loadidx, asm: "SUBL", aux: "SymOff", resultInArg0: true, clobberFlags: true, symEffect: "Read"}, // arg0 - tmp, tmp loaded from arg1+arg2*4+auxint+aux, arg3 = mem {name: "MULLloadidx4", argLength: 4, reg: gp21loadidx, asm: "IMULL", aux: "SymOff", resultInArg0: true, clobberFlags: true, symEffect: "Read"}, // arg0 * tmp, tmp loaded from arg1+arg2*4+auxint+aux, arg3 = mem {name: "ANDLloadidx4", argLength: 4, reg: gp21loadidx, asm: "ANDL", aux: "SymOff", resultInArg0: true, clobberFlags: true, symEffect: "Read"}, // arg0 & tmp, tmp loaded from arg1+arg2*4+auxint+aux, arg3 = mem {name: "ORLloadidx4", argLength: 4, reg: gp21loadidx, asm: "ORL", aux: "SymOff", resultInArg0: true, clobberFlags: true, symEffect: "Read"}, // arg0 | tmp, tmp loaded from arg1+arg2*4+auxint+aux, arg3 = mem {name: "XORLloadidx4", argLength: 4, reg: gp21loadidx, asm: "XORL", aux: "SymOff", resultInArg0: true, clobberFlags: true, symEffect: "Read"}, // arg0 ^ tmp, tmp loaded from arg1+arg2*4+auxint+aux, arg3 = mem // unary ops {name: "NEGL", argLength: 1, reg: gp11, asm: "NEGL", resultInArg0: true, clobberFlags: true}, // -arg0 {name: "NOTL", argLength: 1, reg: gp11, asm: "NOTL", resultInArg0: true}, // ^arg0 {name: "BSFL", argLength: 1, reg: gp11, asm: "BSFL", clobberFlags: true}, // arg0 # of low-order zeroes ; undef if zero {name: "BSFW", argLength: 1, reg: gp11, asm: "BSFW", clobberFlags: true}, // arg0 # of low-order zeroes ; undef if zero {name: "LoweredCtz32", argLength: 1, reg: gp11, clobberFlags: true}, // arg0 # of low-order zeroes {name: "BSRL", argLength: 1, reg: gp11, asm: "BSRL", clobberFlags: true}, // arg0 # of high-order zeroes ; undef if zero {name: "BSRW", argLength: 1, reg: gp11, asm: "BSRW", clobberFlags: true}, // arg0 # of high-order zeroes ; undef if zero {name: "BSWAPL", argLength: 1, reg: gp11, asm: "BSWAPL", resultInArg0: true}, // arg0 swap bytes {name: "SQRTSD", argLength: 1, reg: fp11, asm: "SQRTSD"}, // sqrt(arg0) {name: "SQRTSS", argLength: 1, reg: fp11, asm: "SQRTSS"}, // sqrt(arg0), float32 {name: "SBBLcarrymask", argLength: 1, reg: flagsgp, asm: "SBBL"}, // (int32)(-1) if carry is set, 0 if carry is clear. // Note: SBBW and SBBB are subsumed by SBBL {name: "SETEQ", argLength: 1, reg: readflags, asm: "SETEQ"}, // extract == condition from arg0 {name: "SETNE", argLength: 1, reg: readflags, asm: "SETNE"}, // extract != condition from arg0 {name: "SETL", argLength: 1, reg: readflags, asm: "SETLT"}, // extract signed < condition from arg0 {name: "SETLE", argLength: 1, reg: readflags, asm: "SETLE"}, // extract signed <= condition from arg0 {name: "SETG", argLength: 1, reg: readflags, asm: "SETGT"}, // extract signed > condition from arg0 {name: "SETGE", argLength: 1, reg: readflags, asm: "SETGE"}, // extract signed >= condition from arg0 {name: "SETB", argLength: 1, reg: readflags, asm: "SETCS"}, // extract unsigned < condition from arg0 {name: "SETBE", argLength: 1, reg: readflags, asm: "SETLS"}, // extract unsigned <= condition from arg0 {name: "SETA", argLength: 1, reg: readflags, asm: "SETHI"}, // extract unsigned > condition from arg0 {name: "SETAE", argLength: 1, reg: readflags, asm: "SETCC"}, // extract unsigned >= condition from arg0 {name: "SETO", argLength: 1, reg: readflags, asm: "SETOS"}, // extract if overflow flag is set from arg0 // Need different opcodes for floating point conditions because // any comparison involving a NaN is always FALSE and thus // the patterns for inverting conditions cannot be used. {name: "SETEQF", argLength: 1, reg: flagsgpax, asm: "SETEQ", clobberFlags: true}, // extract == condition from arg0 {name: "SETNEF", argLength: 1, reg: flagsgpax, asm: "SETNE", clobberFlags: true}, // extract != condition from arg0 {name: "SETORD", argLength: 1, reg: flagsgp, asm: "SETPC"}, // extract "ordered" (No Nan present) condition from arg0 {name: "SETNAN", argLength: 1, reg: flagsgp, asm: "SETPS"}, // extract "unordered" (Nan present) condition from arg0 {name: "SETGF", argLength: 1, reg: flagsgp, asm: "SETHI"}, // extract floating > condition from arg0 {name: "SETGEF", argLength: 1, reg: flagsgp, asm: "SETCC"}, // extract floating >= condition from arg0 {name: "MOVBLSX", argLength: 1, reg: gp11, asm: "MOVBLSX"}, // sign extend arg0 from int8 to int32 {name: "MOVBLZX", argLength: 1, reg: gp11, asm: "MOVBLZX"}, // zero extend arg0 from int8 to int32 {name: "MOVWLSX", argLength: 1, reg: gp11, asm: "MOVWLSX"}, // sign extend arg0 from int16 to int32 {name: "MOVWLZX", argLength: 1, reg: gp11, asm: "MOVWLZX"}, // zero extend arg0 from int16 to int32 {name: "MOVLconst", reg: gp01, asm: "MOVL", typ: "UInt32", aux: "Int32", rematerializeable: true}, // 32 low bits of auxint {name: "CVTTSD2SL", argLength: 1, reg: fpgp, asm: "CVTTSD2SL"}, // convert float64 to int32 {name: "CVTTSS2SL", argLength: 1, reg: fpgp, asm: "CVTTSS2SL"}, // convert float32 to int32 {name: "CVTSL2SS", argLength: 1, reg: gpfp, asm: "CVTSL2SS"}, // convert int32 to float32 {name: "CVTSL2SD", argLength: 1, reg: gpfp, asm: "CVTSL2SD"}, // convert int32 to float64 {name: "CVTSD2SS", argLength: 1, reg: fp11, asm: "CVTSD2SS"}, // convert float64 to float32 {name: "CVTSS2SD", argLength: 1, reg: fp11, asm: "CVTSS2SD"}, // convert float32 to float64 {name: "PXOR", argLength: 2, reg: fp21, asm: "PXOR", commutative: true, resultInArg0: true}, // exclusive or, applied to X regs for float negation. {name: "LEAL", argLength: 1, reg: gp11sb, aux: "SymOff", rematerializeable: true, symEffect: "Addr"}, // arg0 + auxint + offset encoded in aux {name: "LEAL1", argLength: 2, reg: gp21sb, commutative: true, aux: "SymOff", symEffect: "Addr"}, // arg0 + arg1 + auxint + aux {name: "LEAL2", argLength: 2, reg: gp21sb, aux: "SymOff", symEffect: "Addr"}, // arg0 + 2*arg1 + auxint + aux {name: "LEAL4", argLength: 2, reg: gp21sb, aux: "SymOff", symEffect: "Addr"}, // arg0 + 4*arg1 + auxint + aux {name: "LEAL8", argLength: 2, reg: gp21sb, aux: "SymOff", symEffect: "Addr"}, // arg0 + 8*arg1 + auxint + aux // Note: LEAL{1,2,4,8} must not have OpSB as either argument. // auxint+aux == add auxint and the offset of the symbol in aux (if any) to the effective address {name: "MOVBload", argLength: 2, reg: gpload, asm: "MOVBLZX", aux: "SymOff", typ: "UInt8", faultOnNilArg0: true, symEffect: "Read"}, // load byte from arg0+auxint+aux. arg1=mem. Zero extend. {name: "MOVBLSXload", argLength: 2, reg: gpload, asm: "MOVBLSX", aux: "SymOff", faultOnNilArg0: true, symEffect: "Read"}, // ditto, sign extend to int32 {name: "MOVWload", argLength: 2, reg: gpload, asm: "MOVWLZX", aux: "SymOff", typ: "UInt16", faultOnNilArg0: true, symEffect: "Read"}, // load 2 bytes from arg0+auxint+aux. arg1=mem. Zero extend. {name: "MOVWLSXload", argLength: 2, reg: gpload, asm: "MOVWLSX", aux: "SymOff", faultOnNilArg0: true, symEffect: "Read"}, // ditto, sign extend to int32 {name: "MOVLload", argLength: 2, reg: gpload, asm: "MOVL", aux: "SymOff", typ: "UInt32", faultOnNilArg0: true, symEffect: "Read"}, // load 4 bytes from arg0+auxint+aux. arg1=mem. Zero extend. {name: "MOVBstore", argLength: 3, reg: gpstore, asm: "MOVB", aux: "SymOff", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store byte in arg1 to arg0+auxint+aux. arg2=mem {name: "MOVWstore", argLength: 3, reg: gpstore, asm: "MOVW", aux: "SymOff", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 2 bytes in arg1 to arg0+auxint+aux. arg2=mem {name: "MOVLstore", argLength: 3, reg: gpstore, asm: "MOVL", aux: "SymOff", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 4 bytes in arg1 to arg0+auxint+aux. arg2=mem // direct binary-op on memory (read-modify-write) {name: "ADDLmodify", argLength: 3, reg: gpstore, asm: "ADDL", aux: "SymOff", typ: "Mem", faultOnNilArg0: true, clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+auxint+aux) += arg1, arg2=mem {name: "SUBLmodify", argLength: 3, reg: gpstore, asm: "SUBL", aux: "SymOff", typ: "Mem", faultOnNilArg0: true, clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+auxint+aux) -= arg1, arg2=mem {name: "ANDLmodify", argLength: 3, reg: gpstore, asm: "ANDL", aux: "SymOff", typ: "Mem", faultOnNilArg0: true, clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+auxint+aux) &= arg1, arg2=mem {name: "ORLmodify", argLength: 3, reg: gpstore, asm: "ORL", aux: "SymOff", typ: "Mem", faultOnNilArg0: true, clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+auxint+aux) |= arg1, arg2=mem {name: "XORLmodify", argLength: 3, reg: gpstore, asm: "XORL", aux: "SymOff", typ: "Mem", faultOnNilArg0: true, clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+auxint+aux) ^= arg1, arg2=mem // direct binary-op on indexed memory (read-modify-write) {name: "ADDLmodifyidx4", argLength: 4, reg: gpstoreidx, asm: "ADDL", aux: "SymOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+arg1*4+auxint+aux) += arg2, arg3=mem {name: "SUBLmodifyidx4", argLength: 4, reg: gpstoreidx, asm: "SUBL", aux: "SymOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+arg1*4+auxint+aux) -= arg2, arg3=mem {name: "ANDLmodifyidx4", argLength: 4, reg: gpstoreidx, asm: "ANDL", aux: "SymOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+arg1*4+auxint+aux) &= arg2, arg3=mem {name: "ORLmodifyidx4", argLength: 4, reg: gpstoreidx, asm: "ORL", aux: "SymOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+arg1*4+auxint+aux) |= arg2, arg3=mem {name: "XORLmodifyidx4", argLength: 4, reg: gpstoreidx, asm: "XORL", aux: "SymOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // *(arg0+arg1*4+auxint+aux) ^= arg2, arg3=mem // direct binary-op on memory with a constant (read-modify-write) {name: "ADDLconstmodify", argLength: 2, reg: gpstoreconst, asm: "ADDL", aux: "SymValAndOff", typ: "Mem", clobberFlags: true, faultOnNilArg0: true, symEffect: "Read,Write"}, // add ValAndOff(AuxInt).Val() to arg0+ValAndOff(AuxInt).Off()+aux, arg1=mem {name: "ANDLconstmodify", argLength: 2, reg: gpstoreconst, asm: "ANDL", aux: "SymValAndOff", typ: "Mem", clobberFlags: true, faultOnNilArg0: true, symEffect: "Read,Write"}, // and ValAndOff(AuxInt).Val() to arg0+ValAndOff(AuxInt).Off()+aux, arg1=mem {name: "ORLconstmodify", argLength: 2, reg: gpstoreconst, asm: "ORL", aux: "SymValAndOff", typ: "Mem", clobberFlags: true, faultOnNilArg0: true, symEffect: "Read,Write"}, // or ValAndOff(AuxInt).Val() to arg0+ValAndOff(AuxInt).Off()+aux, arg1=mem {name: "XORLconstmodify", argLength: 2, reg: gpstoreconst, asm: "XORL", aux: "SymValAndOff", typ: "Mem", clobberFlags: true, faultOnNilArg0: true, symEffect: "Read,Write"}, // xor ValAndOff(AuxInt).Val() to arg0+ValAndOff(AuxInt).Off()+aux, arg1=mem // direct binary-op on indexed memory with a constant (read-modify-write) {name: "ADDLconstmodifyidx4", argLength: 3, reg: gpstoreconstidx, asm: "ADDL", aux: "SymValAndOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // add ValAndOff(AuxInt).Val() to arg0+arg1*4+ValAndOff(AuxInt).Off()+aux, arg2=mem {name: "ANDLconstmodifyidx4", argLength: 3, reg: gpstoreconstidx, asm: "ANDL", aux: "SymValAndOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // and ValAndOff(AuxInt).Val() to arg0+arg1*4+ValAndOff(AuxInt).Off()+aux, arg2=mem {name: "ORLconstmodifyidx4", argLength: 3, reg: gpstoreconstidx, asm: "ORL", aux: "SymValAndOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // or ValAndOff(AuxInt).Val() to arg0+arg1*4+ValAndOff(AuxInt).Off()+aux, arg2=mem {name: "XORLconstmodifyidx4", argLength: 3, reg: gpstoreconstidx, asm: "XORL", aux: "SymValAndOff", typ: "Mem", clobberFlags: true, symEffect: "Read,Write"}, // xor ValAndOff(AuxInt).Val() to arg0+arg1*4+ValAndOff(AuxInt).Off()+aux, arg2=mem // indexed loads/stores {name: "MOVBloadidx1", argLength: 3, reg: gploadidx, commutative: true, asm: "MOVBLZX", aux: "SymOff", symEffect: "Read"}, // load a byte from arg0+arg1+auxint+aux. arg2=mem {name: "MOVWloadidx1", argLength: 3, reg: gploadidx, commutative: true, asm: "MOVWLZX", aux: "SymOff", symEffect: "Read"}, // load 2 bytes from arg0+arg1+auxint+aux. arg2=mem {name: "MOVWloadidx2", argLength: 3, reg: gploadidx, asm: "MOVWLZX", aux: "SymOff", symEffect: "Read"}, // load 2 bytes from arg0+2*arg1+auxint+aux. arg2=mem {name: "MOVLloadidx1", argLength: 3, reg: gploadidx, commutative: true, asm: "MOVL", aux: "SymOff", symEffect: "Read"}, // load 4 bytes from arg0+arg1+auxint+aux. arg2=mem {name: "MOVLloadidx4", argLength: 3, reg: gploadidx, asm: "MOVL", aux: "SymOff", symEffect: "Read"}, // load 4 bytes from arg0+4*arg1+auxint+aux. arg2=mem // TODO: sign-extending indexed loads {name: "MOVBstoreidx1", argLength: 4, reg: gpstoreidx, commutative: true, asm: "MOVB", aux: "SymOff", symEffect: "Write"}, // store byte in arg2 to arg0+arg1+auxint+aux. arg3=mem {name: "MOVWstoreidx1", argLength: 4, reg: gpstoreidx, commutative: true, asm: "MOVW", aux: "SymOff", symEffect: "Write"}, // store 2 bytes in arg2 to arg0+arg1+auxint+aux. arg3=mem {name: "MOVWstoreidx2", argLength: 4, reg: gpstoreidx, asm: "MOVW", aux: "SymOff", symEffect: "Write"}, // store 2 bytes in arg2 to arg0+2*arg1+auxint+aux. arg3=mem {name: "MOVLstoreidx1", argLength: 4, reg: gpstoreidx, commutative: true, asm: "MOVL", aux: "SymOff", symEffect: "Write"}, // store 4 bytes in arg2 to arg0+arg1+auxint+aux. arg3=mem {name: "MOVLstoreidx4", argLength: 4, reg: gpstoreidx, asm: "MOVL", aux: "SymOff", symEffect: "Write"}, // store 4 bytes in arg2 to arg0+4*arg1+auxint+aux. arg3=mem // TODO: add size-mismatched indexed loads, like MOVBstoreidx4. // For storeconst ops, the AuxInt field encodes both // the value to store and an address offset of the store. // Cast AuxInt to a ValAndOff to extract Val and Off fields. {name: "MOVBstoreconst", argLength: 2, reg: gpstoreconst, asm: "MOVB", aux: "SymValAndOff", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store low byte of ValAndOff(AuxInt).Val() to arg0+ValAndOff(AuxInt).Off()+aux. arg1=mem {name: "MOVWstoreconst", argLength: 2, reg: gpstoreconst, asm: "MOVW", aux: "SymValAndOff", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store low 2 bytes of ... {name: "MOVLstoreconst", argLength: 2, reg: gpstoreconst, asm: "MOVL", aux: "SymValAndOff", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store low 4 bytes of ... {name: "MOVBstoreconstidx1", argLength: 3, reg: gpstoreconstidx, asm: "MOVB", aux: "SymValAndOff", typ: "Mem", symEffect: "Write"}, // store low byte of ValAndOff(AuxInt).Val() to arg0+1*arg1+ValAndOff(AuxInt).Off()+aux. arg2=mem {name: "MOVWstoreconstidx1", argLength: 3, reg: gpstoreconstidx, asm: "MOVW", aux: "SymValAndOff", typ: "Mem", symEffect: "Write"}, // store low 2 bytes of ... arg1 ... {name: "MOVWstoreconstidx2", argLength: 3, reg: gpstoreconstidx, asm: "MOVW", aux: "SymValAndOff", typ: "Mem", symEffect: "Write"}, // store low 2 bytes of ... 2*arg1 ... {name: "MOVLstoreconstidx1", argLength: 3, reg: gpstoreconstidx, asm: "MOVL", aux: "SymValAndOff", typ: "Mem", symEffect: "Write"}, // store low 4 bytes of ... arg1 ... {name: "MOVLstoreconstidx4", argLength: 3, reg: gpstoreconstidx, asm: "MOVL", aux: "SymValAndOff", typ: "Mem", symEffect: "Write"}, // store low 4 bytes of ... 4*arg1 ... // arg0 = pointer to start of memory to zero // arg1 = value to store (will always be zero) // arg2 = mem // auxint = offset into duffzero code to start executing // returns mem { name: "DUFFZERO", aux: "Int64", argLength: 3, reg: regInfo{ inputs: []regMask{buildReg("DI"), buildReg("AX")}, clobbers: buildReg("DI CX"), // Note: CX is only clobbered when dynamic linking. }, faultOnNilArg0: true, }, // arg0 = address of memory to zero // arg1 = # of 4-byte words to zero // arg2 = value to store (will always be zero) // arg3 = mem // returns mem { name: "REPSTOSL", argLength: 4, reg: regInfo{ inputs: []regMask{buildReg("DI"), buildReg("CX"), buildReg("AX")}, clobbers: buildReg("DI CX"), }, faultOnNilArg0: true, }, {name: "CALLstatic", argLength: 1, reg: regInfo{clobbers: callerSave}, aux: "CallOff", clobberFlags: true, call: true}, // call static function aux.(*obj.LSym). arg0=mem, auxint=argsize, returns mem {name: "CALLtail", argLength: 1, reg: regInfo{clobbers: callerSave}, aux: "CallOff", clobberFlags: true, call: true, tailCall: true}, // tail call static function aux.(*obj.LSym). arg0=mem, auxint=argsize, returns mem {name: "CALLclosure", argLength: 3, reg: regInfo{inputs: []regMask{gpsp, buildReg("DX"), 0}, clobbers: callerSave}, aux: "CallOff", clobberFlags: true, call: true}, // call function via closure. arg0=codeptr, arg1=closure, arg2=mem, auxint=argsize, returns mem {name: "CALLinter", argLength: 2, reg: regInfo{inputs: []regMask{gp}, clobbers: callerSave}, aux: "CallOff", clobberFlags: true, call: true}, // call fn by pointer. arg0=codeptr, arg1=mem, auxint=argsize, returns mem // arg0 = destination pointer // arg1 = source pointer // arg2 = mem // auxint = offset from duffcopy symbol to call // returns memory { name: "DUFFCOPY", aux: "Int64", argLength: 3, reg: regInfo{ inputs: []regMask{buildReg("DI"), buildReg("SI")}, clobbers: buildReg("DI SI CX"), // uses CX as a temporary }, clobberFlags: true, faultOnNilArg0: true, faultOnNilArg1: true, }, // arg0 = destination pointer // arg1 = source pointer // arg2 = # of 8-byte words to copy // arg3 = mem // returns memory { name: "REPMOVSL", argLength: 4, reg: regInfo{ inputs: []regMask{buildReg("DI"), buildReg("SI"), buildReg("CX")}, clobbers: buildReg("DI SI CX"), }, faultOnNilArg0: true, faultOnNilArg1: true, }, // (InvertFlags (CMPL a b)) == (CMPL b a) // So if we want (SETL (CMPL a b)) but we can't do that because a is a constant, // then we do (SETL (InvertFlags (CMPL b a))) instead. // Rewrites will convert this to (SETG (CMPL b a)). // InvertFlags is a pseudo-op which can't appear in assembly output. {name: "InvertFlags", argLength: 1}, // reverse direction of arg0 // Pseudo-ops {name: "LoweredGetG", argLength: 1, reg: gp01}, // arg0=mem // Scheduler ensures LoweredGetClosurePtr occurs only in entry block, // and sorts it to the very beginning of the block to prevent other // use of DX (the closure pointer) {name: "LoweredGetClosurePtr", reg: regInfo{outputs: []regMask{buildReg("DX")}}, zeroWidth: true}, // LoweredGetCallerPC evaluates to the PC to which its "caller" will return. // I.e., if f calls g "calls" getcallerpc, // the result should be the PC within f that g will return to. // See runtime/stubs.go for a more detailed discussion. {name: "LoweredGetCallerPC", reg: gp01, rematerializeable: true}, // LoweredGetCallerSP returns the SP of the caller of the current function. arg0=mem {name: "LoweredGetCallerSP", argLength: 1, reg: gp01, rematerializeable: true}, //arg0=ptr,arg1=mem, returns void. Faults if ptr is nil. {name: "LoweredNilCheck", argLength: 2, reg: regInfo{inputs: []regMask{gpsp}}, clobberFlags: true, nilCheck: true, faultOnNilArg0: true}, // LoweredWB invokes runtime.gcWriteBarrier. arg0=mem, auxint=# of write barrier slots // It saves all GP registers if necessary, but may clobber others. // Returns a pointer to a write barrier buffer in DI. {name: "LoweredWB", argLength: 1, reg: regInfo{clobbers: callerSave &^ gp, outputs: []regMask{buildReg("DI")}}, clobberFlags: true, aux: "Int64"}, // There are three of these functions so that they can have three different register inputs. // When we check 0 <= c <= cap (A), then 0 <= b <= c (B), then 0 <= a <= b (C), we want the // default registers to match so we don't need to copy registers around unnecessarily. {name: "LoweredPanicBoundsA", argLength: 3, aux: "Int64", reg: regInfo{inputs: []regMask{dx, bx}}, typ: "Mem", call: true}, // arg0=idx, arg1=len, arg2=mem, returns memory. AuxInt contains report code (see PanicBounds in genericOps.go). {name: "LoweredPanicBoundsB", argLength: 3, aux: "Int64", reg: regInfo{inputs: []regMask{cx, dx}}, typ: "Mem", call: true}, // arg0=idx, arg1=len, arg2=mem, returns memory. AuxInt contains report code (see PanicBounds in genericOps.go). {name: "LoweredPanicBoundsC", argLength: 3, aux: "Int64", reg: regInfo{inputs: []regMask{ax, cx}}, typ: "Mem", call: true}, // arg0=idx, arg1=len, arg2=mem, returns memory. AuxInt contains report code (see PanicBounds in genericOps.go). // Extend ops are the same as Bounds ops except the indexes are 64-bit. {name: "LoweredPanicExtendA", argLength: 4, aux: "Int64", reg: regInfo{inputs: []regMask{si, dx, bx}}, typ: "Mem", call: true}, // arg0=idxHi, arg1=idxLo, arg2=len, arg3=mem, returns memory. AuxInt contains report code (see PanicExtend in genericOps.go). {name: "LoweredPanicExtendB", argLength: 4, aux: "Int64", reg: regInfo{inputs: []regMask{si, cx, dx}}, typ: "Mem", call: true}, // arg0=idxHi, arg1=idxLo, arg2=len, arg3=mem, returns memory. AuxInt contains report code (see PanicExtend in genericOps.go). {name: "LoweredPanicExtendC", argLength: 4, aux: "Int64", reg: regInfo{inputs: []regMask{si, ax, cx}}, typ: "Mem", call: true}, // arg0=idxHi, arg1=idxLo, arg2=len, arg3=mem, returns memory. AuxInt contains report code (see PanicExtend in genericOps.go). // Constant flag values. For any comparison, there are 5 possible // outcomes: the three from the signed total order (<,==,>) and the // three from the unsigned total order. The == cases overlap. // Note: there's a sixth "unordered" outcome for floating-point // comparisons, but we don't use such a beast yet. // These ops are for temporary use by rewrite rules. They // cannot appear in the generated assembly. {name: "FlagEQ"}, // equal {name: "FlagLT_ULT"}, // signed < and unsigned < {name: "FlagLT_UGT"}, // signed < and unsigned > {name: "FlagGT_UGT"}, // signed > and unsigned < {name: "FlagGT_ULT"}, // signed > and unsigned > // Special ops for PIC floating-point constants. // MOVSXconst1 loads the address of the constant-pool entry into a register. // MOVSXconst2 loads the constant from that address. // MOVSXconst1 returns a pointer, but we type it as uint32 because it can never point to the Go heap. {name: "MOVSSconst1", reg: gp01, typ: "UInt32", aux: "Float32"}, {name: "MOVSDconst1", reg: gp01, typ: "UInt32", aux: "Float64"}, {name: "MOVSSconst2", argLength: 1, reg: gpfp, asm: "MOVSS"}, {name: "MOVSDconst2", argLength: 1, reg: gpfp, asm: "MOVSD"}, } var _386blocks = []blockData{ {name: "EQ", controls: 1}, {name: "NE", controls: 1}, {name: "LT", controls: 1}, {name: "LE", controls: 1}, {name: "GT", controls: 1}, {name: "GE", controls: 1}, {name: "OS", controls: 1}, {name: "OC", controls: 1}, {name: "ULT", controls: 1}, {name: "ULE", controls: 1}, {name: "UGT", controls: 1}, {name: "UGE", controls: 1}, {name: "EQF", controls: 1}, {name: "NEF", controls: 1}, {name: "ORD", controls: 1}, // FP, ordered comparison (parity zero) {name: "NAN", controls: 1}, // FP, unordered comparison (parity one) } archs = append(archs, arch{ name: "386", pkg: "cmd/internal/obj/x86", genfile: "../../x86/ssa.go", ops: _386ops, blocks: _386blocks, regnames: regNames386, gpregmask: gp, fpregmask: fp, framepointerreg: int8(num["BP"]), linkreg: -1, // not used }) }
go/src/cmd/compile/internal/ssa/_gen/386Ops.go/0
{ "file_path": "go/src/cmd/compile/internal/ssa/_gen/386Ops.go", "repo_id": "go", "token_count": 19261 }
97
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import "strings" // Notes: // - Integer types live in the low portion of registers. Upper portions are junk. // - Boolean types use the low-order byte of a register. 0=false, 1=true. // Upper bytes are junk. // - Unused portions of AuxInt are filled by sign-extending the used portion. // - *const instructions may use a constant larger than the instruction can encode. // In this case the assembler expands to multiple instructions and uses tmp // register (R23). // Suffixes encode the bit width of various instructions. // W (word) = 32 bit // H (half word) = 16 bit // HU = 16 bit unsigned // B (byte) = 8 bit // BU = 8 bit unsigned // F (float) = 32 bit float // D (double) = 64 bit float // Note: registers not used in regalloc are not included in this list, // so that regmask stays within int64 // Be careful when hand coding regmasks. var regNamesMIPS = []string{ "R0", // constant 0 "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15", "R16", "R17", "R18", "R19", "R20", "R21", "R22", //REGTMP "R24", "R25", // R26 reserved by kernel // R27 reserved by kernel "R28", "SP", // aka R29 "g", // aka R30 "R31", // REGLINK // odd FP registers contain high parts of 64-bit FP values "F0", "F2", "F4", "F6", "F8", "F10", "F12", "F14", "F16", "F18", "F20", "F22", "F24", "F26", "F28", "F30", "HI", // high bits of multiplication "LO", // low bits of multiplication // If you add registers, update asyncPreempt in runtime. // pseudo-registers "SB", } func init() { // Make map from reg names to reg integers. if len(regNamesMIPS) > 64 { panic("too many registers") } num := map[string]int{} for i, name := range regNamesMIPS { num[name] = i } buildReg := func(s string) regMask { m := regMask(0) for _, r := range strings.Split(s, " ") { if n, ok := num[r]; ok { m |= regMask(1) << uint(n) continue } panic("register " + r + " not found") } return m } // Common individual register masks var ( gp = buildReg("R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13 R14 R15 R16 R17 R18 R19 R20 R21 R22 R24 R25 R28 R31") gpg = gp | buildReg("g") gpsp = gp | buildReg("SP") gpspg = gpg | buildReg("SP") gpspsbg = gpspg | buildReg("SB") fp = buildReg("F0 F2 F4 F6 F8 F10 F12 F14 F16 F18 F20 F22 F24 F26 F28 F30") lo = buildReg("LO") hi = buildReg("HI") callerSave = gp | fp | lo | hi | buildReg("g") // runtime.setg (and anything calling it) may clobber g r1 = buildReg("R1") r2 = buildReg("R2") r3 = buildReg("R3") r4 = buildReg("R4") r5 = buildReg("R5") ) // Common regInfo var ( gp01 = regInfo{inputs: nil, outputs: []regMask{gp}} gp11 = regInfo{inputs: []regMask{gpg}, outputs: []regMask{gp}} gp11sp = regInfo{inputs: []regMask{gpspg}, outputs: []regMask{gp}} gp21 = regInfo{inputs: []regMask{gpg, gpg}, outputs: []regMask{gp}} gp31 = regInfo{inputs: []regMask{gp, gp, gp}, outputs: []regMask{gp}} gp2hilo = regInfo{inputs: []regMask{gpg, gpg}, outputs: []regMask{hi, lo}} gpload = regInfo{inputs: []regMask{gpspsbg}, outputs: []regMask{gp}} gpstore = regInfo{inputs: []regMask{gpspsbg, gpg}} gpxchg = regInfo{inputs: []regMask{gpspsbg, gpg}, outputs: []regMask{gp}} gpcas = regInfo{inputs: []regMask{gpspsbg, gpg, gpg}, outputs: []regMask{gp}} gpstore0 = regInfo{inputs: []regMask{gpspsbg}} fpgp = regInfo{inputs: []regMask{fp}, outputs: []regMask{gp}} gpfp = regInfo{inputs: []regMask{gp}, outputs: []regMask{fp}} fp01 = regInfo{inputs: nil, outputs: []regMask{fp}} fp11 = regInfo{inputs: []regMask{fp}, outputs: []regMask{fp}} fp21 = regInfo{inputs: []regMask{fp, fp}, outputs: []regMask{fp}} fp2flags = regInfo{inputs: []regMask{fp, fp}} fpload = regInfo{inputs: []regMask{gpspsbg}, outputs: []regMask{fp}} fpstore = regInfo{inputs: []regMask{gpspsbg, fp}} readflags = regInfo{inputs: nil, outputs: []regMask{gp}} ) ops := []opData{ {name: "ADD", argLength: 2, reg: gp21, asm: "ADDU", commutative: true}, // arg0 + arg1 {name: "ADDconst", argLength: 1, reg: gp11sp, asm: "ADDU", aux: "Int32"}, // arg0 + auxInt {name: "SUB", argLength: 2, reg: gp21, asm: "SUBU"}, // arg0 - arg1 {name: "SUBconst", argLength: 1, reg: gp11, asm: "SUBU", aux: "Int32"}, // arg0 - auxInt {name: "MUL", argLength: 2, reg: regInfo{inputs: []regMask{gpg, gpg}, outputs: []regMask{gp}, clobbers: hi | lo}, asm: "MUL", commutative: true}, // arg0 * arg1 {name: "MULT", argLength: 2, reg: gp2hilo, asm: "MUL", commutative: true, typ: "(Int32,Int32)"}, // arg0 * arg1, signed, results hi,lo {name: "MULTU", argLength: 2, reg: gp2hilo, asm: "MULU", commutative: true, typ: "(UInt32,UInt32)"}, // arg0 * arg1, unsigned, results hi,lo {name: "DIV", argLength: 2, reg: gp2hilo, asm: "DIV", typ: "(Int32,Int32)"}, // arg0 / arg1, signed, results hi=arg0%arg1,lo=arg0/arg1 {name: "DIVU", argLength: 2, reg: gp2hilo, asm: "DIVU", typ: "(UInt32,UInt32)"}, // arg0 / arg1, signed, results hi=arg0%arg1,lo=arg0/arg1 {name: "ADDF", argLength: 2, reg: fp21, asm: "ADDF", commutative: true}, // arg0 + arg1 {name: "ADDD", argLength: 2, reg: fp21, asm: "ADDD", commutative: true}, // arg0 + arg1 {name: "SUBF", argLength: 2, reg: fp21, asm: "SUBF"}, // arg0 - arg1 {name: "SUBD", argLength: 2, reg: fp21, asm: "SUBD"}, // arg0 - arg1 {name: "MULF", argLength: 2, reg: fp21, asm: "MULF", commutative: true}, // arg0 * arg1 {name: "MULD", argLength: 2, reg: fp21, asm: "MULD", commutative: true}, // arg0 * arg1 {name: "DIVF", argLength: 2, reg: fp21, asm: "DIVF"}, // arg0 / arg1 {name: "DIVD", argLength: 2, reg: fp21, asm: "DIVD"}, // arg0 / arg1 {name: "AND", argLength: 2, reg: gp21, asm: "AND", commutative: true}, // arg0 & arg1 {name: "ANDconst", argLength: 1, reg: gp11, asm: "AND", aux: "Int32"}, // arg0 & auxInt {name: "OR", argLength: 2, reg: gp21, asm: "OR", commutative: true}, // arg0 | arg1 {name: "ORconst", argLength: 1, reg: gp11, asm: "OR", aux: "Int32"}, // arg0 | auxInt {name: "XOR", argLength: 2, reg: gp21, asm: "XOR", commutative: true, typ: "UInt32"}, // arg0 ^ arg1 {name: "XORconst", argLength: 1, reg: gp11, asm: "XOR", aux: "Int32", typ: "UInt32"}, // arg0 ^ auxInt {name: "NOR", argLength: 2, reg: gp21, asm: "NOR", commutative: true}, // ^(arg0 | arg1) {name: "NORconst", argLength: 1, reg: gp11, asm: "NOR", aux: "Int32"}, // ^(arg0 | auxInt) {name: "NEG", argLength: 1, reg: gp11}, // -arg0 {name: "NEGF", argLength: 1, reg: fp11, asm: "NEGF"}, // -arg0, float32 {name: "NEGD", argLength: 1, reg: fp11, asm: "NEGD"}, // -arg0, float64 {name: "ABSD", argLength: 1, reg: fp11, asm: "ABSD"}, // abs(arg0), float64 {name: "SQRTD", argLength: 1, reg: fp11, asm: "SQRTD"}, // sqrt(arg0), float64 {name: "SQRTF", argLength: 1, reg: fp11, asm: "SQRTF"}, // sqrt(arg0), float32 // shifts {name: "SLL", argLength: 2, reg: gp21, asm: "SLL"}, // arg0 << arg1, shift amount is mod 32 {name: "SLLconst", argLength: 1, reg: gp11, asm: "SLL", aux: "Int32"}, // arg0 << auxInt, shift amount must be 0 through 31 inclusive {name: "SRL", argLength: 2, reg: gp21, asm: "SRL"}, // arg0 >> arg1, unsigned, shift amount is mod 32 {name: "SRLconst", argLength: 1, reg: gp11, asm: "SRL", aux: "Int32"}, // arg0 >> auxInt, shift amount must be 0 through 31 inclusive {name: "SRA", argLength: 2, reg: gp21, asm: "SRA"}, // arg0 >> arg1, signed, shift amount is mod 32 {name: "SRAconst", argLength: 1, reg: gp11, asm: "SRA", aux: "Int32"}, // arg0 >> auxInt, signed, shift amount must be 0 through 31 inclusive {name: "CLZ", argLength: 1, reg: gp11, asm: "CLZ"}, // comparisons {name: "SGT", argLength: 2, reg: gp21, asm: "SGT", typ: "Bool"}, // 1 if arg0 > arg1 (signed), 0 otherwise {name: "SGTconst", argLength: 1, reg: gp11, asm: "SGT", aux: "Int32", typ: "Bool"}, // 1 if auxInt > arg0 (signed), 0 otherwise {name: "SGTzero", argLength: 1, reg: gp11, asm: "SGT", typ: "Bool"}, // 1 if arg0 > 0 (signed), 0 otherwise {name: "SGTU", argLength: 2, reg: gp21, asm: "SGTU", typ: "Bool"}, // 1 if arg0 > arg1 (unsigned), 0 otherwise {name: "SGTUconst", argLength: 1, reg: gp11, asm: "SGTU", aux: "Int32", typ: "Bool"}, // 1 if auxInt > arg0 (unsigned), 0 otherwise {name: "SGTUzero", argLength: 1, reg: gp11, asm: "SGTU", typ: "Bool"}, // 1 if arg0 > 0 (unsigned), 0 otherwise {name: "CMPEQF", argLength: 2, reg: fp2flags, asm: "CMPEQF", typ: "Flags"}, // flags=true if arg0 = arg1, float32 {name: "CMPEQD", argLength: 2, reg: fp2flags, asm: "CMPEQD", typ: "Flags"}, // flags=true if arg0 = arg1, float64 {name: "CMPGEF", argLength: 2, reg: fp2flags, asm: "CMPGEF", typ: "Flags"}, // flags=true if arg0 >= arg1, float32 {name: "CMPGED", argLength: 2, reg: fp2flags, asm: "CMPGED", typ: "Flags"}, // flags=true if arg0 >= arg1, float64 {name: "CMPGTF", argLength: 2, reg: fp2flags, asm: "CMPGTF", typ: "Flags"}, // flags=true if arg0 > arg1, float32 {name: "CMPGTD", argLength: 2, reg: fp2flags, asm: "CMPGTD", typ: "Flags"}, // flags=true if arg0 > arg1, float64 // moves {name: "MOVWconst", argLength: 0, reg: gp01, aux: "Int32", asm: "MOVW", typ: "UInt32", rematerializeable: true}, // auxint {name: "MOVFconst", argLength: 0, reg: fp01, aux: "Float32", asm: "MOVF", typ: "Float32", rematerializeable: true}, // auxint as 64-bit float, convert to 32-bit float {name: "MOVDconst", argLength: 0, reg: fp01, aux: "Float64", asm: "MOVD", typ: "Float64", rematerializeable: true}, // auxint as 64-bit float {name: "MOVWaddr", argLength: 1, reg: regInfo{inputs: []regMask{buildReg("SP") | buildReg("SB")}, outputs: []regMask{gp}}, aux: "SymOff", asm: "MOVW", rematerializeable: true, symEffect: "Addr"}, // arg0 + auxInt + aux.(*gc.Sym), arg0=SP/SB {name: "MOVBload", argLength: 2, reg: gpload, aux: "SymOff", asm: "MOVB", typ: "Int8", faultOnNilArg0: true, symEffect: "Read"}, // load from arg0 + auxInt + aux. arg1=mem. {name: "MOVBUload", argLength: 2, reg: gpload, aux: "SymOff", asm: "MOVBU", typ: "UInt8", faultOnNilArg0: true, symEffect: "Read"}, // load from arg0 + auxInt + aux. arg1=mem. {name: "MOVHload", argLength: 2, reg: gpload, aux: "SymOff", asm: "MOVH", typ: "Int16", faultOnNilArg0: true, symEffect: "Read"}, // load from arg0 + auxInt + aux. arg1=mem. {name: "MOVHUload", argLength: 2, reg: gpload, aux: "SymOff", asm: "MOVHU", typ: "UInt16", faultOnNilArg0: true, symEffect: "Read"}, // load from arg0 + auxInt + aux. arg1=mem. {name: "MOVWload", argLength: 2, reg: gpload, aux: "SymOff", asm: "MOVW", typ: "UInt32", faultOnNilArg0: true, symEffect: "Read"}, // load from arg0 + auxInt + aux. arg1=mem. {name: "MOVFload", argLength: 2, reg: fpload, aux: "SymOff", asm: "MOVF", typ: "Float32", faultOnNilArg0: true, symEffect: "Read"}, // load from arg0 + auxInt + aux. arg1=mem. {name: "MOVDload", argLength: 2, reg: fpload, aux: "SymOff", asm: "MOVD", typ: "Float64", faultOnNilArg0: true, symEffect: "Read"}, // load from arg0 + auxInt + aux. arg1=mem. {name: "MOVBstore", argLength: 3, reg: gpstore, aux: "SymOff", asm: "MOVB", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 1 byte of arg1 to arg0 + auxInt + aux. arg2=mem. {name: "MOVHstore", argLength: 3, reg: gpstore, aux: "SymOff", asm: "MOVH", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 2 bytes of arg1 to arg0 + auxInt + aux. arg2=mem. {name: "MOVWstore", argLength: 3, reg: gpstore, aux: "SymOff", asm: "MOVW", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 4 bytes of arg1 to arg0 + auxInt + aux. arg2=mem. {name: "MOVFstore", argLength: 3, reg: fpstore, aux: "SymOff", asm: "MOVF", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 4 bytes of arg1 to arg0 + auxInt + aux. arg2=mem. {name: "MOVDstore", argLength: 3, reg: fpstore, aux: "SymOff", asm: "MOVD", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 8 bytes of arg1 to arg0 + auxInt + aux. arg2=mem. {name: "MOVBstorezero", argLength: 2, reg: gpstore0, aux: "SymOff", asm: "MOVB", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 1 byte of zero to arg0 + auxInt + aux. arg1=mem. {name: "MOVHstorezero", argLength: 2, reg: gpstore0, aux: "SymOff", asm: "MOVH", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 2 bytes of zero to arg0 + auxInt + aux. arg1=mem. {name: "MOVWstorezero", argLength: 2, reg: gpstore0, aux: "SymOff", asm: "MOVW", typ: "Mem", faultOnNilArg0: true, symEffect: "Write"}, // store 4 bytes of zero to arg0 + auxInt + aux. arg1=mem. // moves (no conversion) {name: "MOVWfpgp", argLength: 1, reg: fpgp, asm: "MOVW"}, // move float32 to int32 (no conversion) {name: "MOVWgpfp", argLength: 1, reg: gpfp, asm: "MOVW"}, // move int32 to float32 (no conversion) // conversions {name: "MOVBreg", argLength: 1, reg: gp11, asm: "MOVB"}, // move from arg0, sign-extended from byte {name: "MOVBUreg", argLength: 1, reg: gp11, asm: "MOVBU"}, // move from arg0, unsign-extended from byte {name: "MOVHreg", argLength: 1, reg: gp11, asm: "MOVH"}, // move from arg0, sign-extended from half {name: "MOVHUreg", argLength: 1, reg: gp11, asm: "MOVHU"}, // move from arg0, unsign-extended from half {name: "MOVWreg", argLength: 1, reg: gp11, asm: "MOVW"}, // move from arg0 {name: "MOVWnop", argLength: 1, reg: regInfo{inputs: []regMask{gp}, outputs: []regMask{gp}}, resultInArg0: true}, // nop, return arg0 in same register // conditional move on zero (returns arg1 if arg2 is 0, otherwise arg0) // order of parameters is reversed so we can use resultInArg0 (OpCMOVZ result arg1 arg2-> CMOVZ arg2reg, arg1reg, resultReg) {name: "CMOVZ", argLength: 3, reg: gp31, asm: "CMOVZ", resultInArg0: true}, {name: "CMOVZzero", argLength: 2, reg: regInfo{inputs: []regMask{gp, gpg}, outputs: []regMask{gp}}, asm: "CMOVZ", resultInArg0: true}, {name: "MOVWF", argLength: 1, reg: fp11, asm: "MOVWF"}, // int32 -> float32 {name: "MOVWD", argLength: 1, reg: fp11, asm: "MOVWD"}, // int32 -> float64 {name: "TRUNCFW", argLength: 1, reg: fp11, asm: "TRUNCFW"}, // float32 -> int32 {name: "TRUNCDW", argLength: 1, reg: fp11, asm: "TRUNCDW"}, // float64 -> int32 {name: "MOVFD", argLength: 1, reg: fp11, asm: "MOVFD"}, // float32 -> float64 {name: "MOVDF", argLength: 1, reg: fp11, asm: "MOVDF"}, // float64 -> float32 // function calls {name: "CALLstatic", argLength: 1, reg: regInfo{clobbers: callerSave}, aux: "CallOff", clobberFlags: true, call: true}, // call static function aux.(*obj.LSym). arg0=mem, auxint=argsize, returns mem {name: "CALLtail", argLength: 1, reg: regInfo{clobbers: callerSave}, aux: "CallOff", clobberFlags: true, call: true, tailCall: true}, // tail call static function aux.(*obj.LSym). arg0=mem, auxint=argsize, returns mem {name: "CALLclosure", argLength: 3, reg: regInfo{inputs: []regMask{gpsp, buildReg("R22"), 0}, clobbers: callerSave}, aux: "CallOff", clobberFlags: true, call: true}, // call function via closure. arg0=codeptr, arg1=closure, arg2=mem, auxint=argsize, returns mem {name: "CALLinter", argLength: 2, reg: regInfo{inputs: []regMask{gp}, clobbers: callerSave}, aux: "CallOff", clobberFlags: true, call: true}, // call fn by pointer. arg0=codeptr, arg1=mem, auxint=argsize, returns mem // atomic ops // load from arg0. arg1=mem. // returns <value,memory> so they can be properly ordered with other loads. // SYNC // MOV(B|W) (Rarg0), Rout // SYNC {name: "LoweredAtomicLoad8", argLength: 2, reg: gpload, faultOnNilArg0: true}, {name: "LoweredAtomicLoad32", argLength: 2, reg: gpload, faultOnNilArg0: true}, // store arg1 to arg0. arg2=mem. returns memory. // SYNC // MOV(B|W) Rarg1, (Rarg0) // SYNC {name: "LoweredAtomicStore8", argLength: 3, reg: gpstore, faultOnNilArg0: true, hasSideEffects: true}, {name: "LoweredAtomicStore32", argLength: 3, reg: gpstore, faultOnNilArg0: true, hasSideEffects: true}, {name: "LoweredAtomicStorezero", argLength: 2, reg: gpstore0, faultOnNilArg0: true, hasSideEffects: true}, // atomic exchange. // store arg1 to arg0. arg2=mem. returns <old content of *arg0, memory>. // SYNC // LL (Rarg0), Rout // MOVW Rarg1, Rtmp // SC Rtmp, (Rarg0) // BEQ Rtmp, -3(PC) // SYNC {name: "LoweredAtomicExchange", argLength: 3, reg: gpxchg, resultNotInArgs: true, faultOnNilArg0: true, hasSideEffects: true, unsafePoint: true}, // atomic add. // *arg0 += arg1. arg2=mem. returns <new content of *arg0, memory>. // SYNC // LL (Rarg0), Rout // ADDU Rarg1, Rout, Rtmp // SC Rtmp, (Rarg0) // BEQ Rtmp, -3(PC) // SYNC // ADDU Rarg1, Rout {name: "LoweredAtomicAdd", argLength: 3, reg: gpxchg, resultNotInArgs: true, faultOnNilArg0: true, hasSideEffects: true, unsafePoint: true}, {name: "LoweredAtomicAddconst", argLength: 2, reg: regInfo{inputs: []regMask{gpspsbg}, outputs: []regMask{gp}}, aux: "Int32", resultNotInArgs: true, faultOnNilArg0: true, hasSideEffects: true, unsafePoint: true}, // atomic compare and swap. // arg0 = pointer, arg1 = old value, arg2 = new value, arg3 = memory. // if *arg0 == arg1 { // *arg0 = arg2 // return (true, memory) // } else { // return (false, memory) // } // SYNC // MOVW $0, Rout // LL (Rarg0), Rtmp // BNE Rtmp, Rarg1, 4(PC) // MOVW Rarg2, Rout // SC Rout, (Rarg0) // BEQ Rout, -4(PC) // SYNC {name: "LoweredAtomicCas", argLength: 4, reg: gpcas, resultNotInArgs: true, faultOnNilArg0: true, hasSideEffects: true, unsafePoint: true}, // atomic and/or. // *arg0 &= (|=) arg1. arg2=mem. returns memory. // SYNC // LL (Rarg0), Rtmp // AND Rarg1, Rtmp // SC Rtmp, (Rarg0) // BEQ Rtmp, -3(PC) // SYNC {name: "LoweredAtomicAnd", argLength: 3, reg: gpstore, asm: "AND", faultOnNilArg0: true, hasSideEffects: true, unsafePoint: true}, {name: "LoweredAtomicOr", argLength: 3, reg: gpstore, asm: "OR", faultOnNilArg0: true, hasSideEffects: true, unsafePoint: true}, // large or unaligned zeroing // arg0 = address of memory to zero (in R1, changed as side effect) // arg1 = address of the last element to zero // arg2 = mem // auxint = alignment // returns mem // SUBU $4, R1 // MOVW R0, 4(R1) // ADDU $4, R1 // BNE Rarg1, R1, -2(PC) { name: "LoweredZero", aux: "Int32", argLength: 3, reg: regInfo{ inputs: []regMask{buildReg("R1"), gp}, clobbers: buildReg("R1"), }, faultOnNilArg0: true, }, // large or unaligned move // arg0 = address of dst memory (in R2, changed as side effect) // arg1 = address of src memory (in R1, changed as side effect) // arg2 = address of the last element of src // arg3 = mem // auxint = alignment // returns mem // SUBU $4, R1 // MOVW 4(R1), Rtmp // MOVW Rtmp, (R2) // ADDU $4, R1 // ADDU $4, R2 // BNE Rarg2, R1, -4(PC) { name: "LoweredMove", aux: "Int32", argLength: 4, reg: regInfo{ inputs: []regMask{buildReg("R2"), buildReg("R1"), gp}, clobbers: buildReg("R1 R2"), }, faultOnNilArg0: true, faultOnNilArg1: true, }, // pseudo-ops {name: "LoweredNilCheck", argLength: 2, reg: regInfo{inputs: []regMask{gpg}}, nilCheck: true, faultOnNilArg0: true}, // panic if arg0 is nil. arg1=mem. {name: "FPFlagTrue", argLength: 1, reg: readflags}, // bool, true if FP flag is true {name: "FPFlagFalse", argLength: 1, reg: readflags}, // bool, true if FP flag is false // Scheduler ensures LoweredGetClosurePtr occurs only in entry block, // and sorts it to the very beginning of the block to prevent other // use of R22 (mips.REGCTXT, the closure pointer) {name: "LoweredGetClosurePtr", reg: regInfo{outputs: []regMask{buildReg("R22")}}, zeroWidth: true}, // LoweredGetCallerSP returns the SP of the caller of the current function. arg0=mem. {name: "LoweredGetCallerSP", argLength: 1, reg: gp01, rematerializeable: true}, // LoweredGetCallerPC evaluates to the PC to which its "caller" will return. // I.e., if f calls g "calls" getcallerpc, // the result should be the PC within f that g will return to. // See runtime/stubs.go for a more detailed discussion. {name: "LoweredGetCallerPC", reg: gp01, rematerializeable: true}, // LoweredWB invokes runtime.gcWriteBarrier. arg0=mem, auxint=# of buffer entries needed // It saves all GP registers if necessary, // but clobbers R31 (LR) because it's a call // and R23 (REGTMP). // Returns a pointer to a write barrier buffer in R25. {name: "LoweredWB", argLength: 1, reg: regInfo{clobbers: (callerSave &^ gpg) | buildReg("R31"), outputs: []regMask{buildReg("R25")}}, clobberFlags: true, aux: "Int64"}, // There are three of these functions so that they can have three different register inputs. // When we check 0 <= c <= cap (A), then 0 <= b <= c (B), then 0 <= a <= b (C), we want the // default registers to match so we don't need to copy registers around unnecessarily. {name: "LoweredPanicBoundsA", argLength: 3, aux: "Int64", reg: regInfo{inputs: []regMask{r3, r4}}, typ: "Mem", call: true}, // arg0=idx, arg1=len, arg2=mem, returns memory. AuxInt contains report code (see PanicBounds in genericOps.go). {name: "LoweredPanicBoundsB", argLength: 3, aux: "Int64", reg: regInfo{inputs: []regMask{r2, r3}}, typ: "Mem", call: true}, // arg0=idx, arg1=len, arg2=mem, returns memory. AuxInt contains report code (see PanicBounds in genericOps.go). {name: "LoweredPanicBoundsC", argLength: 3, aux: "Int64", reg: regInfo{inputs: []regMask{r1, r2}}, typ: "Mem", call: true}, // arg0=idx, arg1=len, arg2=mem, returns memory. AuxInt contains report code (see PanicBounds in genericOps.go). // Extend ops are the same as Bounds ops except the indexes are 64-bit. {name: "LoweredPanicExtendA", argLength: 4, aux: "Int64", reg: regInfo{inputs: []regMask{r5, r3, r4}}, typ: "Mem", call: true}, // arg0=idxHi, arg1=idxLo, arg2=len, arg3=mem, returns memory. AuxInt contains report code (see PanicExtend in genericOps.go). {name: "LoweredPanicExtendB", argLength: 4, aux: "Int64", reg: regInfo{inputs: []regMask{r5, r2, r3}}, typ: "Mem", call: true}, // arg0=idxHi, arg1=idxLo, arg2=len, arg3=mem, returns memory. AuxInt contains report code (see PanicExtend in genericOps.go). {name: "LoweredPanicExtendC", argLength: 4, aux: "Int64", reg: regInfo{inputs: []regMask{r5, r1, r2}}, typ: "Mem", call: true}, // arg0=idxHi, arg1=idxLo, arg2=len, arg3=mem, returns memory. AuxInt contains report code (see PanicExtend in genericOps.go). } blocks := []blockData{ {name: "EQ", controls: 1}, {name: "NE", controls: 1}, {name: "LTZ", controls: 1}, // < 0 {name: "LEZ", controls: 1}, // <= 0 {name: "GTZ", controls: 1}, // > 0 {name: "GEZ", controls: 1}, // >= 0 {name: "FPT", controls: 1}, // FP flag is true {name: "FPF", controls: 1}, // FP flag is false } archs = append(archs, arch{ name: "MIPS", pkg: "cmd/internal/obj/mips", genfile: "../../mips/ssa.go", ops: ops, blocks: blocks, regnames: regNamesMIPS, gpregmask: gp, fpregmask: fp, specialregmask: hi | lo, framepointerreg: -1, // not used linkreg: int8(num["R31"]), }) }
go/src/cmd/compile/internal/ssa/_gen/MIPSOps.go/0
{ "file_path": "go/src/cmd/compile/internal/ssa/_gen/MIPSOps.go", "repo_id": "go", "token_count": 10919 }
98
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssa import ( "cmd/internal/src" "fmt" "hash/crc32" "internal/buildcfg" "io" "log" "math/rand" "os" "path/filepath" "regexp" "runtime" "sort" "strings" "time" ) // Compile is the main entry point for this package. // Compile modifies f so that on return: // - all Values in f map to 0 or 1 assembly instructions of the target architecture // - the order of f.Blocks is the order to emit the Blocks // - the order of b.Values is the order to emit the Values in each Block // - f has a non-nil regAlloc field func Compile(f *Func) { // TODO: debugging - set flags to control verbosity of compiler, // which phases to dump IR before/after, etc. if f.Log() { f.Logf("compiling %s\n", f.Name) } var rnd *rand.Rand if checkEnabled { seed := int64(crc32.ChecksumIEEE(([]byte)(f.Name))) ^ int64(checkRandSeed) rnd = rand.New(rand.NewSource(seed)) } // hook to print function & phase if panic happens phaseName := "init" defer func() { if phaseName != "" { err := recover() stack := make([]byte, 16384) n := runtime.Stack(stack, false) stack = stack[:n] if f.HTMLWriter != nil { f.HTMLWriter.flushPhases() } f.Fatalf("panic during %s while compiling %s:\n\n%v\n\n%s\n", phaseName, f.Name, err, stack) } }() // Run all the passes if f.Log() { printFunc(f) } f.HTMLWriter.WritePhase("start", "start") if BuildDump[f.Name] { f.dumpFile("build") } if checkEnabled { checkFunc(f) } const logMemStats = false for _, p := range passes { if !f.Config.optimize && !p.required || p.disabled { continue } f.pass = &p phaseName = p.name if f.Log() { f.Logf(" pass %s begin\n", p.name) } // TODO: capture logging during this pass, add it to the HTML var mStart runtime.MemStats if logMemStats || p.mem { runtime.ReadMemStats(&mStart) } if checkEnabled && !f.scheduled { // Test that we don't depend on the value order, by randomizing // the order of values in each block. See issue 18169. for _, b := range f.Blocks { for i := 0; i < len(b.Values)-1; i++ { j := i + rnd.Intn(len(b.Values)-i) b.Values[i], b.Values[j] = b.Values[j], b.Values[i] } } } tStart := time.Now() p.fn(f) tEnd := time.Now() // Need something less crude than "Log the whole intermediate result". if f.Log() || f.HTMLWriter != nil { time := tEnd.Sub(tStart).Nanoseconds() var stats string if logMemStats { var mEnd runtime.MemStats runtime.ReadMemStats(&mEnd) nBytes := mEnd.TotalAlloc - mStart.TotalAlloc nAllocs := mEnd.Mallocs - mStart.Mallocs stats = fmt.Sprintf("[%d ns %d allocs %d bytes]", time, nAllocs, nBytes) } else { stats = fmt.Sprintf("[%d ns]", time) } if f.Log() { f.Logf(" pass %s end %s\n", p.name, stats) printFunc(f) } f.HTMLWriter.WritePhase(phaseName, fmt.Sprintf("%s <span class=\"stats\">%s</span>", phaseName, stats)) } if p.time || p.mem { // Surround timing information w/ enough context to allow comparisons. time := tEnd.Sub(tStart).Nanoseconds() if p.time { f.LogStat("TIME(ns)", time) } if p.mem { var mEnd runtime.MemStats runtime.ReadMemStats(&mEnd) nBytes := mEnd.TotalAlloc - mStart.TotalAlloc nAllocs := mEnd.Mallocs - mStart.Mallocs f.LogStat("TIME(ns):BYTES:ALLOCS", time, nBytes, nAllocs) } } if p.dump != nil && p.dump[f.Name] { // Dump function to appropriately named file f.dumpFile(phaseName) } if checkEnabled { checkFunc(f) } } if f.HTMLWriter != nil { // Ensure we write any pending phases to the html f.HTMLWriter.flushPhases() } if f.ruleMatches != nil { var keys []string for key := range f.ruleMatches { keys = append(keys, key) } sort.Strings(keys) buf := new(strings.Builder) fmt.Fprintf(buf, "%s: ", f.Name) for _, key := range keys { fmt.Fprintf(buf, "%s=%d ", key, f.ruleMatches[key]) } fmt.Fprint(buf, "\n") fmt.Print(buf.String()) } // Squash error printing defer phaseName = "" } // DumpFileForPhase creates a file from the function name and phase name, // warning and returning nil if this is not possible. func (f *Func) DumpFileForPhase(phaseName string) io.WriteCloser { f.dumpFileSeq++ fname := fmt.Sprintf("%s_%02d__%s.dump", f.Name, int(f.dumpFileSeq), phaseName) fname = strings.Replace(fname, " ", "_", -1) fname = strings.Replace(fname, "/", "_", -1) fname = strings.Replace(fname, ":", "_", -1) if ssaDir := os.Getenv("GOSSADIR"); ssaDir != "" { fname = filepath.Join(ssaDir, fname) } fi, err := os.Create(fname) if err != nil { f.Warnl(src.NoXPos, "Unable to create after-phase dump file %s", fname) return nil } return fi } // dumpFile creates a file from the phase name and function name // Dumping is done to files to avoid buffering huge strings before // output. func (f *Func) dumpFile(phaseName string) { fi := f.DumpFileForPhase(phaseName) if fi != nil { p := stringFuncPrinter{w: fi} fprintFunc(p, f) fi.Close() } } type pass struct { name string fn func(*Func) required bool disabled bool time bool // report time to run pass mem bool // report mem stats to run pass stats int // pass reports own "stats" (e.g., branches removed) debug int // pass performs some debugging. =1 should be in error-testing-friendly Warnl format. test int // pass-specific ad-hoc option, perhaps useful in development dump map[string]bool // dump if function name matches } func (p *pass) addDump(s string) { if p.dump == nil { p.dump = make(map[string]bool) } p.dump[s] = true } func (p *pass) String() string { if p == nil { return "nil pass" } return p.name } // Run consistency checker between each phase var ( checkEnabled = false checkRandSeed = 0 ) // Debug output var IntrinsicsDebug int var IntrinsicsDisable bool var BuildDebug int var BuildTest int var BuildStats int var BuildDump map[string]bool = make(map[string]bool) // names of functions to dump after initial build of ssa var GenssaDump map[string]bool = make(map[string]bool) // names of functions to dump after ssa has been converted to asm // PhaseOption sets the specified flag in the specified ssa phase, // returning empty string if this was successful or a string explaining // the error if it was not. // A version of the phase name with "_" replaced by " " is also checked for a match. // If the phase name begins a '~' then the rest of the underscores-replaced-with-blanks // version is used as a regular expression to match the phase name(s). // // Special cases that have turned out to be useful: // - ssa/check/on enables checking after each phase // - ssa/all/time enables time reporting for all phases // // See gc/lex.go for dissection of the option string. // Example uses: // // GO_GCFLAGS=-d=ssa/generic_cse/time,ssa/generic_cse/stats,ssa/generic_cse/debug=3 ./make.bash // // BOOT_GO_GCFLAGS=-d='ssa/~^.*scc$/off' GO_GCFLAGS='-d=ssa/~^.*scc$/off' ./make.bash func PhaseOption(phase, flag string, val int, valString string) string { switch phase { case "", "help": lastcr := 0 phasenames := " check, all, build, intrinsics, genssa" for _, p := range passes { pn := strings.Replace(p.name, " ", "_", -1) if len(pn)+len(phasenames)-lastcr > 70 { phasenames += "\n " lastcr = len(phasenames) phasenames += pn } else { phasenames += ", " + pn } } return `PhaseOptions usage: go tool compile -d=ssa/<phase>/<flag>[=<value>|<function_name>] where: - <phase> is one of: ` + phasenames + ` - <flag> is one of: on, off, debug, mem, time, test, stats, dump, seed - <value> defaults to 1 - <function_name> is required for the "dump" flag, and specifies the name of function to dump after <phase> Phase "all" supports flags "time", "mem", and "dump". Phase "intrinsics" supports flags "on", "off", and "debug". Phase "genssa" (assembly generation) supports the flag "dump". If the "dump" flag is specified, the output is written on a file named <phase>__<function_name>_<seq>.dump; otherwise it is directed to stdout. Examples: -d=ssa/check/on enables checking after each phase -d=ssa/check/seed=1234 enables checking after each phase, using 1234 to seed the PRNG used for value order randomization -d=ssa/all/time enables time reporting for all phases -d=ssa/prove/debug=2 sets debugging level to 2 in the prove pass Be aware that when "/debug=X" is applied to a pass, some passes will emit debug output for all functions, and other passes will only emit debug output for functions that match the current GOSSAFUNC value. Multiple flags can be passed at once, by separating them with commas. For example: -d=ssa/check/on,ssa/all/time ` } if phase == "check" { switch flag { case "on": checkEnabled = val != 0 debugPoset = checkEnabled // also turn on advanced self-checking in prove's data structure return "" case "off": checkEnabled = val == 0 debugPoset = checkEnabled return "" case "seed": checkEnabled = true checkRandSeed = val debugPoset = checkEnabled return "" } } alltime := false allmem := false alldump := false if phase == "all" { switch flag { case "time": alltime = val != 0 case "mem": allmem = val != 0 case "dump": alldump = val != 0 if alldump { BuildDump[valString] = true GenssaDump[valString] = true } default: return fmt.Sprintf("Did not find a flag matching %s in -d=ssa/%s debug option (expected ssa/all/{time,mem,dump=function_name})", flag, phase) } } if phase == "intrinsics" { switch flag { case "on": IntrinsicsDisable = val == 0 case "off": IntrinsicsDisable = val != 0 case "debug": IntrinsicsDebug = val default: return fmt.Sprintf("Did not find a flag matching %s in -d=ssa/%s debug option (expected ssa/intrinsics/{on,off,debug})", flag, phase) } return "" } if phase == "build" { switch flag { case "debug": BuildDebug = val case "test": BuildTest = val case "stats": BuildStats = val case "dump": BuildDump[valString] = true default: return fmt.Sprintf("Did not find a flag matching %s in -d=ssa/%s debug option (expected ssa/build/{debug,test,stats,dump=function_name})", flag, phase) } return "" } if phase == "genssa" { switch flag { case "dump": GenssaDump[valString] = true default: return fmt.Sprintf("Did not find a flag matching %s in -d=ssa/%s debug option (expected ssa/genssa/dump=function_name)", flag, phase) } return "" } underphase := strings.Replace(phase, "_", " ", -1) var re *regexp.Regexp if phase[0] == '~' { r, ok := regexp.Compile(underphase[1:]) if ok != nil { return fmt.Sprintf("Error %s in regexp for phase %s, flag %s", ok.Error(), phase, flag) } re = r } matchedOne := false for i, p := range passes { if phase == "all" { p.time = alltime p.mem = allmem if alldump { p.addDump(valString) } passes[i] = p matchedOne = true } else if p.name == phase || p.name == underphase || re != nil && re.MatchString(p.name) { switch flag { case "on": p.disabled = val == 0 case "off": p.disabled = val != 0 case "time": p.time = val != 0 case "mem": p.mem = val != 0 case "debug": p.debug = val case "stats": p.stats = val case "test": p.test = val case "dump": p.addDump(valString) default: return fmt.Sprintf("Did not find a flag matching %s in -d=ssa/%s debug option", flag, phase) } if p.disabled && p.required { return fmt.Sprintf("Cannot disable required SSA phase %s using -d=ssa/%s debug option", phase, phase) } passes[i] = p matchedOne = true } } if matchedOne { return "" } return fmt.Sprintf("Did not find a phase matching %s in -d=ssa/... debug option", phase) } // list of passes for the compiler var passes = [...]pass{ {name: "number lines", fn: numberLines, required: true}, {name: "early phielim and copyelim", fn: copyelim}, {name: "early deadcode", fn: deadcode}, // remove generated dead code to avoid doing pointless work during opt {name: "short circuit", fn: shortcircuit}, {name: "decompose user", fn: decomposeUser, required: true}, {name: "pre-opt deadcode", fn: deadcode}, {name: "opt", fn: opt, required: true}, // NB: some generic rules know the name of the opt pass. TODO: split required rules and optimizing rules {name: "zero arg cse", fn: zcse, required: true}, // required to merge OpSB values {name: "opt deadcode", fn: deadcode, required: true}, // remove any blocks orphaned during opt {name: "generic cse", fn: cse}, {name: "phiopt", fn: phiopt}, {name: "gcse deadcode", fn: deadcode, required: true}, // clean out after cse and phiopt {name: "nilcheckelim", fn: nilcheckelim}, {name: "prove", fn: prove}, {name: "early fuse", fn: fuseEarly}, {name: "expand calls", fn: expandCalls, required: true}, {name: "decompose builtin", fn: postExpandCallsDecompose, required: true}, {name: "softfloat", fn: softfloat, required: true}, {name: "late opt", fn: opt, required: true}, // TODO: split required rules and optimizing rules {name: "dead auto elim", fn: elimDeadAutosGeneric}, {name: "sccp", fn: sccp}, {name: "generic deadcode", fn: deadcode, required: true}, // remove dead stores, which otherwise mess up store chain {name: "branchelim", fn: branchelim}, {name: "late fuse", fn: fuseLate}, {name: "check bce", fn: checkbce}, {name: "dse", fn: dse}, {name: "memcombine", fn: memcombine}, {name: "writebarrier", fn: writebarrier, required: true}, // expand write barrier ops {name: "insert resched checks", fn: insertLoopReschedChecks, disabled: !buildcfg.Experiment.PreemptibleLoops}, // insert resched checks in loops. {name: "lower", fn: lower, required: true}, {name: "addressing modes", fn: addressingModes, required: false}, {name: "late lower", fn: lateLower, required: true}, {name: "lowered deadcode for cse", fn: deadcode}, // deadcode immediately before CSE avoids CSE making dead values live again {name: "lowered cse", fn: cse}, {name: "elim unread autos", fn: elimUnreadAutos}, {name: "tighten tuple selectors", fn: tightenTupleSelectors, required: true}, {name: "lowered deadcode", fn: deadcode, required: true}, {name: "checkLower", fn: checkLower, required: true}, {name: "late phielim and copyelim", fn: copyelim}, {name: "tighten", fn: tighten, required: true}, // move values closer to their uses {name: "late deadcode", fn: deadcode}, {name: "critical", fn: critical, required: true}, // remove critical edges {name: "phi tighten", fn: phiTighten}, // place rematerializable phi args near uses to reduce value lifetimes {name: "likelyadjust", fn: likelyadjust}, {name: "layout", fn: layout, required: true}, // schedule blocks {name: "schedule", fn: schedule, required: true}, // schedule values {name: "late nilcheck", fn: nilcheckelim2}, {name: "flagalloc", fn: flagalloc, required: true}, // allocate flags register {name: "regalloc", fn: regalloc, required: true}, // allocate int & float registers + stack slots {name: "loop rotate", fn: loopRotate}, {name: "trim", fn: trim}, // remove empty blocks } // Double-check phase ordering constraints. // This code is intended to document the ordering requirements // between different phases. It does not override the passes // list above. type constraint struct { a, b string // a must come before b } var passOrder = [...]constraint{ // "insert resched checks" uses mem, better to clean out stores first. {"dse", "insert resched checks"}, // insert resched checks adds new blocks containing generic instructions {"insert resched checks", "lower"}, {"insert resched checks", "tighten"}, // prove relies on common-subexpression elimination for maximum benefits. {"generic cse", "prove"}, // deadcode after prove to eliminate all new dead blocks. {"prove", "generic deadcode"}, // common-subexpression before dead-store elim, so that we recognize // when two address expressions are the same. {"generic cse", "dse"}, // cse substantially improves nilcheckelim efficacy {"generic cse", "nilcheckelim"}, // allow deadcode to clean up after nilcheckelim {"nilcheckelim", "generic deadcode"}, // nilcheckelim generates sequences of plain basic blocks {"nilcheckelim", "late fuse"}, // nilcheckelim relies on opt to rewrite user nil checks {"opt", "nilcheckelim"}, // tighten will be most effective when as many values have been removed as possible {"generic deadcode", "tighten"}, {"generic cse", "tighten"}, // checkbce needs the values removed {"generic deadcode", "check bce"}, // decompose builtin now also cleans up after expand calls {"expand calls", "decompose builtin"}, // don't run optimization pass until we've decomposed builtin objects {"decompose builtin", "late opt"}, // decompose builtin is the last pass that may introduce new float ops, so run softfloat after it {"decompose builtin", "softfloat"}, // tuple selectors must be tightened to generators and de-duplicated before scheduling {"tighten tuple selectors", "schedule"}, // remove critical edges before phi tighten, so that phi args get better placement {"critical", "phi tighten"}, // don't layout blocks until critical edges have been removed {"critical", "layout"}, // regalloc requires the removal of all critical edges {"critical", "regalloc"}, // regalloc requires all the values in a block to be scheduled {"schedule", "regalloc"}, // the rules in late lower run after the general rules. {"lower", "late lower"}, // late lower may generate some values that need to be CSEed. {"late lower", "lowered cse"}, // checkLower must run after lowering & subsequent dead code elim {"lower", "checkLower"}, {"lowered deadcode", "checkLower"}, {"late lower", "checkLower"}, // late nilcheck needs instructions to be scheduled. {"schedule", "late nilcheck"}, // flagalloc needs instructions to be scheduled. {"schedule", "flagalloc"}, // regalloc needs flags to be allocated first. {"flagalloc", "regalloc"}, // loopRotate will confuse regalloc. {"regalloc", "loop rotate"}, // trim needs regalloc to be done first. {"regalloc", "trim"}, // memcombine works better if fuse happens first, to help merge stores. {"late fuse", "memcombine"}, // memcombine is a arch-independent pass. {"memcombine", "lower"}, } func init() { for _, c := range passOrder { a, b := c.a, c.b i := -1 j := -1 for k, p := range passes { if p.name == a { i = k } if p.name == b { j = k } } if i < 0 { log.Panicf("pass %s not found", a) } if j < 0 { log.Panicf("pass %s not found", b) } if i >= j { log.Panicf("passes %s and %s out of order", a, b) } } }
go/src/cmd/compile/internal/ssa/compile.go/0
{ "file_path": "go/src/cmd/compile/internal/ssa/compile.go", "repo_id": "go", "token_count": 7003 }
99
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssa import ( "cmd/compile/internal/types" "testing" ) func BenchmarkDominatorsLinear(b *testing.B) { benchmarkDominators(b, 10000, genLinear) } func BenchmarkDominatorsFwdBack(b *testing.B) { benchmarkDominators(b, 10000, genFwdBack) } func BenchmarkDominatorsManyPred(b *testing.B) { benchmarkDominators(b, 10000, genManyPred) } func BenchmarkDominatorsMaxPred(b *testing.B) { benchmarkDominators(b, 10000, genMaxPred) } func BenchmarkDominatorsMaxPredVal(b *testing.B) { benchmarkDominators(b, 10000, genMaxPredValue) } type blockGen func(size int) []bloc // genLinear creates an array of blocks that succeed one another // b_n -> [b_n+1]. func genLinear(size int) []bloc { var blocs []bloc blocs = append(blocs, Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Goto(blockn(0)), ), ) for i := 0; i < size; i++ { blocs = append(blocs, Bloc(blockn(i), Goto(blockn(i+1)))) } blocs = append(blocs, Bloc(blockn(size), Goto("exit")), Bloc("exit", Exit("mem")), ) return blocs } // genFwdBack creates an array of blocks that alternate between // b_n -> [b_n+1], b_n -> [b_n+1, b_n-1] , b_n -> [b_n+1, b_n+2] func genFwdBack(size int) []bloc { var blocs []bloc blocs = append(blocs, Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), Goto(blockn(0)), ), ) for i := 0; i < size; i++ { switch i % 2 { case 0: blocs = append(blocs, Bloc(blockn(i), If("p", blockn(i+1), blockn(i+2)))) case 1: blocs = append(blocs, Bloc(blockn(i), If("p", blockn(i+1), blockn(i-1)))) } } blocs = append(blocs, Bloc(blockn(size), Goto("exit")), Bloc("exit", Exit("mem")), ) return blocs } // genManyPred creates an array of blocks where 1/3rd have a successor of the // first block, 1/3rd the last block, and the remaining third are plain. func genManyPred(size int) []bloc { var blocs []bloc blocs = append(blocs, Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), Goto(blockn(0)), ), ) // We want predecessor lists to be long, so 2/3rds of the blocks have a // successor of the first or last block. for i := 0; i < size; i++ { switch i % 3 { case 0: blocs = append(blocs, Bloc(blockn(i), Valu("a", OpConstBool, types.Types[types.TBOOL], 1, nil), Goto(blockn(i+1)))) case 1: blocs = append(blocs, Bloc(blockn(i), Valu("a", OpConstBool, types.Types[types.TBOOL], 1, nil), If("p", blockn(i+1), blockn(0)))) case 2: blocs = append(blocs, Bloc(blockn(i), Valu("a", OpConstBool, types.Types[types.TBOOL], 1, nil), If("p", blockn(i+1), blockn(size)))) } } blocs = append(blocs, Bloc(blockn(size), Goto("exit")), Bloc("exit", Exit("mem")), ) return blocs } // genMaxPred maximizes the size of the 'exit' predecessor list. func genMaxPred(size int) []bloc { var blocs []bloc blocs = append(blocs, Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), Goto(blockn(0)), ), ) for i := 0; i < size; i++ { blocs = append(blocs, Bloc(blockn(i), If("p", blockn(i+1), "exit"))) } blocs = append(blocs, Bloc(blockn(size), Goto("exit")), Bloc("exit", Exit("mem")), ) return blocs } // genMaxPredValue is identical to genMaxPred but contains an // additional value. func genMaxPredValue(size int) []bloc { var blocs []bloc blocs = append(blocs, Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), Goto(blockn(0)), ), ) for i := 0; i < size; i++ { blocs = append(blocs, Bloc(blockn(i), Valu("a", OpConstBool, types.Types[types.TBOOL], 1, nil), If("p", blockn(i+1), "exit"))) } blocs = append(blocs, Bloc(blockn(size), Goto("exit")), Bloc("exit", Exit("mem")), ) return blocs } // sink for benchmark var domBenchRes []*Block func benchmarkDominators(b *testing.B, size int, bg blockGen) { c := testConfig(b) fun := c.Fun("entry", bg(size)...) CheckFunc(fun.f) b.SetBytes(int64(size)) b.ResetTimer() for i := 0; i < b.N; i++ { domBenchRes = dominators(fun.f) } } type domFunc func(f *Func) []*Block // verifyDominators verifies that the dominators of fut (function under test) // as determined by domFn, match the map node->dominator func verifyDominators(t *testing.T, fut fun, domFn domFunc, doms map[string]string) { blockNames := map[*Block]string{} for n, b := range fut.blocks { blockNames[b] = n } calcDom := domFn(fut.f) for n, d := range doms { nblk, ok := fut.blocks[n] if !ok { t.Errorf("invalid block name %s", n) } dblk, ok := fut.blocks[d] if !ok { t.Errorf("invalid block name %s", d) } domNode := calcDom[nblk.ID] switch { case calcDom[nblk.ID] == dblk: calcDom[nblk.ID] = nil continue case calcDom[nblk.ID] != dblk: t.Errorf("expected %s as dominator of %s, found %s", d, n, blockNames[domNode]) default: t.Fatal("unexpected dominator condition") } } for id, d := range calcDom { // If nil, we've already verified it if d == nil { continue } for _, b := range fut.blocks { if int(b.ID) == id { t.Errorf("unexpected dominator of %s for %s", blockNames[d], blockNames[b]) } } } } func TestDominatorsSingleBlock(t *testing.T) { c := testConfig(t) fun := c.Fun("entry", Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Exit("mem"))) doms := map[string]string{} CheckFunc(fun.f) verifyDominators(t, fun, dominators, doms) verifyDominators(t, fun, dominatorsSimple, doms) } func TestDominatorsSimple(t *testing.T) { c := testConfig(t) fun := c.Fun("entry", Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Goto("a")), Bloc("a", Goto("b")), Bloc("b", Goto("c")), Bloc("c", Goto("exit")), Bloc("exit", Exit("mem"))) doms := map[string]string{ "a": "entry", "b": "a", "c": "b", "exit": "c", } CheckFunc(fun.f) verifyDominators(t, fun, dominators, doms) verifyDominators(t, fun, dominatorsSimple, doms) } func TestDominatorsMultPredFwd(t *testing.T) { c := testConfig(t) fun := c.Fun("entry", Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), If("p", "a", "c")), Bloc("a", If("p", "b", "c")), Bloc("b", Goto("c")), Bloc("c", Goto("exit")), Bloc("exit", Exit("mem"))) doms := map[string]string{ "a": "entry", "b": "a", "c": "entry", "exit": "c", } CheckFunc(fun.f) verifyDominators(t, fun, dominators, doms) verifyDominators(t, fun, dominatorsSimple, doms) } func TestDominatorsDeadCode(t *testing.T) { c := testConfig(t) fun := c.Fun("entry", Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 0, nil), If("p", "b3", "b5")), Bloc("b2", Exit("mem")), Bloc("b3", Goto("b2")), Bloc("b4", Goto("b2")), Bloc("b5", Goto("b2"))) doms := map[string]string{ "b2": "entry", "b3": "entry", "b5": "entry", } CheckFunc(fun.f) verifyDominators(t, fun, dominators, doms) verifyDominators(t, fun, dominatorsSimple, doms) } func TestDominatorsMultPredRev(t *testing.T) { c := testConfig(t) fun := c.Fun("entry", Bloc("entry", Goto("first")), Bloc("first", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), Goto("a")), Bloc("a", If("p", "b", "first")), Bloc("b", Goto("c")), Bloc("c", If("p", "exit", "b")), Bloc("exit", Exit("mem"))) doms := map[string]string{ "first": "entry", "a": "first", "b": "a", "c": "b", "exit": "c", } CheckFunc(fun.f) verifyDominators(t, fun, dominators, doms) verifyDominators(t, fun, dominatorsSimple, doms) } func TestDominatorsMultPred(t *testing.T) { c := testConfig(t) fun := c.Fun("entry", Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), If("p", "a", "c")), Bloc("a", If("p", "b", "c")), Bloc("b", Goto("c")), Bloc("c", If("p", "b", "exit")), Bloc("exit", Exit("mem"))) doms := map[string]string{ "a": "entry", "b": "entry", "c": "entry", "exit": "c", } CheckFunc(fun.f) verifyDominators(t, fun, dominators, doms) verifyDominators(t, fun, dominatorsSimple, doms) } func TestInfiniteLoop(t *testing.T) { c := testConfig(t) // note lack of an exit block fun := c.Fun("entry", Bloc("entry", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), Goto("a")), Bloc("a", Goto("b")), Bloc("b", Goto("a"))) CheckFunc(fun.f) doms := map[string]string{"a": "entry", "b": "a"} verifyDominators(t, fun, dominators, doms) } func TestDomTricky(t *testing.T) { doms := map[string]string{ "4": "1", "2": "4", "5": "4", "11": "4", "15": "4", // the incorrect answer is "5" "10": "15", "19": "15", } if4 := [2]string{"2", "5"} if5 := [2]string{"15", "11"} if15 := [2]string{"19", "10"} for i := 0; i < 8; i++ { a := 1 & i b := 1 & i >> 1 c := 1 & i >> 2 cfg := testConfig(t) fun := cfg.Fun("1", Bloc("1", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), Goto("4")), Bloc("2", Goto("11")), Bloc("4", If("p", if4[a], if4[1-a])), // 2, 5 Bloc("5", If("p", if5[b], if5[1-b])), //15, 11 Bloc("10", Exit("mem")), Bloc("11", Goto("15")), Bloc("15", If("p", if15[c], if15[1-c])), //19, 10 Bloc("19", Goto("10"))) CheckFunc(fun.f) verifyDominators(t, fun, dominators, doms) verifyDominators(t, fun, dominatorsSimple, doms) } } // generateDominatorMap uses dominatorsSimple to obtain a // reference dominator tree for testing faster algorithms. func generateDominatorMap(fut fun) map[string]string { blockNames := map[*Block]string{} for n, b := range fut.blocks { blockNames[b] = n } referenceDom := dominatorsSimple(fut.f) doms := make(map[string]string) for _, b := range fut.f.Blocks { if d := referenceDom[b.ID]; d != nil { doms[blockNames[b]] = blockNames[d] } } return doms } func TestDominatorsPostTrickyA(t *testing.T) { testDominatorsPostTricky(t, "b8", "b11", "b10", "b8", "b14", "b15") } func TestDominatorsPostTrickyB(t *testing.T) { testDominatorsPostTricky(t, "b11", "b8", "b10", "b8", "b14", "b15") } func TestDominatorsPostTrickyC(t *testing.T) { testDominatorsPostTricky(t, "b8", "b11", "b8", "b10", "b14", "b15") } func TestDominatorsPostTrickyD(t *testing.T) { testDominatorsPostTricky(t, "b11", "b8", "b8", "b10", "b14", "b15") } func TestDominatorsPostTrickyE(t *testing.T) { testDominatorsPostTricky(t, "b8", "b11", "b10", "b8", "b15", "b14") } func TestDominatorsPostTrickyF(t *testing.T) { testDominatorsPostTricky(t, "b11", "b8", "b10", "b8", "b15", "b14") } func TestDominatorsPostTrickyG(t *testing.T) { testDominatorsPostTricky(t, "b8", "b11", "b8", "b10", "b15", "b14") } func TestDominatorsPostTrickyH(t *testing.T) { testDominatorsPostTricky(t, "b11", "b8", "b8", "b10", "b15", "b14") } func testDominatorsPostTricky(t *testing.T, b7then, b7else, b12then, b12else, b13then, b13else string) { c := testConfig(t) fun := c.Fun("b1", Bloc("b1", Valu("mem", OpInitMem, types.TypeMem, 0, nil), Valu("p", OpConstBool, types.Types[types.TBOOL], 1, nil), If("p", "b3", "b2")), Bloc("b3", If("p", "b5", "b6")), Bloc("b5", Goto("b7")), Bloc("b7", If("p", b7then, b7else)), Bloc("b8", Goto("b13")), Bloc("b13", If("p", b13then, b13else)), Bloc("b14", Goto("b10")), Bloc("b15", Goto("b16")), Bloc("b16", Goto("b9")), Bloc("b9", Goto("b7")), Bloc("b11", Goto("b12")), Bloc("b12", If("p", b12then, b12else)), Bloc("b10", Goto("b6")), Bloc("b6", Goto("b17")), Bloc("b17", Goto("b18")), Bloc("b18", If("p", "b22", "b19")), Bloc("b22", Goto("b23")), Bloc("b23", If("p", "b21", "b19")), Bloc("b19", If("p", "b24", "b25")), Bloc("b24", Goto("b26")), Bloc("b26", Goto("b25")), Bloc("b25", If("p", "b27", "b29")), Bloc("b27", Goto("b30")), Bloc("b30", Goto("b28")), Bloc("b29", Goto("b31")), Bloc("b31", Goto("b28")), Bloc("b28", If("p", "b32", "b33")), Bloc("b32", Goto("b21")), Bloc("b21", Goto("b47")), Bloc("b47", If("p", "b45", "b46")), Bloc("b45", Goto("b48")), Bloc("b48", Goto("b49")), Bloc("b49", If("p", "b50", "b51")), Bloc("b50", Goto("b52")), Bloc("b52", Goto("b53")), Bloc("b53", Goto("b51")), Bloc("b51", Goto("b54")), Bloc("b54", Goto("b46")), Bloc("b46", Exit("mem")), Bloc("b33", Goto("b34")), Bloc("b34", Goto("b37")), Bloc("b37", If("p", "b35", "b36")), Bloc("b35", Goto("b38")), Bloc("b38", Goto("b39")), Bloc("b39", If("p", "b40", "b41")), Bloc("b40", Goto("b42")), Bloc("b42", Goto("b43")), Bloc("b43", Goto("b41")), Bloc("b41", Goto("b44")), Bloc("b44", Goto("b36")), Bloc("b36", Goto("b20")), Bloc("b20", Goto("b18")), Bloc("b2", Goto("b4")), Bloc("b4", Exit("mem"))) CheckFunc(fun.f) doms := generateDominatorMap(fun) verifyDominators(t, fun, dominators, doms) }
go/src/cmd/compile/internal/ssa/dom_test.go/0
{ "file_path": "go/src/cmd/compile/internal/ssa/dom_test.go", "repo_id": "go", "token_count": 6612 }
100
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssa type ID int32 // idAlloc provides an allocator for unique integers. type idAlloc struct { last ID } // get allocates an ID and returns it. IDs are always > 0. func (a *idAlloc) get() ID { x := a.last x++ if x == 1<<31-1 { panic("too many ids for this function") } a.last = x return x } // num returns the maximum ID ever returned + 1. func (a *idAlloc) num() int { return int(a.last + 1) }
go/src/cmd/compile/internal/ssa/id.go/0
{ "file_path": "go/src/cmd/compile/internal/ssa/id.go", "repo_id": "go", "token_count": 199 }
101
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ssa import ( "cmd/compile/internal/abi" "cmd/compile/internal/ir" "cmd/compile/internal/types" "cmd/internal/obj" "fmt" "strings" ) // An Op encodes the specific operation that a Value performs. // Opcodes' semantics can be modified by the type and aux fields of the Value. // For instance, OpAdd can be 32 or 64 bit, signed or unsigned, float or complex, depending on Value.Type. // Semantics of each op are described in the opcode files in _gen/*Ops.go. // There is one file for generic (architecture-independent) ops and one file // for each architecture. type Op int32 type opInfo struct { name string reg regInfo auxType auxType argLen int32 // the number of arguments, -1 if variable length asm obj.As generic bool // this is a generic (arch-independent) opcode rematerializeable bool // this op is rematerializeable commutative bool // this operation is commutative (e.g. addition) resultInArg0 bool // (first, if a tuple) output of v and v.Args[0] must be allocated to the same register resultNotInArgs bool // outputs must not be allocated to the same registers as inputs clobberFlags bool // this op clobbers flags register needIntTemp bool // need a temporary free integer register call bool // is a function call tailCall bool // is a tail call nilCheck bool // this op is a nil check on arg0 faultOnNilArg0 bool // this op will fault if arg0 is nil (and aux encodes a small offset) faultOnNilArg1 bool // this op will fault if arg1 is nil (and aux encodes a small offset) usesScratch bool // this op requires scratch memory space hasSideEffects bool // for "reasons", not to be eliminated. E.g., atomic store, #19182. zeroWidth bool // op never translates into any machine code. example: copy, which may sometimes translate to machine code, is not zero-width. unsafePoint bool // this op is an unsafe point, i.e. not safe for async preemption symEffect SymEffect // effect this op has on symbol in aux scale uint8 // amd64/386 indexed load scale } type inputInfo struct { idx int // index in Args array regs regMask // allowed input registers } type outputInfo struct { idx int // index in output tuple regs regMask // allowed output registers } type regInfo struct { // inputs encodes the register restrictions for an instruction's inputs. // Each entry specifies an allowed register set for a particular input. // They are listed in the order in which regalloc should pick a register // from the register set (most constrained first). // Inputs which do not need registers are not listed. inputs []inputInfo // clobbers encodes the set of registers that are overwritten by // the instruction (other than the output registers). clobbers regMask // outputs is the same as inputs, but for the outputs of the instruction. outputs []outputInfo } func (r *regInfo) String() string { s := "" s += "INS:\n" for _, i := range r.inputs { mask := fmt.Sprintf("%64b", i.regs) mask = strings.Replace(mask, "0", ".", -1) s += fmt.Sprintf("%2d |%s|\n", i.idx, mask) } s += "OUTS:\n" for _, i := range r.outputs { mask := fmt.Sprintf("%64b", i.regs) mask = strings.Replace(mask, "0", ".", -1) s += fmt.Sprintf("%2d |%s|\n", i.idx, mask) } s += "CLOBBERS:\n" mask := fmt.Sprintf("%64b", r.clobbers) mask = strings.Replace(mask, "0", ".", -1) s += fmt.Sprintf(" |%s|\n", mask) return s } type auxType int8 type AuxNameOffset struct { Name *ir.Name Offset int64 } func (a *AuxNameOffset) CanBeAnSSAAux() {} func (a *AuxNameOffset) String() string { return fmt.Sprintf("%s+%d", a.Name.Sym().Name, a.Offset) } func (a *AuxNameOffset) FrameOffset() int64 { return a.Name.FrameOffset() + a.Offset } type AuxCall struct { Fn *obj.LSym reg *regInfo // regInfo for this call abiInfo *abi.ABIParamResultInfo } // Reg returns the regInfo for a given call, combining the derived in/out register masks // with the machine-specific register information in the input i. (The machine-specific // regInfo is much handier at the call site than it is when the AuxCall is being constructed, // therefore do this lazily). // // TODO: there is a Clever Hack that allows pre-generation of a small-ish number of the slices // of inputInfo and outputInfo used here, provided that we are willing to reorder the inputs // and outputs from calls, so that all integer registers come first, then all floating registers. // At this point (active development of register ABI) that is very premature, // but if this turns out to be a cost, we could do it. func (a *AuxCall) Reg(i *regInfo, c *Config) *regInfo { if a.reg.clobbers != 0 { // Already updated return a.reg } if a.abiInfo.InRegistersUsed()+a.abiInfo.OutRegistersUsed() == 0 { // Shortcut for zero case, also handles old ABI. a.reg = i return a.reg } k := len(i.inputs) for _, p := range a.abiInfo.InParams() { for _, r := range p.Registers { m := archRegForAbiReg(r, c) a.reg.inputs = append(a.reg.inputs, inputInfo{idx: k, regs: (1 << m)}) k++ } } a.reg.inputs = append(a.reg.inputs, i.inputs...) // These are less constrained, thus should come last k = len(i.outputs) for _, p := range a.abiInfo.OutParams() { for _, r := range p.Registers { m := archRegForAbiReg(r, c) a.reg.outputs = append(a.reg.outputs, outputInfo{idx: k, regs: (1 << m)}) k++ } } a.reg.outputs = append(a.reg.outputs, i.outputs...) a.reg.clobbers = i.clobbers return a.reg } func (a *AuxCall) ABI() *abi.ABIConfig { return a.abiInfo.Config() } func (a *AuxCall) ABIInfo() *abi.ABIParamResultInfo { return a.abiInfo } func (a *AuxCall) ResultReg(c *Config) *regInfo { if a.abiInfo.OutRegistersUsed() == 0 { return a.reg } if len(a.reg.inputs) > 0 { return a.reg } k := 0 for _, p := range a.abiInfo.OutParams() { for _, r := range p.Registers { m := archRegForAbiReg(r, c) a.reg.inputs = append(a.reg.inputs, inputInfo{idx: k, regs: (1 << m)}) k++ } } return a.reg } // For ABI register index r, returns the (dense) register number used in // SSA backend. func archRegForAbiReg(r abi.RegIndex, c *Config) uint8 { var m int8 if int(r) < len(c.intParamRegs) { m = c.intParamRegs[r] } else { m = c.floatParamRegs[int(r)-len(c.intParamRegs)] } return uint8(m) } // For ABI register index r, returns the register number used in the obj // package (assembler). func ObjRegForAbiReg(r abi.RegIndex, c *Config) int16 { m := archRegForAbiReg(r, c) return c.registers[m].objNum } // ArgWidth returns the amount of stack needed for all the inputs // and outputs of a function or method, including ABI-defined parameter // slots and ABI-defined spill slots for register-resident parameters. // // The name is taken from the types package's ArgWidth(<function type>), // which predated changes to the ABI; this version handles those changes. func (a *AuxCall) ArgWidth() int64 { return a.abiInfo.ArgWidth() } // ParamAssignmentForResult returns the ABI Parameter assignment for result which (indexed 0, 1, etc). func (a *AuxCall) ParamAssignmentForResult(which int64) *abi.ABIParamAssignment { return a.abiInfo.OutParam(int(which)) } // OffsetOfResult returns the SP offset of result which (indexed 0, 1, etc). func (a *AuxCall) OffsetOfResult(which int64) int64 { n := int64(a.abiInfo.OutParam(int(which)).Offset()) return n } // OffsetOfArg returns the SP offset of argument which (indexed 0, 1, etc). // If the call is to a method, the receiver is the first argument (i.e., index 0) func (a *AuxCall) OffsetOfArg(which int64) int64 { n := int64(a.abiInfo.InParam(int(which)).Offset()) return n } // RegsOfResult returns the register(s) used for result which (indexed 0, 1, etc). func (a *AuxCall) RegsOfResult(which int64) []abi.RegIndex { return a.abiInfo.OutParam(int(which)).Registers } // RegsOfArg returns the register(s) used for argument which (indexed 0, 1, etc). // If the call is to a method, the receiver is the first argument (i.e., index 0) func (a *AuxCall) RegsOfArg(which int64) []abi.RegIndex { return a.abiInfo.InParam(int(which)).Registers } // NameOfResult returns the ir.Name of result which (indexed 0, 1, etc). func (a *AuxCall) NameOfResult(which int64) *ir.Name { return a.abiInfo.OutParam(int(which)).Name } // TypeOfResult returns the type of result which (indexed 0, 1, etc). func (a *AuxCall) TypeOfResult(which int64) *types.Type { return a.abiInfo.OutParam(int(which)).Type } // TypeOfArg returns the type of argument which (indexed 0, 1, etc). // If the call is to a method, the receiver is the first argument (i.e., index 0) func (a *AuxCall) TypeOfArg(which int64) *types.Type { return a.abiInfo.InParam(int(which)).Type } // SizeOfResult returns the size of result which (indexed 0, 1, etc). func (a *AuxCall) SizeOfResult(which int64) int64 { return a.TypeOfResult(which).Size() } // SizeOfArg returns the size of argument which (indexed 0, 1, etc). // If the call is to a method, the receiver is the first argument (i.e., index 0) func (a *AuxCall) SizeOfArg(which int64) int64 { return a.TypeOfArg(which).Size() } // NResults returns the number of results. func (a *AuxCall) NResults() int64 { return int64(len(a.abiInfo.OutParams())) } // LateExpansionResultType returns the result type (including trailing mem) // for a call that will be expanded later in the SSA phase. func (a *AuxCall) LateExpansionResultType() *types.Type { var tys []*types.Type for i := int64(0); i < a.NResults(); i++ { tys = append(tys, a.TypeOfResult(i)) } tys = append(tys, types.TypeMem) return types.NewResults(tys) } // NArgs returns the number of arguments (including receiver, if there is one). func (a *AuxCall) NArgs() int64 { return int64(len(a.abiInfo.InParams())) } // String returns "AuxCall{<fn>}" func (a *AuxCall) String() string { var fn string if a.Fn == nil { fn = "AuxCall{nil" // could be interface/closure etc. } else { fn = fmt.Sprintf("AuxCall{%v", a.Fn) } // TODO how much of the ABI should be printed? return fn + "}" } // StaticAuxCall returns an AuxCall for a static call. func StaticAuxCall(sym *obj.LSym, paramResultInfo *abi.ABIParamResultInfo) *AuxCall { if paramResultInfo == nil { panic(fmt.Errorf("Nil paramResultInfo, sym=%v", sym)) } var reg *regInfo if paramResultInfo.InRegistersUsed()+paramResultInfo.OutRegistersUsed() > 0 { reg = &regInfo{} } return &AuxCall{Fn: sym, abiInfo: paramResultInfo, reg: reg} } // InterfaceAuxCall returns an AuxCall for an interface call. func InterfaceAuxCall(paramResultInfo *abi.ABIParamResultInfo) *AuxCall { var reg *regInfo if paramResultInfo.InRegistersUsed()+paramResultInfo.OutRegistersUsed() > 0 { reg = &regInfo{} } return &AuxCall{Fn: nil, abiInfo: paramResultInfo, reg: reg} } // ClosureAuxCall returns an AuxCall for a closure call. func ClosureAuxCall(paramResultInfo *abi.ABIParamResultInfo) *AuxCall { var reg *regInfo if paramResultInfo.InRegistersUsed()+paramResultInfo.OutRegistersUsed() > 0 { reg = &regInfo{} } return &AuxCall{Fn: nil, abiInfo: paramResultInfo, reg: reg} } func (*AuxCall) CanBeAnSSAAux() {} // OwnAuxCall returns a function's own AuxCall. func OwnAuxCall(fn *obj.LSym, paramResultInfo *abi.ABIParamResultInfo) *AuxCall { // TODO if this remains identical to ClosureAuxCall above after new ABI is done, should deduplicate. var reg *regInfo if paramResultInfo.InRegistersUsed()+paramResultInfo.OutRegistersUsed() > 0 { reg = &regInfo{} } return &AuxCall{Fn: fn, abiInfo: paramResultInfo, reg: reg} } const ( auxNone auxType = iota auxBool // auxInt is 0/1 for false/true auxInt8 // auxInt is an 8-bit integer auxInt16 // auxInt is a 16-bit integer auxInt32 // auxInt is a 32-bit integer auxInt64 // auxInt is a 64-bit integer auxInt128 // auxInt represents a 128-bit integer. Always 0. auxUInt8 // auxInt is an 8-bit unsigned integer auxFloat32 // auxInt is a float32 (encoded with math.Float64bits) auxFloat64 // auxInt is a float64 (encoded with math.Float64bits) auxFlagConstant // auxInt is a flagConstant auxCCop // auxInt is a ssa.Op that represents a flags-to-bool conversion (e.g. LessThan) auxNameOffsetInt8 // aux is a &struct{Name ir.Name, Offset int64}; auxInt is index in parameter registers array auxString // aux is a string auxSym // aux is a symbol (a *gc.Node for locals, an *obj.LSym for globals, or nil for none) auxSymOff // aux is a symbol, auxInt is an offset auxSymValAndOff // aux is a symbol, auxInt is a ValAndOff auxTyp // aux is a type auxTypSize // aux is a type, auxInt is a size, must have Aux.(Type).Size() == AuxInt auxCall // aux is a *ssa.AuxCall auxCallOff // aux is a *ssa.AuxCall, AuxInt is int64 param (in+out) size // architecture specific aux types auxARM64BitField // aux is an arm64 bitfield lsb and width packed into auxInt auxS390XRotateParams // aux is a s390x rotate parameters object encoding start bit, end bit and rotate amount auxS390XCCMask // aux is a s390x 4-bit condition code mask auxS390XCCMaskInt8 // aux is a s390x 4-bit condition code mask, auxInt is an int8 immediate auxS390XCCMaskUint8 // aux is a s390x 4-bit condition code mask, auxInt is a uint8 immediate ) // A SymEffect describes the effect that an SSA Value has on the variable // identified by the symbol in its Aux field. type SymEffect int8 const ( SymRead SymEffect = 1 << iota SymWrite SymAddr SymRdWr = SymRead | SymWrite SymNone SymEffect = 0 ) // A Sym represents a symbolic offset from a base register. // Currently a Sym can be one of 3 things: // - a *gc.Node, for an offset from SP (the stack pointer) // - a *obj.LSym, for an offset from SB (the global pointer) // - nil, for no offset type Sym interface { CanBeAnSSASym() CanBeAnSSAAux() } // A ValAndOff is used by the several opcodes. It holds // both a value and a pointer offset. // A ValAndOff is intended to be encoded into an AuxInt field. // The zero ValAndOff encodes a value of 0 and an offset of 0. // The high 32 bits hold a value. // The low 32 bits hold a pointer offset. type ValAndOff int64 func (x ValAndOff) Val() int32 { return int32(int64(x) >> 32) } func (x ValAndOff) Val64() int64 { return int64(x) >> 32 } func (x ValAndOff) Val16() int16 { return int16(int64(x) >> 32) } func (x ValAndOff) Val8() int8 { return int8(int64(x) >> 32) } func (x ValAndOff) Off64() int64 { return int64(int32(x)) } func (x ValAndOff) Off() int32 { return int32(x) } func (x ValAndOff) String() string { return fmt.Sprintf("val=%d,off=%d", x.Val(), x.Off()) } // validVal reports whether the value can be used // as an argument to makeValAndOff. func validVal(val int64) bool { return val == int64(int32(val)) } func makeValAndOff(val, off int32) ValAndOff { return ValAndOff(int64(val)<<32 + int64(uint32(off))) } func (x ValAndOff) canAdd32(off int32) bool { newoff := x.Off64() + int64(off) return newoff == int64(int32(newoff)) } func (x ValAndOff) canAdd64(off int64) bool { newoff := x.Off64() + off return newoff == int64(int32(newoff)) } func (x ValAndOff) addOffset32(off int32) ValAndOff { if !x.canAdd32(off) { panic("invalid ValAndOff.addOffset32") } return makeValAndOff(x.Val(), x.Off()+off) } func (x ValAndOff) addOffset64(off int64) ValAndOff { if !x.canAdd64(off) { panic("invalid ValAndOff.addOffset64") } return makeValAndOff(x.Val(), x.Off()+int32(off)) } // int128 is a type that stores a 128-bit constant. // The only allowed constant right now is 0, so we can cheat quite a bit. type int128 int64 type BoundsKind uint8 const ( BoundsIndex BoundsKind = iota // indexing operation, 0 <= idx < len failed BoundsIndexU // ... with unsigned idx BoundsSliceAlen // 2-arg slicing operation, 0 <= high <= len failed BoundsSliceAlenU // ... with unsigned high BoundsSliceAcap // 2-arg slicing operation, 0 <= high <= cap failed BoundsSliceAcapU // ... with unsigned high BoundsSliceB // 2-arg slicing operation, 0 <= low <= high failed BoundsSliceBU // ... with unsigned low BoundsSlice3Alen // 3-arg slicing operation, 0 <= max <= len failed BoundsSlice3AlenU // ... with unsigned max BoundsSlice3Acap // 3-arg slicing operation, 0 <= max <= cap failed BoundsSlice3AcapU // ... with unsigned max BoundsSlice3B // 3-arg slicing operation, 0 <= high <= max failed BoundsSlice3BU // ... with unsigned high BoundsSlice3C // 3-arg slicing operation, 0 <= low <= high failed BoundsSlice3CU // ... with unsigned low BoundsConvert // conversion to array pointer failed BoundsKindCount ) // boundsABI determines which register arguments a bounds check call should use. For an [a:b:c] slice, we do: // // CMPQ c, cap // JA fail1 // CMPQ b, c // JA fail2 // CMPQ a, b // JA fail3 // // fail1: CALL panicSlice3Acap (c, cap) // fail2: CALL panicSlice3B (b, c) // fail3: CALL panicSlice3C (a, b) // // When we register allocate that code, we want the same register to be used for // the first arg of panicSlice3Acap and the second arg to panicSlice3B. That way, // initializing that register once will satisfy both calls. // That desire ends up dividing the set of bounds check calls into 3 sets. This function // determines which set to use for a given panic call. // The first arg for set 0 should be the second arg for set 1. // The first arg for set 1 should be the second arg for set 2. func boundsABI(b int64) int { switch BoundsKind(b) { case BoundsSlice3Alen, BoundsSlice3AlenU, BoundsSlice3Acap, BoundsSlice3AcapU, BoundsConvert: return 0 case BoundsSliceAlen, BoundsSliceAlenU, BoundsSliceAcap, BoundsSliceAcapU, BoundsSlice3B, BoundsSlice3BU: return 1 case BoundsIndex, BoundsIndexU, BoundsSliceB, BoundsSliceBU, BoundsSlice3C, BoundsSlice3CU: return 2 default: panic("bad BoundsKind") } } // arm64BitField is the GO type of ARM64BitField auxInt. // if x is an ARM64BitField, then width=x&0xff, lsb=(x>>8)&0xff, and // width+lsb<64 for 64-bit variant, width+lsb<32 for 32-bit variant. // the meaning of width and lsb are instruction-dependent. type arm64BitField int16
go/src/cmd/compile/internal/ssa/op.go/0
{ "file_path": "go/src/cmd/compile/internal/ssa/op.go", "repo_id": "go", "token_count": 7301 }
102
// Code generated from _gen/AMD64splitload.rules using 'go generate'; DO NOT EDIT. package ssa func rewriteValueAMD64splitload(v *Value) bool { switch v.Op { case OpAMD64CMPBconstload: return rewriteValueAMD64splitload_OpAMD64CMPBconstload(v) case OpAMD64CMPBconstloadidx1: return rewriteValueAMD64splitload_OpAMD64CMPBconstloadidx1(v) case OpAMD64CMPBload: return rewriteValueAMD64splitload_OpAMD64CMPBload(v) case OpAMD64CMPBloadidx1: return rewriteValueAMD64splitload_OpAMD64CMPBloadidx1(v) case OpAMD64CMPLconstload: return rewriteValueAMD64splitload_OpAMD64CMPLconstload(v) case OpAMD64CMPLconstloadidx1: return rewriteValueAMD64splitload_OpAMD64CMPLconstloadidx1(v) case OpAMD64CMPLconstloadidx4: return rewriteValueAMD64splitload_OpAMD64CMPLconstloadidx4(v) case OpAMD64CMPLload: return rewriteValueAMD64splitload_OpAMD64CMPLload(v) case OpAMD64CMPLloadidx1: return rewriteValueAMD64splitload_OpAMD64CMPLloadidx1(v) case OpAMD64CMPLloadidx4: return rewriteValueAMD64splitload_OpAMD64CMPLloadidx4(v) case OpAMD64CMPQconstload: return rewriteValueAMD64splitload_OpAMD64CMPQconstload(v) case OpAMD64CMPQconstloadidx1: return rewriteValueAMD64splitload_OpAMD64CMPQconstloadidx1(v) case OpAMD64CMPQconstloadidx8: return rewriteValueAMD64splitload_OpAMD64CMPQconstloadidx8(v) case OpAMD64CMPQload: return rewriteValueAMD64splitload_OpAMD64CMPQload(v) case OpAMD64CMPQloadidx1: return rewriteValueAMD64splitload_OpAMD64CMPQloadidx1(v) case OpAMD64CMPQloadidx8: return rewriteValueAMD64splitload_OpAMD64CMPQloadidx8(v) case OpAMD64CMPWconstload: return rewriteValueAMD64splitload_OpAMD64CMPWconstload(v) case OpAMD64CMPWconstloadidx1: return rewriteValueAMD64splitload_OpAMD64CMPWconstloadidx1(v) case OpAMD64CMPWconstloadidx2: return rewriteValueAMD64splitload_OpAMD64CMPWconstloadidx2(v) case OpAMD64CMPWload: return rewriteValueAMD64splitload_OpAMD64CMPWload(v) case OpAMD64CMPWloadidx1: return rewriteValueAMD64splitload_OpAMD64CMPWloadidx1(v) case OpAMD64CMPWloadidx2: return rewriteValueAMD64splitload_OpAMD64CMPWloadidx2(v) } return false } func rewriteValueAMD64splitload_OpAMD64CMPBconstload(v *Value) bool { v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPBconstload {sym} [vo] ptr mem) // cond: vo.Val() == 0 // result: (TESTB x:(MOVBload {sym} [vo.Off()] ptr mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 mem := v_1 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTB) x := b.NewValue0(v.Pos, OpAMD64MOVBload, typ.UInt8) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg2(ptr, mem) v.AddArg2(x, x) return true } // match: (CMPBconstload {sym} [vo] ptr mem) // cond: vo.Val() != 0 // result: (CMPBconst (MOVBload {sym} [vo.Off()] ptr mem) [vo.Val8()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 mem := v_1 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPBconst) v.AuxInt = int8ToAuxInt(vo.Val8()) v0 := b.NewValue0(v.Pos, OpAMD64MOVBload, typ.UInt8) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg2(ptr, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPBconstloadidx1(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPBconstloadidx1 {sym} [vo] ptr idx mem) // cond: vo.Val() == 0 // result: (TESTB x:(MOVBloadidx1 {sym} [vo.Off()] ptr idx mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTB) x := b.NewValue0(v.Pos, OpAMD64MOVBloadidx1, typ.UInt8) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg3(ptr, idx, mem) v.AddArg2(x, x) return true } // match: (CMPBconstloadidx1 {sym} [vo] ptr idx mem) // cond: vo.Val() != 0 // result: (CMPBconst (MOVBloadidx1 {sym} [vo.Off()] ptr idx mem) [vo.Val8()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPBconst) v.AuxInt = int8ToAuxInt(vo.Val8()) v0 := b.NewValue0(v.Pos, OpAMD64MOVBloadidx1, typ.UInt8) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPBload(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPBload {sym} [off] ptr x mem) // result: (CMPB (MOVBload {sym} [off] ptr mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 x := v_1 mem := v_2 v.reset(OpAMD64CMPB) v0 := b.NewValue0(v.Pos, OpAMD64MOVBload, typ.UInt8) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg2(ptr, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPBloadidx1(v *Value) bool { v_3 := v.Args[3] v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPBloadidx1 {sym} [off] ptr idx x mem) // result: (CMPB (MOVBloadidx1 {sym} [off] ptr idx mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 x := v_2 mem := v_3 v.reset(OpAMD64CMPB) v0 := b.NewValue0(v.Pos, OpAMD64MOVBloadidx1, typ.UInt8) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPLconstload(v *Value) bool { v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPLconstload {sym} [vo] ptr mem) // cond: vo.Val() == 0 // result: (TESTL x:(MOVLload {sym} [vo.Off()] ptr mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 mem := v_1 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTL) x := b.NewValue0(v.Pos, OpAMD64MOVLload, typ.UInt32) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg2(ptr, mem) v.AddArg2(x, x) return true } // match: (CMPLconstload {sym} [vo] ptr mem) // cond: vo.Val() != 0 // result: (CMPLconst (MOVLload {sym} [vo.Off()] ptr mem) [vo.Val()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 mem := v_1 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPLconst) v.AuxInt = int32ToAuxInt(vo.Val()) v0 := b.NewValue0(v.Pos, OpAMD64MOVLload, typ.UInt32) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg2(ptr, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPLconstloadidx1(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPLconstloadidx1 {sym} [vo] ptr idx mem) // cond: vo.Val() == 0 // result: (TESTL x:(MOVLloadidx1 {sym} [vo.Off()] ptr idx mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTL) x := b.NewValue0(v.Pos, OpAMD64MOVLloadidx1, typ.UInt32) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg3(ptr, idx, mem) v.AddArg2(x, x) return true } // match: (CMPLconstloadidx1 {sym} [vo] ptr idx mem) // cond: vo.Val() != 0 // result: (CMPLconst (MOVLloadidx1 {sym} [vo.Off()] ptr idx mem) [vo.Val()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPLconst) v.AuxInt = int32ToAuxInt(vo.Val()) v0 := b.NewValue0(v.Pos, OpAMD64MOVLloadidx1, typ.UInt32) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPLconstloadidx4(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPLconstloadidx4 {sym} [vo] ptr idx mem) // cond: vo.Val() == 0 // result: (TESTL x:(MOVLloadidx4 {sym} [vo.Off()] ptr idx mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTL) x := b.NewValue0(v.Pos, OpAMD64MOVLloadidx4, typ.UInt32) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg3(ptr, idx, mem) v.AddArg2(x, x) return true } // match: (CMPLconstloadidx4 {sym} [vo] ptr idx mem) // cond: vo.Val() != 0 // result: (CMPLconst (MOVLloadidx4 {sym} [vo.Off()] ptr idx mem) [vo.Val()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPLconst) v.AuxInt = int32ToAuxInt(vo.Val()) v0 := b.NewValue0(v.Pos, OpAMD64MOVLloadidx4, typ.UInt32) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPLload(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPLload {sym} [off] ptr x mem) // result: (CMPL (MOVLload {sym} [off] ptr mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 x := v_1 mem := v_2 v.reset(OpAMD64CMPL) v0 := b.NewValue0(v.Pos, OpAMD64MOVLload, typ.UInt32) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg2(ptr, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPLloadidx1(v *Value) bool { v_3 := v.Args[3] v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPLloadidx1 {sym} [off] ptr idx x mem) // result: (CMPL (MOVLloadidx1 {sym} [off] ptr idx mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 x := v_2 mem := v_3 v.reset(OpAMD64CMPL) v0 := b.NewValue0(v.Pos, OpAMD64MOVLloadidx1, typ.UInt32) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPLloadidx4(v *Value) bool { v_3 := v.Args[3] v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPLloadidx4 {sym} [off] ptr idx x mem) // result: (CMPL (MOVLloadidx4 {sym} [off] ptr idx mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 x := v_2 mem := v_3 v.reset(OpAMD64CMPL) v0 := b.NewValue0(v.Pos, OpAMD64MOVLloadidx4, typ.UInt32) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPQconstload(v *Value) bool { v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPQconstload {sym} [vo] ptr mem) // cond: vo.Val() == 0 // result: (TESTQ x:(MOVQload {sym} [vo.Off()] ptr mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 mem := v_1 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTQ) x := b.NewValue0(v.Pos, OpAMD64MOVQload, typ.UInt64) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg2(ptr, mem) v.AddArg2(x, x) return true } // match: (CMPQconstload {sym} [vo] ptr mem) // cond: vo.Val() != 0 // result: (CMPQconst (MOVQload {sym} [vo.Off()] ptr mem) [vo.Val()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 mem := v_1 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPQconst) v.AuxInt = int32ToAuxInt(vo.Val()) v0 := b.NewValue0(v.Pos, OpAMD64MOVQload, typ.UInt64) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg2(ptr, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPQconstloadidx1(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPQconstloadidx1 {sym} [vo] ptr idx mem) // cond: vo.Val() == 0 // result: (TESTQ x:(MOVQloadidx1 {sym} [vo.Off()] ptr idx mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTQ) x := b.NewValue0(v.Pos, OpAMD64MOVQloadidx1, typ.UInt64) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg3(ptr, idx, mem) v.AddArg2(x, x) return true } // match: (CMPQconstloadidx1 {sym} [vo] ptr idx mem) // cond: vo.Val() != 0 // result: (CMPQconst (MOVQloadidx1 {sym} [vo.Off()] ptr idx mem) [vo.Val()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPQconst) v.AuxInt = int32ToAuxInt(vo.Val()) v0 := b.NewValue0(v.Pos, OpAMD64MOVQloadidx1, typ.UInt64) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPQconstloadidx8(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPQconstloadidx8 {sym} [vo] ptr idx mem) // cond: vo.Val() == 0 // result: (TESTQ x:(MOVQloadidx8 {sym} [vo.Off()] ptr idx mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTQ) x := b.NewValue0(v.Pos, OpAMD64MOVQloadidx8, typ.UInt64) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg3(ptr, idx, mem) v.AddArg2(x, x) return true } // match: (CMPQconstloadidx8 {sym} [vo] ptr idx mem) // cond: vo.Val() != 0 // result: (CMPQconst (MOVQloadidx8 {sym} [vo.Off()] ptr idx mem) [vo.Val()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPQconst) v.AuxInt = int32ToAuxInt(vo.Val()) v0 := b.NewValue0(v.Pos, OpAMD64MOVQloadidx8, typ.UInt64) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPQload(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPQload {sym} [off] ptr x mem) // result: (CMPQ (MOVQload {sym} [off] ptr mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 x := v_1 mem := v_2 v.reset(OpAMD64CMPQ) v0 := b.NewValue0(v.Pos, OpAMD64MOVQload, typ.UInt64) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg2(ptr, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPQloadidx1(v *Value) bool { v_3 := v.Args[3] v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPQloadidx1 {sym} [off] ptr idx x mem) // result: (CMPQ (MOVQloadidx1 {sym} [off] ptr idx mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 x := v_2 mem := v_3 v.reset(OpAMD64CMPQ) v0 := b.NewValue0(v.Pos, OpAMD64MOVQloadidx1, typ.UInt64) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPQloadidx8(v *Value) bool { v_3 := v.Args[3] v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPQloadidx8 {sym} [off] ptr idx x mem) // result: (CMPQ (MOVQloadidx8 {sym} [off] ptr idx mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 x := v_2 mem := v_3 v.reset(OpAMD64CMPQ) v0 := b.NewValue0(v.Pos, OpAMD64MOVQloadidx8, typ.UInt64) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPWconstload(v *Value) bool { v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPWconstload {sym} [vo] ptr mem) // cond: vo.Val() == 0 // result: (TESTW x:(MOVWload {sym} [vo.Off()] ptr mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 mem := v_1 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTW) x := b.NewValue0(v.Pos, OpAMD64MOVWload, typ.UInt16) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg2(ptr, mem) v.AddArg2(x, x) return true } // match: (CMPWconstload {sym} [vo] ptr mem) // cond: vo.Val() != 0 // result: (CMPWconst (MOVWload {sym} [vo.Off()] ptr mem) [vo.Val16()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 mem := v_1 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPWconst) v.AuxInt = int16ToAuxInt(vo.Val16()) v0 := b.NewValue0(v.Pos, OpAMD64MOVWload, typ.UInt16) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg2(ptr, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPWconstloadidx1(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPWconstloadidx1 {sym} [vo] ptr idx mem) // cond: vo.Val() == 0 // result: (TESTW x:(MOVWloadidx1 {sym} [vo.Off()] ptr idx mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTW) x := b.NewValue0(v.Pos, OpAMD64MOVWloadidx1, typ.UInt16) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg3(ptr, idx, mem) v.AddArg2(x, x) return true } // match: (CMPWconstloadidx1 {sym} [vo] ptr idx mem) // cond: vo.Val() != 0 // result: (CMPWconst (MOVWloadidx1 {sym} [vo.Off()] ptr idx mem) [vo.Val16()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPWconst) v.AuxInt = int16ToAuxInt(vo.Val16()) v0 := b.NewValue0(v.Pos, OpAMD64MOVWloadidx1, typ.UInt16) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPWconstloadidx2(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPWconstloadidx2 {sym} [vo] ptr idx mem) // cond: vo.Val() == 0 // result: (TESTW x:(MOVWloadidx2 {sym} [vo.Off()] ptr idx mem) x) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() == 0) { break } v.reset(OpAMD64TESTW) x := b.NewValue0(v.Pos, OpAMD64MOVWloadidx2, typ.UInt16) x.AuxInt = int32ToAuxInt(vo.Off()) x.Aux = symToAux(sym) x.AddArg3(ptr, idx, mem) v.AddArg2(x, x) return true } // match: (CMPWconstloadidx2 {sym} [vo] ptr idx mem) // cond: vo.Val() != 0 // result: (CMPWconst (MOVWloadidx2 {sym} [vo.Off()] ptr idx mem) [vo.Val16()]) for { vo := auxIntToValAndOff(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 mem := v_2 if !(vo.Val() != 0) { break } v.reset(OpAMD64CMPWconst) v.AuxInt = int16ToAuxInt(vo.Val16()) v0 := b.NewValue0(v.Pos, OpAMD64MOVWloadidx2, typ.UInt16) v0.AuxInt = int32ToAuxInt(vo.Off()) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg(v0) return true } return false } func rewriteValueAMD64splitload_OpAMD64CMPWload(v *Value) bool { v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPWload {sym} [off] ptr x mem) // result: (CMPW (MOVWload {sym} [off] ptr mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 x := v_1 mem := v_2 v.reset(OpAMD64CMPW) v0 := b.NewValue0(v.Pos, OpAMD64MOVWload, typ.UInt16) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg2(ptr, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPWloadidx1(v *Value) bool { v_3 := v.Args[3] v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPWloadidx1 {sym} [off] ptr idx x mem) // result: (CMPW (MOVWloadidx1 {sym} [off] ptr idx mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 x := v_2 mem := v_3 v.reset(OpAMD64CMPW) v0 := b.NewValue0(v.Pos, OpAMD64MOVWloadidx1, typ.UInt16) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg2(v0, x) return true } } func rewriteValueAMD64splitload_OpAMD64CMPWloadidx2(v *Value) bool { v_3 := v.Args[3] v_2 := v.Args[2] v_1 := v.Args[1] v_0 := v.Args[0] b := v.Block typ := &b.Func.Config.Types // match: (CMPWloadidx2 {sym} [off] ptr idx x mem) // result: (CMPW (MOVWloadidx2 {sym} [off] ptr idx mem) x) for { off := auxIntToInt32(v.AuxInt) sym := auxToSym(v.Aux) ptr := v_0 idx := v_1 x := v_2 mem := v_3 v.reset(OpAMD64CMPW) v0 := b.NewValue0(v.Pos, OpAMD64MOVWloadidx2, typ.UInt16) v0.AuxInt = int32ToAuxInt(off) v0.Aux = symToAux(sym) v0.AddArg3(ptr, idx, mem) v.AddArg2(v0, x) return true } } func rewriteBlockAMD64splitload(b *Block) bool { return false }
go/src/cmd/compile/internal/ssa/rewriteAMD64splitload.go/0
{ "file_path": "go/src/cmd/compile/internal/ssa/rewriteAMD64splitload.go", "repo_id": "go", "token_count": 11442 }
103