llvm.org GIT mirror llvm / fdfeb69
Add support for a union type in LLVM IR. Patch by Talin! git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@96011 91177308-0d34-0410-b5e6-96231b3b80d8 Chris Lattner 10 years ago
24 changed file(s) with 614 addition(s) and 61 deletion(s). Raw diff Collapse all Expand all
6565
6666
  • Derived Types
  • 6767
    68
  • Array Type>
  • 68
  • Aggregate Types>
  • 69
    70
  • Array Type
  • 71
  • Structure Type
  • 72
  • Packed Structure Type
  • 73
  • Union Type
  • 74
  • Vector Type
  • 75
    76
    6977
  • Function Type
  • 7078
  • Pointer Type
  • 71
  • Structure Type
  • 72
  • Packed Structure Type
  • 73
  • Vector Type
  • 7479
  • Opaque Type
  • 7580
    7681
    14031408 pointer,
    14041409 vector,
    14051410 structure,
    1411 union,
    14061412 array,
    14071413 label,
    14081414 metadata.
    14171423
    14181424
    14191425 derived
    1420 integer,
    1421 array,
    1426 array,
    14221427 function,
    14231428 pointer,
    14241429 structure,
    14251430 packed structure,
    1431 union,
    14261432 vector,
    14271433 opaque.
    14281434
    15591565 may be a primitive type, or another derived type. For example, it is
    15601566 possible to have a two dimensional array, using an array as the element type
    15611567 of another array.

    1568
    1569
    1570
    1571
    1572
    1573
    1574
    1575
    1576
    1577

    Aggregate Types are a subset of derived types that can contain multiple

    1578 member types. Arrays,
    1579 structs, vectors and
    1580 unions are aggregate types.

    1581
    1582
    15621583
    15631584
    15641585
    16281649
    Overview:
    16291650

    The function type can be thought of as a function signature. It consists of

    16301651 a return type and a list of formal parameter types. The return type of a
    1631 function type is a scalar type, a void type, or a struct type. If the return
    1632 type is a struct type then all struct elements must be of first class types,
    1633 and the struct must have at least one element.

    1652 function type is a scalar type, a void type, a struct type, or a union
    1653 type. If the return type is a struct type then all struct elements must be
    1654 of first class types, and the struct must have at least one element.

    16341655
    16351656
    Syntax:
    16361657
    
                      
                    
    17531774
    17541775
    17551776
    1777
    1778
    1779
    1780
    1781
    Overview:
    1782

    A union type describes an object with size and alignment suitable for

    1783 an object of any one of a given set of types (also known as an "untagged"
    1784 union). It is similar in concept and usage to a
    1785 struct, except that all members of the union
    1786 have an offset of zero. The elements of a union may be any type that has a
    1787 size. Unions must have at least one member - empty unions are not allowed.
    1788

    1789
    1790

    The size of the union as a whole will be the size of its largest member,

    1791 and the alignment requirements of the union as a whole will be the largest
    1792 alignment requirement of any member.

    1793
    1794

    Unions members are accessed using 'load and

    1795 'store' by getting a pointer to a field with
    1796 the 'getelementptr' instruction.
    1797 Since all members are at offset zero, the getelementptr instruction does
    1798 not affect the address, only the type of the resulting pointer.

    1799
    1800
    Syntax:
    1801
    
                      
                    
    1802 union { <type list> }
    1803
    1804
    1805
    Examples:
    1806
    1807
    1808 union { i32, i32*, float }
    1809 A union of three types: an i32, a pointer to
    1810 an i32, and a float.
    1811
    1812
    1813 union { float, i32 (i32) * }
    1814 A union, where the first element is a float and the
    1815 second element is a pointer to a
    1816 function that takes an i32, returning
    1817 an i32.
    1818
    1819
    1820
    1821
    1822
    1823
    17561824
    17571825
    17581826
    19902058 the number and types of elements must match those specified by the
    19912059 type.
    19922060
    2061
    Union constants
    2062
    Union constants are represented with notation similar to a structure with
    2063 a single element - that is, a single typed element surrounded
    2064 by braces ({})). For example: "{ i32 4 }". The
    2065 union type can be initialized with a single-element
    2066 struct as long as the type of the struct element matches the type of
    2067 one of the union members.
    2068
    19932069
    Array constants
    19942070
    Array constants are represented with notation similar to array type
    19952071 definitions (a comma separated list of elements, surrounded by square
    20082084
    20092085
    Zero initialization
    20102086
    The string 'zeroinitializer' can be used to zero initialize a
    2011 value to zero of any type, including scalar and aggregate types.
    2087 value to zero of any type, including scalar and
    2088 aggregate types.
    20122089 This is often used to avoid having to print large zero initializers
    20132090 (e.g. for large arrays) and is always exactly equivalent to using explicit
    20142091 zero initializers.
    38443921
    38453922
    38463923
    3847

    LLVM supports several instructions for working with aggregate values.

    3924

    LLVM supports several instructions for working with

    3925 aggregate values.

    38483926
    38493927
    38503928
    38613939
    38623940
    38633941
    Overview:
    3864

    The 'extractvalue' instruction extracts the value of a struct field

    3865 or array element from an aggregate value.

    3942

    The 'extractvalue' instruction extracts the value of a member field

    3943 from an aggregate value.

    38663944
    38673945
    Arguments:
    38683946

    The first operand of an 'extractvalue' instruction is a value

    3869 of struct or array type. The
    3870 operands are constant indices to specify which value to extract in a similar
    3871 manner as indices in a
    3947 of struct, union or
    3948 array type. The operands are constant indices to
    3949 specify which value to extract in a similar manner as indices in a
    38723950 'getelementptr' instruction.

    38733951
    38743952
    Semantics:
    38953973
    38963974
    38973975
    Overview:
    3898

    The 'insertvalue' instruction inserts a value into a struct field or

    3899 array element in an aggregate.

    3900
    3976

    The 'insertvalue' instruction inserts a value into a member field

    3977 in an aggregate value.

    39013978
    39023979
    Arguments:
    39033980

    The first operand of an 'insertvalue' instruction is a value

    3904 of struct or array type. The
    3905 second operand is a first-class value to insert. The following operands are
    3906 constant indices indicating the position at which to insert the value in a
    3907 similar manner as indices in a
    3981 of struct, union or
    3982 array type. The second operand is a first-class
    3983 value to insert. The following operands are constant indices indicating
    3984 the position at which to insert the value in a similar manner as indices in a
    39083985 'getelementptr' instruction. The
    39093986 value to insert must have the same type as the value identified by the
    39103987 indices.

    41064183
    41074184
    Overview:
    41084185

    The 'getelementptr' instruction is used to get the address of a

    4109 subelement of an aggregate data structure. It performs address calculation
    4110 only and does not access memory.

    4186 subelement of an aggregate data structure.
    4187 It performs address calculation only and does not access memory.

    41114188
    41124189
    Arguments:
    41134190

    The first argument is always a pointer, and forms the basis of the

    41174194 indexes the pointer value given as the first argument, the second index
    41184195 indexes a value of the type pointed to (not necessarily the value directly
    41194196 pointed to, since the first index can be non-zero), etc. The first type
    4120 indexed into must be a pointer value, subsequent types can be arrays, vectors
    4121 and structs. Note that subsequent types being indexed into can never be
    4122 pointers, since that would require loading the pointer before continuing
    4123 calculation.

    4197 indexed into must be a pointer value, subsequent types can be arrays,
    4198 vectors, structs and unions. Note that subsequent types being indexed into
    4199 can never be pointers, since that would require loading the pointer before
    4200 continuing calculation.

    41244201
    41254202

    The type of each index argument depends on the type it is indexing into.

    4126 When indexing into a (optionally packed) structure, only i32 integer
    4127 constants are allowed. When indexing into an array, pointer or
    4128 vector, integers of any width are allowed, and they are not required to be
    4203 When indexing into a (optionally packed) structure or union, only i32
    4204 integer constants are allowed. When indexing into an array, pointer
    4205 or vector, integers of any width are allowed, and they are not required to be
    41294206 constant.

    41304207
    41314208

    For example, let's consider a C code fragment and how it gets compiled to

    9393 TYPE_CODE_FP128 = 14, // LONG DOUBLE (112 bit mantissa)
    9494 TYPE_CODE_PPC_FP128= 15, // PPC LONG DOUBLE (2 doubles)
    9595
    96 TYPE_CODE_METADATA = 16 // METADATA
    96 TYPE_CODE_METADATA = 16, // METADATA
    97 TYPE_CODE_UNION = 17 // UNION: [eltty x N]
    9798 };
    9899
    99100 // The type symbol table only has one code (TST_ENTRY_CODE).
    3232 class ArrayType;
    3333 class IntegerType;
    3434 class StructType;
    35 class UnionType;
    3536 class PointerType;
    3637 class VectorType;
    3738
    450451 };
    451452
    452453 DEFINE_TRANSPARENT_CASTED_OPERAND_ACCESSORS(ConstantStruct, Constant)
    454
    455 //===----------------------------------------------------------------------===//
    456 // ConstantUnion - Constant Union Declarations
    457 //
    458 class ConstantUnion : public Constant {
    459 friend struct ConstantCreator;
    460 ConstantUnion(const ConstantUnion &); // DO NOT IMPLEMENT
    461 protected:
    462 ConstantUnion(const UnionType *T, Constant* Val);
    463 public:
    464 // ConstantUnion accessors
    465 static Constant *get(const UnionType *T, Constant* V);
    466
    467 /// Transparently provide more efficient getOperand methods.
    468 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant);
    469
    470 /// getType() specialization - Reduce amount of casting...
    471 ///
    472 inline const UnionType *getType() const {
    473 return reinterpret_cast(Value::getType());
    474 }
    475
    476 /// isNullValue - Return true if this is the value that would be returned by
    477 /// getNullValue. This always returns false because zero structs are always
    478 /// created as ConstantAggregateZero objects.
    479 virtual bool isNullValue() const {
    480 return false;
    481 }
    482
    483 virtual void destroyConstant();
    484 virtual void replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U);
    485
    486 /// Methods for support type inquiry through isa, cast, and dyn_cast:
    487 static inline bool classof(const ConstantUnion *) { return true; }
    488 static bool classof(const Value *V) {
    489 return V->getValueID() == ConstantUnionVal;
    490 }
    491 };
    492
    493 template <>
    494 struct OperandTraits : public FixedNumOperandTraits<1> {
    495 };
    496
    497 DEFINE_TRANSPARENT_CASTED_OPERAND_ACCESSORS(ConstantUnion, Constant)
    453498
    454499 //===----------------------------------------------------------------------===//
    455500 /// ConstantVector - Constant Vector Declarations
    2626 class FunctionValType;
    2727 class ArrayValType;
    2828 class StructValType;
    29 class UnionValType;
    2930 class PointerValType;
    3031 class VectorValType;
    3132 class IntegerValType;
    228229 return T->getTypeID() == ArrayTyID ||
    229230 T->getTypeID() == StructTyID ||
    230231 T->getTypeID() == PointerTyID ||
    231 T->getTypeID() == VectorTyID;
    232 T->getTypeID() == VectorTyID ||
    233 T->getTypeID() == UnionTyID;
    232234 }
    233235 };
    234236
    297299 }
    298300
    299301 bool isPacked() const { return (0 != getSubclassData()) ? true : false; }
    302 };
    303
    304
    305 /// UnionType - Class to represent union types. A union type is similar to
    306 /// a structure, except that all member fields begin at offset 0.
    307 ///
    308 class UnionType : public CompositeType {
    309 friend class TypeMap;
    310 UnionType(const UnionType &); // Do not implement
    311 const UnionType &operator=(const UnionType &); // Do not implement
    312 UnionType(LLVMContext &C, const Type* const* Types, unsigned NumTypes);
    313 public:
    314 /// UnionType::get - This static method is the primary way to create a
    315 /// UnionType.
    316 static UnionType *get(const Type* const* Types, unsigned NumTypes);
    317
    318 /// UnionType::get - This static method is a convenience method for
    319 /// creating union types by specifying the elements as arguments.
    320 static UnionType *get(const Type *type, ...) END_WITH_NULL;
    321
    322 /// isValidElementType - Return true if the specified type is valid as a
    323 /// element type.
    324 static bool isValidElementType(const Type *ElemTy);
    325
    326 /// Given an element type, return the member index of that type, or -1
    327 /// if there is no such member type.
    328 int getElementTypeIndex(const Type *ElemTy) const;
    329
    330 // Iterator access to the elements
    331 typedef Type::subtype_iterator element_iterator;
    332 element_iterator element_begin() const { return ContainedTys; }
    333 element_iterator element_end() const { return &ContainedTys[NumContainedTys];}
    334
    335 // Random access to the elements
    336 unsigned getNumElements() const { return NumContainedTys; }
    337 const Type *getElementType(unsigned N) const {
    338 assert(N < NumContainedTys && "Element number out of range!");
    339 return ContainedTys[N];
    340 }
    341
    342 /// getTypeAtIndex - Given an index value into the type, return the type of
    343 /// the element. For a union type, this must be a constant value...
    344 ///
    345 virtual const Type *getTypeAtIndex(const Value *V) const;
    346 virtual const Type *getTypeAtIndex(unsigned Idx) const;
    347 virtual bool indexValid(const Value *V) const;
    348 virtual bool indexValid(unsigned Idx) const;
    349
    350 // Implement the AbstractTypeUser interface.
    351 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
    352 virtual void typeBecameConcrete(const DerivedType *AbsTy);
    353
    354 // Methods for support type inquiry through isa, cast, and dyn_cast:
    355 static inline bool classof(const UnionType *) { return true; }
    356 static inline bool classof(const Type *T) {
    357 return T->getTypeID() == UnionTyID;
    358 }
    300359 };
    301360
    302361
    8181 IntegerTyID, ///< 8: Arbitrary bit width integers
    8282 FunctionTyID, ///< 9: Functions
    8383 StructTyID, ///< 10: Structures
    84 ArrayTyID, ///< 11: Arrays
    85 PointerTyID, ///< 12: Pointers
    86 OpaqueTyID, ///< 13: Opaque: type with unknown structure
    87 VectorTyID, ///< 14: SIMD 'packed' format, or other vector type
    84 UnionTyID, ///< 11: Unions
    85 ArrayTyID, ///< 12: Arrays
    86 PointerTyID, ///< 13: Pointers
    87 OpaqueTyID, ///< 14: Opaque: type with unknown structure
    88 VectorTyID, ///< 15: SIMD 'packed' format, or other vector type
    8889
    8990 NumTypeIDs, // Must remain as last defined ID
    9091 LastPrimitiveTyID = LabelTyID,
    296297 /// does not include vector types.
    297298 ///
    298299 inline bool isAggregateType() const {
    299 return ID == StructTyID || ID == ArrayTyID;
    300 return ID == StructTyID || ID == ArrayTyID || ID == UnionTyID;
    300301 }
    301302
    302303 /// isSized - Return true if it makes sense to take the size of this type. To
    309310 return true;
    310311 // If it is not something that can have a size (e.g. a function or label),
    311312 // it doesn't have a size.
    312 if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID)
    313 if (ID != StructTyID && ID != ArrayTyID && ID != VectorTyID &&
    314 ID != UnionTyID)
    313315 return false;
    314316 // If it is something that can have a size and it's concrete, it definitely
    315317 // has a size, otherwise we have to try harder to decide.
    214214 ConstantFPVal, // This is an instance of ConstantFP
    215215 ConstantArrayVal, // This is an instance of ConstantArray
    216216 ConstantStructVal, // This is an instance of ConstantStruct
    217 ConstantUnionVal, // This is an instance of ConstantUnion
    217218 ConstantVectorVal, // This is an instance of ConstantVector
    218219 ConstantPointerNullVal, // This is an instance of ConstantPointerNull
    219220 MDNodeVal, // This is an instance of MDNode
    192192 LLVMPointerTypeKind, /**< Pointers */
    193193 LLVMOpaqueTypeKind, /**< Opaque: type with unknown structure */
    194194 LLVMVectorTypeKind, /**< SIMD 'packed' format, or other vector type */
    195 LLVMMetadataTypeKind /**< Metadata */
    195 LLVMMetadataTypeKind, /**< Metadata */
    196 LLVMUnionTypeKind /**< Unions */
    196197 } LLVMTypeKind;
    197198
    198199 typedef enum {
    370371 unsigned LLVMCountStructElementTypes(LLVMTypeRef StructTy);
    371372 void LLVMGetStructElementTypes(LLVMTypeRef StructTy, LLVMTypeRef *Dest);
    372373 LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy);
    374
    375 /* Operations on union types */
    376 LLVMTypeRef LLVMUnionTypeInContext(LLVMContextRef C, LLVMTypeRef *ElementTypes,
    377 unsigned ElementCount);
    378 LLVMTypeRef LLVMUnionType(LLVMTypeRef *ElementTypes, unsigned ElementCount);
    379 unsigned LLVMCountUnionElementTypes(LLVMTypeRef UnionTy);
    380 void LLVMGetUnionElementTypes(LLVMTypeRef UnionTy, LLVMTypeRef *Dest);
    373381
    374382 /* Operations on array, pointer, and vector types (sequence types) */
    375383 LLVMTypeRef LLVMArrayType(LLVMTypeRef ElementType, unsigned ElementCount);
    569569
    570570 KEYWORD(type);
    571571 KEYWORD(opaque);
    572 KEYWORD(union);
    572573
    573574 KEYWORD(eq); KEYWORD(ne); KEYWORD(slt); KEYWORD(sgt); KEYWORD(sle);
    574575 KEYWORD(sge); KEYWORD(ult); KEYWORD(ugt); KEYWORD(ule); KEYWORD(uge);
    12941294 if (ParseStructType(Result, false))
    12951295 return true;
    12961296 break;
    1297 case lltok::kw_union:
    1298 // TypeRec ::= 'union' '{' ... '}'
    1299 if (ParseUnionType(Result))
    1300 return true;
    1301 break;
    12971302 case lltok::lsquare:
    12981303 // TypeRec ::= '[' ... ']'
    12991304 Lex.Lex(); // eat the lsquare.
    16001605 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
    16011606 ParamsListTy.push_back(ParamsList[i].get());
    16021607 Result = HandleUpRefs(StructType::get(Context, ParamsListTy, Packed));
    1608 return false;
    1609 }
    1610
    1611 /// ParseUnionType
    1612 /// TypeRec
    1613 /// ::= 'union' '{' TypeRec (',' TypeRec)* '}'
    1614 bool LLParser::ParseUnionType(PATypeHolder &Result) {
    1615 assert(Lex.getKind() == lltok::kw_union);
    1616 Lex.Lex(); // Consume the 'union'
    1617
    1618 if (ParseToken(lltok::lbrace, "'{' expected after 'union'")) return true;
    1619
    1620 SmallVector ParamsList;
    1621 do {
    1622 LocTy EltTyLoc = Lex.getLoc();
    1623 if (ParseTypeRec(Result)) return true;
    1624 ParamsList.push_back(Result);
    1625
    1626 if (Result->isVoidTy())
    1627 return Error(EltTyLoc, "union element can not have void type");
    1628 if (!UnionType::isValidElementType(Result))
    1629 return Error(EltTyLoc, "invalid element type for union");
    1630
    1631 } while (EatIfPresent(lltok::comma)) ;
    1632
    1633 if (ParseToken(lltok::rbrace, "expected '}' at end of union"))
    1634 return true;
    1635
    1636 SmallVector ParamsListTy;
    1637 for (unsigned i = 0, e = ParamsList.size(); i != e; ++i)
    1638 ParamsListTy.push_back(ParamsList[i].get());
    1639 Result = HandleUpRefs(UnionType::get(&ParamsListTy[0], ParamsListTy.size()));
    16031640 return false;
    16041641 }
    16051642
    21622199 ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
    21632200 return true;
    21642201
    2165 if (!isa(Val->getType()) && !isa(Val->getType()))
    2166 return Error(ID.Loc, "extractvalue operand must be array or struct");
    2202 if (!Val->getType()->isAggregateType())
    2203 return Error(ID.Loc, "extractvalue operand must be aggregate type");
    21672204 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
    21682205 Indices.end()))
    21692206 return Error(ID.Loc, "invalid indices for extractvalue");
    21832220 ParseIndexList(Indices) ||
    21842221 ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
    21852222 return true;
    2186 if (!isa(Val0->getType()) && !isa(Val0->getType()))
    2187 return Error(ID.Loc, "extractvalue operand must be array or struct");
    2223 if (!Val0->getType()->isAggregateType())
    2224 return Error(ID.Loc, "insertvalue operand must be aggregate type");
    21882225 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
    21892226 Indices.end()))
    21902227 return Error(ID.Loc, "invalid indices for insertvalue");
    25202557 V = Constant::getNullValue(Ty);
    25212558 return false;
    25222559 case ValID::t_Constant:
    2523 if (ID.ConstantVal->getType() != Ty)
    2560 if (ID.ConstantVal->getType() != Ty) {
    2561 // Allow a constant struct with a single member to be converted
    2562 // to a union, if the union has a member which is the same type
    2563 // as the struct member.
    2564 if (const UnionType* utype = dyn_cast(Ty)) {
    2565 return ParseUnionValue(utype, ID, V);
    2566 }
    2567
    25242568 return Error(ID.Loc, "constant expression type mismatch");
    2569 }
    2570
    25252571 V = ID.ConstantVal;
    25262572 return false;
    25272573 }
    25492595 return Error(Loc, "expected a basic block");
    25502596 BB = cast(V);
    25512597 return false;
    2598 }
    2599
    2600 bool LLParser::ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V) {
    2601 if (const StructType* stype = dyn_cast(ID.ConstantVal->getType())) {
    2602 if (stype->getNumContainedTypes() != 1)
    2603 return Error(ID.Loc, "constant expression type mismatch");
    2604 int index = utype->getElementTypeIndex(stype->getContainedType(0));
    2605 if (index < 0)
    2606 return Error(ID.Loc, "initializer type is not a member of the union");
    2607
    2608 V = ConstantUnion::get(
    2609 utype, cast(ID.ConstantVal->getOperand(0)));
    2610 return false;
    2611 }
    2612
    2613 return Error(ID.Loc, "constant expression type mismatch");
    25522614 }
    25532615
    25542616
    38103872 ParseIndexList(Indices, AteExtraComma))
    38113873 return true;
    38123874
    3813 if (!isa(Val->getType()) && !isa(Val->getType()))
    3814 return Error(Loc, "extractvalue operand must be array or struct");
    3875 if (!Val->getType()->isAggregateType())
    3876 return Error(Loc, "extractvalue operand must be aggregate type");
    38153877
    38163878 if (!ExtractValueInst::getIndexedType(Val->getType(), Indices.begin(),
    38173879 Indices.end()))
    38323894 ParseIndexList(Indices, AteExtraComma))
    38333895 return true;
    38343896
    3835 if (!isa(Val0->getType()) && !isa(Val0->getType()))
    3836 return Error(Loc0, "extractvalue operand must be array or struct");
    3897 if (!Val0->getType()->isAggregateType())
    3898 return Error(Loc0, "insertvalue operand must be aggregate type");
    38373899
    38383900 if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices.begin(),
    38393901 Indices.end()))
    3030 class GlobalValue;
    3131 class MDString;
    3232 class MDNode;
    33 class UnionType;
    3334
    3435 /// ValID - Represents a reference of a definition of some sort with no type.
    3536 /// There are several cases where we have to parse the value but where the
    211212 }
    212213 bool ParseTypeRec(PATypeHolder &H);
    213214 bool ParseStructType(PATypeHolder &H, bool Packed);
    215 bool ParseUnionType(PATypeHolder &H);
    214216 bool ParseArrayVectorType(PATypeHolder &H, bool isVector);
    215217 bool ParseFunctionType(PATypeHolder &Result);
    216218 PATypeHolder HandleUpRefs(const Type *Ty);
    278280 LocTy Loc;
    279281 return ParseTypeAndBasicBlock(BB, Loc, PFS);
    280282 }
    283
    284 bool ParseUnionValue(const UnionType* utype, ValID &ID, Value *&V);
    281285
    282286 struct ParamInfo {
    283287 LocTy Loc;
    9696
    9797 kw_type,
    9898 kw_opaque,
    99 kw_union,
    99100
    100101 kw_eq, kw_ne, kw_slt, kw_sgt, kw_sle, kw_sge, kw_ult, kw_ugt, kw_ule,
    101102 kw_uge, kw_oeq, kw_one, kw_olt, kw_ogt, kw_ole, kw_oge, kw_ord, kw_uno,
    582582 for (unsigned i = 1, e = Record.size(); i != e; ++i)
    583583 EltTys.push_back(getTypeByID(Record[i], true));
    584584 ResultTy = StructType::get(Context, EltTys, Record[0]);
    585 break;
    586 }
    587 case bitc::TYPE_CODE_UNION: { // UNION: [eltty x N]
    588 SmallVector EltTys;
    589 for (unsigned i = 0, e = Record.size(); i != e; ++i)
    590 EltTys.push_back(getTypeByID(Record[i], true));
    591 ResultTy = UnionType::get(&EltTys[0], EltTys.size());
    585592 break;
    586593 }
    587594 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
    179179 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    180180 Log2_32_Ceil(VE.getTypes().size()+1)));
    181181 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
    182
    183 // Abbrev for TYPE_CODE_UNION.
    184 Abbv = new BitCodeAbbrev();
    185 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_UNION));
    186 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    187 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    188 Log2_32_Ceil(VE.getTypes().size()+1)));
    189 unsigned UnionAbbrev = Stream.EmitAbbrev(Abbv);
    182190
    183191 // Abbrev for TYPE_CODE_ARRAY.
    184192 Abbv = new BitCodeAbbrev();
    247255 E = ST->element_end(); I != E; ++I)
    248256 TypeVals.push_back(VE.getTypeID(*I));
    249257 AbbrevToUse = StructAbbrev;
    258 break;
    259 }
    260 case Type::UnionTyID: {
    261 const UnionType *UT = cast(T);
    262 // UNION: [eltty x N]
    263 Code = bitc::TYPE_CODE_UNION;
    264 // Output all of the element types.
    265 for (UnionType::element_iterator I = UT->element_begin(),
    266 E = UT->element_end(); I != E; ++I)
    267 TypeVals.push_back(VE.getTypeID(*I));
    268 AbbrevToUse = UnionAbbrev;
    250269 break;
    251270 }
    252271 case Type::ArrayTyID: {
    788807 else if (isCStr7)
    789808 AbbrevToUse = CString7Abbrev;
    790809 } else if (isa(C) || isa(V) ||
    791 isaVector>(V)) {
    810 isaUnion>(C) || isaVector>(V)) {
    792811 Code = bitc::CST_CODE_AGGREGATE;
    793812 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
    794813 Record.push_back(VE.getValueID(C->getOperand(i)));
    42414241 // 66 0F 38 81
    42424242 def INVVPID : I<0x38, RawFrm, (outs), (ins), "invvpid", []>, OpSize, TB;
    42434243 // 0F 01 C1
    4244 def VMCALL : I<0x01, RawFrm, (outs), (ins), "vmcall", []>, TB;
    4244 def VMCALL : I<0x01, MRM_C1, (outs), (ins), "vmcall", []>, TB;
    42454245 def VMCLEARm : I<0xC7, MRM6m, (outs), (ins i64mem:$vmcs),
    42464246 "vmclear\t$vmcs", []>, OpSize, TB;
    42474247 // 0F 01 C2
    236236 OS << '}';
    237237 if (STy->isPacked())
    238238 OS << '>';
    239 break;
    240 }
    241 case Type::UnionTyID: {
    242 const UnionType *UTy = cast(Ty);
    243 OS << "union { ";
    244 for (StructType::element_iterator I = UTy->element_begin(),
    245 E = UTy->element_end(); I != E; ++I) {
    246 CalcTypeName(*I, TypeStack, OS);
    247 if (next(I) != UTy->element_end())
    248 OS << ',';
    249 OS << ' ';
    250 }
    251 OS << '}';
    239252 break;
    240253 }
    241254 case Type::PointerTyID: {
    884884 unsigned numOps;
    885885 if (const ArrayType *AR = dyn_cast(AggTy))
    886886 numOps = AR->getNumElements();
    887 else if (isa(AggTy))
    888 numOps = 1;
    887889 else
    888890 numOps = cast(AggTy)->getNumElements();
    889891
    900902
    901903 if (const StructType* ST = dyn_cast(AggTy))
    902904 return ConstantStruct::get(ST->getContext(), Ops, ST->isPacked());
    905 if (const UnionType* UT = dyn_cast(AggTy)) {
    906 assert(Ops.size() == 1 && "Union can only contain a single value!");
    907 return ConstantUnion::get(UT, Ops[0]);
    908 }
    903909 return ConstantArray::get(cast(AggTy), Ops);
    904910 }
    905911
    583583 // FIXME: make this the primary ctor method.
    584584 return get(Context, std::vector(Vals, Vals+NumVals), Packed);
    585585 }
    586
    587 ConstantUnion::ConstantUnion(const UnionType *T, Constant* V)
    588 : Constant(T, ConstantUnionVal,
    589 OperandTraits::op_end(this) - 1, 1) {
    590 Use *OL = OperandList;
    591 assert(T->getElementTypeIndex(V->getType()) >= 0 &&
    592 "Initializer for union element isn't a member of union type!");
    593 *OL = V;
    594 }
    595
    596 // ConstantUnion accessors.
    597 Constant* ConstantUnion::get(const UnionType* T, Constant* V) {
    598 LLVMContextImpl* pImpl = T->getContext().pImpl;
    599
    600 // Create a ConstantAggregateZero value if all elements are zeros...
    601 if (!V->isNullValue())
    602 return pImpl->UnionConstants.getOrCreate(T, V);
    603
    604 return ConstantAggregateZero::get(T);
    605 }
    606
    586607
    587608 ConstantVector::ConstantVector(const VectorType *T,
    588609 const std::vector &V)
    10041025 //
    10051026 void ConstantStruct::destroyConstant() {
    10061027 getType()->getContext().pImpl->StructConstants.remove(this);
    1028 destroyConstantImpl();
    1029 }
    1030
    1031 // destroyConstant - Remove the constant from the constant table...
    1032 //
    1033 void ConstantUnion::destroyConstant() {
    1034 getType()->getContext().pImpl->UnionConstants.remove(this);
    10071035 destroyConstantImpl();
    10081036 }
    10091037
    20802108
    20812109 // Delete the old constant!
    20822110 destroyConstant();
    2111 }
    2112
    2113 void ConstantUnion::replaceUsesOfWithOnConstant(Value *From, Value *To,
    2114 Use *U) {
    2115 assert(false && "Implement replaceUsesOfWithOnConstant for unions");
    20832116 }
    20842117
    20852118 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
    337337 struct ConstantTraits< std::vector > {
    338338 static unsigned uses(const std::vector& v) {
    339339 return v.size();
    340 }
    341 };
    342
    343 template<>
    344 struct ConstantTraits {
    345 static unsigned uses(Constant * const & v) {
    346 return 1;
    340347 }
    341348 };
    342349
    469476 }
    470477 };
    471478
    479 template<>
    480 struct ConstantKeyData {
    481 typedef Constant* ValType;
    482 static ValType getValType(ConstantUnion *CU) {
    483 return cast(CU->getOperand(0));
    484 }
    485 };
    486
    472487 // ConstantPointerNull does not take extra "value" argument...
    473488 template
    474489 struct ConstantCreator {
    140140 return LLVMFunctionTypeKind;
    141141 case Type::StructTyID:
    142142 return LLVMStructTypeKind;
    143 case Type::UnionTyID:
    144 return LLVMUnionTypeKind;
    143145 case Type::ArrayTyID:
    144146 return LLVMArrayTypeKind;
    145147 case Type::PointerTyID:
    296298
    297299 LLVMBool LLVMIsPackedStruct(LLVMTypeRef StructTy) {
    298300 return unwrap(StructTy)->isPacked();
    301 }
    302
    303 /*--.. Operations on union types ..........................................--*/
    304
    305 LLVMTypeRef LLVMUnionTypeInContext(LLVMContextRef C, LLVMTypeRef *ElementTypes,
    306 unsigned ElementCount) {
    307 SmallVector Tys;
    308 for (LLVMTypeRef *I = ElementTypes,
    309 *E = ElementTypes + ElementCount; I != E; ++I)
    310 Tys.push_back(unwrap(*I));
    311
    312 return wrap(UnionType::get(&Tys[0], Tys.size()));
    313 }
    314
    315 LLVMTypeRef LLVMUnionType(LLVMTypeRef *ElementTypes,
    316 unsigned ElementCount, int Packed) {
    317 return LLVMUnionTypeInContext(LLVMGetGlobalContext(), ElementTypes,
    318 ElementCount);
    319 }
    320
    321 unsigned LLVMCountUnionElementTypes(LLVMTypeRef UnionTy) {
    322 return unwrap(UnionTy)->getNumElements();
    323 }
    324
    325 void LLVMGetUnionElementTypes(LLVMTypeRef UnionTy, LLVMTypeRef *Dest) {
    326 UnionType *Ty = unwrap(UnionTy);
    327 for (FunctionType::param_iterator I = Ty->element_begin(),
    328 E = Ty->element_end(); I != E; ++I)
    329 *Dest++ = wrap(*I);
    299330 }
    300331
    301332 /*--.. Operations on array, pointer, and vector types (sequence types) .....--*/
    115115 ConstantStruct, true /*largekey*/> StructConstantsTy;
    116116 StructConstantsTy StructConstants;
    117117
    118 typedef ConstantUniqueMap
    119 UnionConstantsTy;
    120 UnionConstantsTy UnionConstants;
    121
    118122 typedef ConstantUniqueMap, VectorType,
    119123 ConstantVector> VectorConstantsTy;
    120124 VectorConstantsTy VectorConstants;
    158162 TypeMap PointerTypes;
    159163 TypeMap FunctionTypes;
    160164 TypeMap StructTypes;
    165 TypeMap UnionTypes;
    161166 TypeMap IntegerTypes;
    162167
    163168 // Opaque types are not structurally uniqued, so don't use TypeMap.
    4949
    5050 /// Because of the way Type subclasses are allocated, this function is necessary
    5151 /// to use the correct kind of "delete" operator to deallocate the Type object.
    52 /// Some type objects (FunctionTy, StructTy) allocate additional space after
    53 /// the space for their derived type to hold the contained types array of
    52 /// Some type objects (FunctionTy, StructTy, UnionTy) allocate additional space
    53 /// after the space for their derived type to hold the contained types array of
    5454 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
    5555 /// allocated with the type object, decreasing allocations and eliminating the
    5656 /// need for a std::vector to be used in the Type class itself.
    6060 // Structures and Functions allocate their contained types past the end of
    6161 // the type object itself. These need to be destroyed differently than the
    6262 // other types.
    63 if (isa(this) || isa(this)) {
    63 if (isa(this) || isa(this) ||
    64 isa(this)) {
    6465 // First, make sure we destruct any PATypeHandles allocated by these
    6566 // subclasses. They must be manually destructed.
    6667 for (unsigned i = 0; i < NumContainedTys; ++i)
    7071 // to delete this as an array of char.
    7172 if (isa(this))
    7273 static_cast(this)->FunctionType::~FunctionType();
    74 else if (isa(this))
    75 static_cast(this)->StructType::~StructType();
    7376 else
    74 static_castStructType*>(this)->StructType::~StructType();
    77 static_castUnionType*>(this)->UnionType::~UnionType();
    7578
    7679 // Finally, remove the memory as an array deallocation of the chars it was
    7780 // constructed from.
    225228 if (const VectorType *PTy = dyn_cast(this))
    226229 return PTy->getElementType()->isSized();
    227230
    228 if (!isa(this))
    231 if (!isa(this) && !isa(this))
    229232 return false;
    230233
    231234 // Okay, our struct is sized if all of the elements are...
    303306 }
    304307
    305308 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
    309 assert(indexValid(Idx) && "Invalid structure index!");
    310 return ContainedTys[Idx];
    311 }
    312
    313
    314 bool UnionType::indexValid(const Value *V) const {
    315 // Union indexes require 32-bit integer constants.
    316 if (V->getType()->isInteger(32))
    317 if (const ConstantInt *CU = dyn_cast(V))
    318 return indexValid(CU->getZExtValue());
    319 return false;
    320 }
    321
    322 bool UnionType::indexValid(unsigned V) const {
    323 return V < NumContainedTys;
    324 }
    325
    326 // getTypeAtIndex - Given an index value into the type, return the type of the
    327 // element. For a structure type, this must be a constant value...
    328 //
    329 const Type *UnionType::getTypeAtIndex(const Value *V) const {
    330 unsigned Idx = (unsigned)cast(V)->getZExtValue();
    331 return getTypeAtIndex(Idx);
    332 }
    333
    334 const Type *UnionType::getTypeAtIndex(unsigned Idx) const {
    306335 assert(indexValid(Idx) && "Invalid structure index!");
    307336 return ContainedTys[Idx];
    308337 }
    454483 assert(Types[i] && " type for structure field!");
    455484 assert(isValidElementType(Types[i]) &&
    456485 "Invalid type for structure element!");
    486 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
    487 isAbstract |= Types[i]->isAbstract();
    488 }
    489
    490 // Calculate whether or not this type is abstract
    491 setAbstract(isAbstract);
    492 }
    493
    494 UnionType::UnionType(LLVMContext &C,const Type* const* Types, unsigned NumTypes)
    495 : CompositeType(C, UnionTyID) {
    496 ContainedTys = reinterpret_cast(this + 1);
    497 NumContainedTys = NumTypes;
    498 bool isAbstract = false;
    499 for (unsigned i = 0; i < NumTypes; ++i) {
    500 assert(Types[i] && " type for union field!");
    501 assert(isValidElementType(Types[i]) &&
    502 "Invalid type for union element!");
    457503 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
    458504 isAbstract |= Types[i]->isAbstract();
    459505 }
    641687 if (STy->isPacked() != STy2->isPacked()) return false;
    642688 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
    643689 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
    690 return false;
    691 return true;
    692 } else if (const UnionType *UTy = dyn_cast(Ty)) {
    693 const UnionType *UTy2 = cast(Ty2);
    694 if (UTy->getNumElements() != UTy2->getNumElements()) return false;
    695 for (unsigned i = 0, e = UTy2->getNumElements(); i != e; ++i)
    696 if (!TypesEqual(UTy->getElementType(i), UTy2->getElementType(i), EqTypes))
    644697 return false;
    645698 return true;
    646699 } else if (const ArrayType *ATy = dyn_cast(Ty)) {
    900953 }
    901954
    902955 bool StructType::isValidElementType(const Type *ElemTy) {
    903 return ElemTy->getTypeID() != VoidTyID && ElemTy->getTypeID() != LabelTyID &&
    904 ElemTy->getTypeID() != MetadataTyID && !isa(ElemTy);
    905 }
    906
    956 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
    957 !ElemTy->isMetadataTy() && !isa(ElemTy);
    958 }
    959
    960
    961 //===----------------------------------------------------------------------===//
    962 // Union Type Factory...
    963 //
    964
    965 UnionType *UnionType::get(const Type* const* Types, unsigned NumTypes) {
    966 assert(NumTypes > 0 && "union must have at least one member type!");
    967 UnionValType UTV(Types, NumTypes);
    968 UnionType *UT = 0;
    969
    970 LLVMContextImpl *pImpl = Types[0]->getContext().pImpl;
    971
    972 UT = pImpl->UnionTypes.get(UTV);
    973
    974 if (!UT) {
    975 // Value not found. Derive a new type!
    976 UT = (UnionType*) operator new(sizeof(UnionType) +
    977 sizeof(PATypeHandle) * NumTypes);
    978 new (UT) UnionType(Types[0]->getContext(), Types, NumTypes);
    979 pImpl->UnionTypes.add(UTV, UT);
    980 }
    981 #ifdef DEBUG_MERGE_TYPES
    982 DEBUG(dbgs() << "Derived new type: " << *UT << "\n");
    983 #endif
    984 return UT;
    985 }
    986
    987 UnionType *UnionType::get(const Type *type, ...) {
    988 va_list ap;
    989 SmallVector UnionFields;
    990 va_start(ap, type);
    991 while (type) {
    992 UnionFields.push_back(type);
    993 type = va_arg(ap, llvm::Type*);
    994 }
    995 unsigned NumTypes = UnionFields.size();
    996 assert(NumTypes > 0 && "union must have at least one member type!");
    997 return llvm::UnionType::get(&UnionFields[0], NumTypes);
    998 }
    999
    1000 bool UnionType::isValidElementType(const Type *ElemTy) {
    1001 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
    1002 !ElemTy->isMetadataTy() && !ElemTy->isFunction();
    1003 }
    1004
    1005 int UnionType::getElementTypeIndex(const Type *ElemTy) const {
    1006 int index = 0;
    1007 for (UnionType::element_iterator I = element_begin(), E = element_end();
    1008 I != E; ++I, ++index) {
    1009 if (ElemTy == *I) return index;
    1010 }
    1011
    1012 return -1;
    1013 }
    9071014
    9081015 //===----------------------------------------------------------------------===//
    9091016 // Pointer Type Factory...
    11681275 // concrete - this could potentially change us from an abstract type to a
    11691276 // concrete type.
    11701277 //
    1278 void UnionType::refineAbstractType(const DerivedType *OldType,
    1279 const Type *NewType) {
    1280 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
    1281 pImpl->UnionTypes.RefineAbstractType(this, OldType, NewType);
    1282 }
    1283
    1284 void UnionType::typeBecameConcrete(const DerivedType *AbsTy) {
    1285 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
    1286 pImpl->UnionTypes.TypeBecameConcrete(this, AbsTy);
    1287 }
    1288
    1289 // refineAbstractType - Called when a contained type is found to be more
    1290 // concrete - this could potentially change us from an abstract type to a
    1291 // concrete type.
    1292 //
    11711293 void PointerType::refineAbstractType(const DerivedType *OldType,
    11721294 const Type *NewType) {
    11731295 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
    176176 if (ElTypes < STV.ElTypes) return true;
    177177 else if (ElTypes > STV.ElTypes) return false;
    178178 else return (int)packed < (int)STV.packed;
    179 }
    180 };
    181
    182 // UnionValType - Define a class to hold the key that goes into the TypeMap
    183 //
    184 class UnionValType {
    185 std::vector ElTypes;
    186 public:
    187 UnionValType(const Type* const* Types, unsigned NumTypes)
    188 : ElTypes(&Types[0], &Types[NumTypes]) {}
    189
    190 static UnionValType get(const UnionType *UT) {
    191 std::vector ElTypes;
    192 ElTypes.reserve(UT->getNumElements());
    193 for (unsigned i = 0, e = UT->getNumElements(); i != e; ++i)
    194 ElTypes.push_back(UT->getElementType(i));
    195
    196 return UnionValType(&ElTypes[0], ElTypes.size());
    197 }
    198
    199 static unsigned hashTypeStructure(const UnionType *UT) {
    200 return UT->getNumElements();
    201 }
    202
    203 inline bool operator<(const UnionValType &UTV) const {
    204 return (ElTypes < UTV.ElTypes);
    179205 }
    180206 };
    181207
    0 ; RUN: llvm-as %s -o /dev/null
    1
    2 %X = type union { i32, i32* }
    0 ; RUN: llvm-as < %s | llvm-dis > %t1.ll
    1 ; RUN: llvm-as %t1.ll -o - | llvm-dis > %t2.ll
    2 ; RUN: diff %t1.ll %t2.ll
    3
    4 %union.anon = type union { i8, i32, float }
    5
    6 @union1 = constant union { i32, i8 } { i32 4 }
    7 @union2 = constant union { i32, i8 } insertvalue(union { i32, i8 } undef, i32 4, 0)
    8
    9 define void @"Unions" () {
    10 ret void
    11 }