github.com/llir/llvm@v0.3.6/ir/constant/const_vector.go (about)

     1  package constant
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/llir/llvm/ir/types"
     8  )
     9  
    10  // --- [ Vector constants ] ----------------------------------------------------
    11  
    12  // Vector is an LLVM IR vector constant.
    13  type Vector struct {
    14  	// Vector type.
    15  	Typ *types.VectorType
    16  	// Vector elements.
    17  	Elems []Constant
    18  }
    19  
    20  // NewVector returns a new vector constant based on the given vector type and
    21  // elements. The vector type is infered from the type of the elements if t is
    22  // nil.
    23  func NewVector(t *types.VectorType, elems ...Constant) *Vector {
    24  	c := &Vector{
    25  		Elems: elems,
    26  		Typ:   t,
    27  	}
    28  	// Compute type.
    29  	c.Type()
    30  	return c
    31  }
    32  
    33  // String returns the LLVM syntax representation of the constant as a type-value
    34  // pair.
    35  func (c *Vector) String() string {
    36  	return fmt.Sprintf("%s %s", c.Type(), c.Ident())
    37  }
    38  
    39  // Type returns the type of the constant.
    40  func (c *Vector) Type() types.Type {
    41  	// Cache type if not present.
    42  	if c.Typ == nil {
    43  		elemType := c.Elems[0].Type()
    44  		c.Typ = types.NewVector(uint64(len(c.Elems)), elemType)
    45  	}
    46  	return c.Typ
    47  }
    48  
    49  // Ident returns the identifier associated with the constant.
    50  func (c *Vector) Ident() string {
    51  	// '<' Elems=(TypeConst separator ',')* '>'
    52  	buf := &strings.Builder{}
    53  	buf.WriteString("<")
    54  	for i, elem := range c.Elems {
    55  		if i != 0 {
    56  			buf.WriteString(", ")
    57  		}
    58  		buf.WriteString(elem.String())
    59  	}
    60  	buf.WriteString(">")
    61  	return buf.String()
    62  }