Silencing an "enumeral and non-enumeral type in conditional expression" warning;...
[oota-llvm.git] / lib / IR / Type.cpp
1 //===-- Type.cpp - Implement the Type class -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Type class for the IR library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/Type.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/IR/Module.h"
18 #include <algorithm>
19 #include <cstdarg>
20 using namespace llvm;
21
22 //===----------------------------------------------------------------------===//
23 //                         Type Class Implementation
24 //===----------------------------------------------------------------------===//
25
26 Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
27   switch (IDNumber) {
28   case VoidTyID      : return getVoidTy(C);
29   case HalfTyID      : return getHalfTy(C);
30   case FloatTyID     : return getFloatTy(C);
31   case DoubleTyID    : return getDoubleTy(C);
32   case X86_FP80TyID  : return getX86_FP80Ty(C);
33   case FP128TyID     : return getFP128Ty(C);
34   case PPC_FP128TyID : return getPPC_FP128Ty(C);
35   case LabelTyID     : return getLabelTy(C);
36   case MetadataTyID  : return getMetadataTy(C);
37   case X86_MMXTyID   : return getX86_MMXTy(C);
38   default:
39     return nullptr;
40   }
41 }
42
43 /// getScalarType - If this is a vector type, return the element type,
44 /// otherwise return this.
45 Type *Type::getScalarType() {
46   if (VectorType *VTy = dyn_cast<VectorType>(this))
47     return VTy->getElementType();
48   return this;
49 }
50
51 const Type *Type::getScalarType() const {
52   if (const VectorType *VTy = dyn_cast<VectorType>(this))
53     return VTy->getElementType();
54   return this;
55 }
56
57 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
58 bool Type::isIntegerTy(unsigned Bitwidth) const {
59   return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
60 }
61
62 // canLosslesslyBitCastTo - Return true if this type can be converted to
63 // 'Ty' without any reinterpretation of bits.  For example, i8* to i32*.
64 //
65 bool Type::canLosslesslyBitCastTo(Type *Ty) const {
66   // Identity cast means no change so return true
67   if (this == Ty) 
68     return true;
69   
70   // They are not convertible unless they are at least first class types
71   if (!this->isFirstClassType() || !Ty->isFirstClassType())
72     return false;
73
74   // Vector -> Vector conversions are always lossless if the two vector types
75   // have the same size, otherwise not.  Also, 64-bit vector types can be
76   // converted to x86mmx.
77   if (const VectorType *thisPTy = dyn_cast<VectorType>(this)) {
78     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
79       return thisPTy->getBitWidth() == thatPTy->getBitWidth();
80     if (Ty->getTypeID() == Type::X86_MMXTyID &&
81         thisPTy->getBitWidth() == 64)
82       return true;
83   }
84
85   if (this->getTypeID() == Type::X86_MMXTyID)
86     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
87       if (thatPTy->getBitWidth() == 64)
88         return true;
89
90   // At this point we have only various mismatches of the first class types
91   // remaining and ptr->ptr. Just select the lossless conversions. Everything
92   // else is not lossless. Conservatively assume we can't losslessly convert
93   // between pointers with different address spaces.
94   if (const PointerType *PTy = dyn_cast<PointerType>(this)) {
95     if (const PointerType *OtherPTy = dyn_cast<PointerType>(Ty))
96       return PTy->getAddressSpace() == OtherPTy->getAddressSpace();
97     return false;
98   }
99   return false;  // Other types have no identity values
100 }
101
102 bool Type::isEmptyTy() const {
103   const ArrayType *ATy = dyn_cast<ArrayType>(this);
104   if (ATy) {
105     unsigned NumElements = ATy->getNumElements();
106     return NumElements == 0 || ATy->getElementType()->isEmptyTy();
107   }
108
109   const StructType *STy = dyn_cast<StructType>(this);
110   if (STy) {
111     unsigned NumElements = STy->getNumElements();
112     for (unsigned i = 0; i < NumElements; ++i)
113       if (!STy->getElementType(i)->isEmptyTy())
114         return false;
115     return true;
116   }
117
118   return false;
119 }
120
121 unsigned Type::getPrimitiveSizeInBits() const {
122   switch (getTypeID()) {
123   case Type::HalfTyID: return 16;
124   case Type::FloatTyID: return 32;
125   case Type::DoubleTyID: return 64;
126   case Type::X86_FP80TyID: return 80;
127   case Type::FP128TyID: return 128;
128   case Type::PPC_FP128TyID: return 128;
129   case Type::X86_MMXTyID: return 64;
130   case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
131   case Type::VectorTyID:  return cast<VectorType>(this)->getBitWidth();
132   default: return 0;
133   }
134 }
135
136 /// getScalarSizeInBits - If this is a vector type, return the
137 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
138 /// getPrimitiveSizeInBits value for this type.
139 unsigned Type::getScalarSizeInBits() const {
140   return getScalarType()->getPrimitiveSizeInBits();
141 }
142
143 /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
144 /// is only valid on floating point types.  If the FP type does not
145 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
146 int Type::getFPMantissaWidth() const {
147   if (const VectorType *VTy = dyn_cast<VectorType>(this))
148     return VTy->getElementType()->getFPMantissaWidth();
149   assert(isFloatingPointTy() && "Not a floating point type!");
150   if (getTypeID() == HalfTyID) return 11;
151   if (getTypeID() == FloatTyID) return 24;
152   if (getTypeID() == DoubleTyID) return 53;
153   if (getTypeID() == X86_FP80TyID) return 64;
154   if (getTypeID() == FP128TyID) return 113;
155   assert(getTypeID() == PPC_FP128TyID && "unknown fp type");
156   return -1;
157 }
158
159 /// isSizedDerivedType - Derived types like structures and arrays are sized
160 /// iff all of the members of the type are sized as well.  Since asking for
161 /// their size is relatively uncommon, move this operation out of line.
162 bool Type::isSizedDerivedType(SmallPtrSetImpl<const Type*> *Visited) const {
163   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
164     return ATy->getElementType()->isSized(Visited);
165
166   if (const VectorType *VTy = dyn_cast<VectorType>(this))
167     return VTy->getElementType()->isSized(Visited);
168
169   return cast<StructType>(this)->isSized(Visited);
170 }
171
172 //===----------------------------------------------------------------------===//
173 //                         Subclass Helper Methods
174 //===----------------------------------------------------------------------===//
175
176 unsigned Type::getIntegerBitWidth() const {
177   return cast<IntegerType>(this)->getBitWidth();
178 }
179
180 bool Type::isFunctionVarArg() const {
181   return cast<FunctionType>(this)->isVarArg();
182 }
183
184 Type *Type::getFunctionParamType(unsigned i) const {
185   return cast<FunctionType>(this)->getParamType(i);
186 }
187
188 unsigned Type::getFunctionNumParams() const {
189   return cast<FunctionType>(this)->getNumParams();
190 }
191
192 StringRef Type::getStructName() const {
193   return cast<StructType>(this)->getName();
194 }
195
196 unsigned Type::getStructNumElements() const {
197   return cast<StructType>(this)->getNumElements();
198 }
199
200 Type *Type::getStructElementType(unsigned N) const {
201   return cast<StructType>(this)->getElementType(N);
202 }
203
204 Type *Type::getSequentialElementType() const {
205   return cast<SequentialType>(this)->getElementType();
206 }
207
208 uint64_t Type::getArrayNumElements() const {
209   return cast<ArrayType>(this)->getNumElements();
210 }
211
212 unsigned Type::getVectorNumElements() const {
213   return cast<VectorType>(this)->getNumElements();
214 }
215
216 unsigned Type::getPointerAddressSpace() const {
217   return cast<PointerType>(getScalarType())->getAddressSpace();
218 }
219
220
221 //===----------------------------------------------------------------------===//
222 //                          Primitive 'Type' data
223 //===----------------------------------------------------------------------===//
224
225 Type *Type::getVoidTy(LLVMContext &C) { return &C.pImpl->VoidTy; }
226 Type *Type::getLabelTy(LLVMContext &C) { return &C.pImpl->LabelTy; }
227 Type *Type::getHalfTy(LLVMContext &C) { return &C.pImpl->HalfTy; }
228 Type *Type::getFloatTy(LLVMContext &C) { return &C.pImpl->FloatTy; }
229 Type *Type::getDoubleTy(LLVMContext &C) { return &C.pImpl->DoubleTy; }
230 Type *Type::getMetadataTy(LLVMContext &C) { return &C.pImpl->MetadataTy; }
231 Type *Type::getX86_FP80Ty(LLVMContext &C) { return &C.pImpl->X86_FP80Ty; }
232 Type *Type::getFP128Ty(LLVMContext &C) { return &C.pImpl->FP128Ty; }
233 Type *Type::getPPC_FP128Ty(LLVMContext &C) { return &C.pImpl->PPC_FP128Ty; }
234 Type *Type::getX86_MMXTy(LLVMContext &C) { return &C.pImpl->X86_MMXTy; }
235
236 IntegerType *Type::getInt1Ty(LLVMContext &C) { return &C.pImpl->Int1Ty; }
237 IntegerType *Type::getInt8Ty(LLVMContext &C) { return &C.pImpl->Int8Ty; }
238 IntegerType *Type::getInt16Ty(LLVMContext &C) { return &C.pImpl->Int16Ty; }
239 IntegerType *Type::getInt32Ty(LLVMContext &C) { return &C.pImpl->Int32Ty; }
240 IntegerType *Type::getInt64Ty(LLVMContext &C) { return &C.pImpl->Int64Ty; }
241
242 IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
243   return IntegerType::get(C, N);
244 }
245
246 PointerType *Type::getHalfPtrTy(LLVMContext &C, unsigned AS) {
247   return getHalfTy(C)->getPointerTo(AS);
248 }
249
250 PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
251   return getFloatTy(C)->getPointerTo(AS);
252 }
253
254 PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
255   return getDoubleTy(C)->getPointerTo(AS);
256 }
257
258 PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
259   return getX86_FP80Ty(C)->getPointerTo(AS);
260 }
261
262 PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
263   return getFP128Ty(C)->getPointerTo(AS);
264 }
265
266 PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
267   return getPPC_FP128Ty(C)->getPointerTo(AS);
268 }
269
270 PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
271   return getX86_MMXTy(C)->getPointerTo(AS);
272 }
273
274 PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
275   return getIntNTy(C, N)->getPointerTo(AS);
276 }
277
278 PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
279   return getInt1Ty(C)->getPointerTo(AS);
280 }
281
282 PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
283   return getInt8Ty(C)->getPointerTo(AS);
284 }
285
286 PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
287   return getInt16Ty(C)->getPointerTo(AS);
288 }
289
290 PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
291   return getInt32Ty(C)->getPointerTo(AS);
292 }
293
294 PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
295   return getInt64Ty(C)->getPointerTo(AS);
296 }
297
298
299 //===----------------------------------------------------------------------===//
300 //                       IntegerType Implementation
301 //===----------------------------------------------------------------------===//
302
303 IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
304   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
305   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
306   
307   // Check for the built-in integer types
308   switch (NumBits) {
309   case  1: return cast<IntegerType>(Type::getInt1Ty(C));
310   case  8: return cast<IntegerType>(Type::getInt8Ty(C));
311   case 16: return cast<IntegerType>(Type::getInt16Ty(C));
312   case 32: return cast<IntegerType>(Type::getInt32Ty(C));
313   case 64: return cast<IntegerType>(Type::getInt64Ty(C));
314   default: 
315     break;
316   }
317   
318   IntegerType *&Entry = C.pImpl->IntegerTypes[NumBits];
319
320   if (!Entry)
321     Entry = new (C.pImpl->TypeAllocator) IntegerType(C, NumBits);
322   
323   return Entry;
324 }
325
326 bool IntegerType::isPowerOf2ByteWidth() const {
327   unsigned BitWidth = getBitWidth();
328   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
329 }
330
331 APInt IntegerType::getMask() const {
332   return APInt::getAllOnesValue(getBitWidth());
333 }
334
335 //===----------------------------------------------------------------------===//
336 //                       FunctionType Implementation
337 //===----------------------------------------------------------------------===//
338
339 FunctionType::FunctionType(Type *Result, ArrayRef<Type*> Params,
340                            bool IsVarArgs)
341   : Type(Result->getContext(), FunctionTyID) {
342   Type **SubTys = reinterpret_cast<Type**>(this+1);
343   assert(isValidReturnType(Result) && "invalid return type for function");
344   setSubclassData(IsVarArgs);
345
346   SubTys[0] = const_cast<Type*>(Result);
347
348   for (unsigned i = 0, e = Params.size(); i != e; ++i) {
349     assert(isValidArgumentType(Params[i]) &&
350            "Not a valid type for function argument!");
351     SubTys[i+1] = Params[i];
352   }
353
354   ContainedTys = SubTys;
355   NumContainedTys = Params.size() + 1; // + 1 for result type
356 }
357
358 // FunctionType::get - The factory function for the FunctionType class.
359 FunctionType *FunctionType::get(Type *ReturnType,
360                                 ArrayRef<Type*> Params, bool isVarArg) {
361   LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
362   FunctionTypeKeyInfo::KeyTy Key(ReturnType, Params, isVarArg);
363   LLVMContextImpl::FunctionTypeMap::iterator I =
364     pImpl->FunctionTypes.find_as(Key);
365   FunctionType *FT;
366
367   if (I == pImpl->FunctionTypes.end()) {
368     FT = (FunctionType*) pImpl->TypeAllocator.
369       Allocate(sizeof(FunctionType) + sizeof(Type*) * (Params.size() + 1),
370                AlignOf<FunctionType>::Alignment);
371     new (FT) FunctionType(ReturnType, Params, isVarArg);
372     pImpl->FunctionTypes[FT] = true;
373   } else {
374     FT = I->first;
375   }
376
377   return FT;
378 }
379
380 FunctionType *FunctionType::get(Type *Result, bool isVarArg) {
381   return get(Result, None, isVarArg);
382 }
383
384 /// isValidReturnType - Return true if the specified type is valid as a return
385 /// type.
386 bool FunctionType::isValidReturnType(Type *RetTy) {
387   return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
388   !RetTy->isMetadataTy();
389 }
390
391 /// isValidArgumentType - Return true if the specified type is valid as an
392 /// argument type.
393 bool FunctionType::isValidArgumentType(Type *ArgTy) {
394   return ArgTy->isFirstClassType();
395 }
396
397 //===----------------------------------------------------------------------===//
398 //                       StructType Implementation
399 //===----------------------------------------------------------------------===//
400
401 // Primitive Constructors.
402
403 StructType *StructType::get(LLVMContext &Context, ArrayRef<Type*> ETypes, 
404                             bool isPacked) {
405   LLVMContextImpl *pImpl = Context.pImpl;
406   AnonStructTypeKeyInfo::KeyTy Key(ETypes, isPacked);
407   LLVMContextImpl::StructTypeMap::iterator I =
408     pImpl->AnonStructTypes.find_as(Key);
409   StructType *ST;
410
411   if (I == pImpl->AnonStructTypes.end()) {
412     // Value not found.  Create a new type!
413     ST = new (Context.pImpl->TypeAllocator) StructType(Context);
414     ST->setSubclassData(SCDB_IsLiteral);  // Literal struct.
415     ST->setBody(ETypes, isPacked);
416     Context.pImpl->AnonStructTypes[ST] = true;
417   } else {
418     ST = I->first;
419   }
420
421   return ST;
422 }
423
424 void StructType::setBody(ArrayRef<Type*> Elements, bool isPacked) {
425   assert(isOpaque() && "Struct body already set!");
426   
427   setSubclassData(getSubclassData() | SCDB_HasBody);
428   if (isPacked)
429     setSubclassData(getSubclassData() | SCDB_Packed);
430
431   unsigned NumElements = Elements.size();
432   Type **Elts = getContext().pImpl->TypeAllocator.Allocate<Type*>(NumElements);
433   memcpy(Elts, Elements.data(), sizeof(Elements[0]) * NumElements);
434   
435   ContainedTys = Elts;
436   NumContainedTys = NumElements;
437 }
438
439 void StructType::setName(StringRef Name) {
440   if (Name == getName()) return;
441
442   StringMap<StructType *> &SymbolTable = getContext().pImpl->NamedStructTypes;
443   typedef StringMap<StructType *>::MapEntryTy EntryTy;
444
445   // If this struct already had a name, remove its symbol table entry. Don't
446   // delete the data yet because it may be part of the new name.
447   if (SymbolTableEntry)
448     SymbolTable.remove((EntryTy *)SymbolTableEntry);
449
450   // If this is just removing the name, we're done.
451   if (Name.empty()) {
452     if (SymbolTableEntry) {
453       // Delete the old string data.
454       ((EntryTy *)SymbolTableEntry)->Destroy(SymbolTable.getAllocator());
455       SymbolTableEntry = nullptr;
456     }
457     return;
458   }
459   
460   // Look up the entry for the name.
461   EntryTy *Entry = &getContext().pImpl->NamedStructTypes.GetOrCreateValue(Name);
462   
463   // While we have a name collision, try a random rename.
464   if (Entry->getValue()) {
465     SmallString<64> TempStr(Name);
466     TempStr.push_back('.');
467     raw_svector_ostream TmpStream(TempStr);
468     unsigned NameSize = Name.size();
469    
470     do {
471       TempStr.resize(NameSize + 1);
472       TmpStream.resync();
473       TmpStream << getContext().pImpl->NamedStructTypesUniqueID++;
474       
475       Entry = &getContext().pImpl->
476                  NamedStructTypes.GetOrCreateValue(TmpStream.str());
477     } while (Entry->getValue());
478   }
479
480   // Okay, we found an entry that isn't used.  It's us!
481   Entry->setValue(this);
482
483   // Delete the old string data.
484   if (SymbolTableEntry)
485     ((EntryTy *)SymbolTableEntry)->Destroy(SymbolTable.getAllocator());
486   SymbolTableEntry = Entry;
487 }
488
489 //===----------------------------------------------------------------------===//
490 // StructType Helper functions.
491
492 StructType *StructType::create(LLVMContext &Context, StringRef Name) {
493   StructType *ST = new (Context.pImpl->TypeAllocator) StructType(Context);
494   if (!Name.empty())
495     ST->setName(Name);
496   return ST;
497 }
498
499 StructType *StructType::get(LLVMContext &Context, bool isPacked) {
500   return get(Context, None, isPacked);
501 }
502
503 StructType *StructType::get(Type *type, ...) {
504   assert(type && "Cannot create a struct type with no elements with this");
505   LLVMContext &Ctx = type->getContext();
506   va_list ap;
507   SmallVector<llvm::Type*, 8> StructFields;
508   va_start(ap, type);
509   while (type) {
510     StructFields.push_back(type);
511     type = va_arg(ap, llvm::Type*);
512   }
513   auto *Ret = llvm::StructType::get(Ctx, StructFields);
514   va_end(ap);
515   return Ret;
516 }
517
518 StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements,
519                                StringRef Name, bool isPacked) {
520   StructType *ST = create(Context, Name);
521   ST->setBody(Elements, isPacked);
522   return ST;
523 }
524
525 StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements) {
526   return create(Context, Elements, StringRef());
527 }
528
529 StructType *StructType::create(LLVMContext &Context) {
530   return create(Context, StringRef());
531 }
532
533 StructType *StructType::create(ArrayRef<Type*> Elements, StringRef Name,
534                                bool isPacked) {
535   assert(!Elements.empty() &&
536          "This method may not be invoked with an empty list");
537   return create(Elements[0]->getContext(), Elements, Name, isPacked);
538 }
539
540 StructType *StructType::create(ArrayRef<Type*> Elements) {
541   assert(!Elements.empty() &&
542          "This method may not be invoked with an empty list");
543   return create(Elements[0]->getContext(), Elements, StringRef());
544 }
545
546 StructType *StructType::create(StringRef Name, Type *type, ...) {
547   assert(type && "Cannot create a struct type with no elements with this");
548   LLVMContext &Ctx = type->getContext();
549   va_list ap;
550   SmallVector<llvm::Type*, 8> StructFields;
551   va_start(ap, type);
552   while (type) {
553     StructFields.push_back(type);
554     type = va_arg(ap, llvm::Type*);
555   }
556   auto *Ret = llvm::StructType::create(Ctx, StructFields, Name);
557   va_end(ap);
558   return Ret;
559 }
560
561 bool StructType::isSized(SmallPtrSetImpl<const Type*> *Visited) const {
562   if ((getSubclassData() & SCDB_IsSized) != 0)
563     return true;
564   if (isOpaque())
565     return false;
566
567   if (Visited && !Visited->insert(this))
568     return false;
569
570   // Okay, our struct is sized if all of the elements are, but if one of the
571   // elements is opaque, the struct isn't sized *yet*, but may become sized in
572   // the future, so just bail out without caching.
573   for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
574     if (!(*I)->isSized(Visited))
575       return false;
576
577   // Here we cheat a bit and cast away const-ness. The goal is to memoize when
578   // we find a sized type, as types can only move from opaque to sized, not the
579   // other way.
580   const_cast<StructType*>(this)->setSubclassData(
581     getSubclassData() | SCDB_IsSized);
582   return true;
583 }
584
585 StringRef StructType::getName() const {
586   assert(!isLiteral() && "Literal structs never have names");
587   if (!SymbolTableEntry) return StringRef();
588
589   return ((StringMapEntry<StructType*> *)SymbolTableEntry)->getKey();
590 }
591
592 void StructType::setBody(Type *type, ...) {
593   assert(type && "Cannot create a struct type with no elements with this");
594   va_list ap;
595   SmallVector<llvm::Type*, 8> StructFields;
596   va_start(ap, type);
597   while (type) {
598     StructFields.push_back(type);
599     type = va_arg(ap, llvm::Type*);
600   }
601   setBody(StructFields);
602   va_end(ap);
603 }
604
605 bool StructType::isValidElementType(Type *ElemTy) {
606   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
607          !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
608 }
609
610 /// isLayoutIdentical - Return true if this is layout identical to the
611 /// specified struct.
612 bool StructType::isLayoutIdentical(StructType *Other) const {
613   if (this == Other) return true;
614   
615   if (isPacked() != Other->isPacked() ||
616       getNumElements() != Other->getNumElements())
617     return false;
618   
619   return std::equal(element_begin(), element_end(), Other->element_begin());
620 }
621
622 /// getTypeByName - Return the type with the specified name, or null if there
623 /// is none by that name.
624 StructType *Module::getTypeByName(StringRef Name) const {
625   return getContext().pImpl->NamedStructTypes.lookup(Name);
626 }
627
628
629 //===----------------------------------------------------------------------===//
630 //                       CompositeType Implementation
631 //===----------------------------------------------------------------------===//
632
633 Type *CompositeType::getTypeAtIndex(const Value *V) {
634   if (StructType *STy = dyn_cast<StructType>(this)) {
635     unsigned Idx =
636       (unsigned)cast<Constant>(V)->getUniqueInteger().getZExtValue();
637     assert(indexValid(Idx) && "Invalid structure index!");
638     return STy->getElementType(Idx);
639   }
640
641   return cast<SequentialType>(this)->getElementType();
642 }
643 Type *CompositeType::getTypeAtIndex(unsigned Idx) {
644   if (StructType *STy = dyn_cast<StructType>(this)) {
645     assert(indexValid(Idx) && "Invalid structure index!");
646     return STy->getElementType(Idx);
647   }
648   
649   return cast<SequentialType>(this)->getElementType();
650 }
651 bool CompositeType::indexValid(const Value *V) const {
652   if (const StructType *STy = dyn_cast<StructType>(this)) {
653     // Structure indexes require (vectors of) 32-bit integer constants.  In the
654     // vector case all of the indices must be equal.
655     if (!V->getType()->getScalarType()->isIntegerTy(32))
656       return false;
657     const Constant *C = dyn_cast<Constant>(V);
658     if (C && V->getType()->isVectorTy())
659       C = C->getSplatValue();
660     const ConstantInt *CU = dyn_cast_or_null<ConstantInt>(C);
661     return CU && CU->getZExtValue() < STy->getNumElements();
662   }
663
664   // Sequential types can be indexed by any integer.
665   return V->getType()->isIntOrIntVectorTy();
666 }
667
668 bool CompositeType::indexValid(unsigned Idx) const {
669   if (const StructType *STy = dyn_cast<StructType>(this))
670     return Idx < STy->getNumElements();
671   // Sequential types can be indexed by any integer.
672   return true;
673 }
674
675
676 //===----------------------------------------------------------------------===//
677 //                           ArrayType Implementation
678 //===----------------------------------------------------------------------===//
679
680 ArrayType::ArrayType(Type *ElType, uint64_t NumEl)
681   : SequentialType(ArrayTyID, ElType) {
682   NumElements = NumEl;
683 }
684
685 ArrayType *ArrayType::get(Type *elementType, uint64_t NumElements) {
686   Type *ElementType = const_cast<Type*>(elementType);
687   assert(isValidElementType(ElementType) && "Invalid type for array element!");
688     
689   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
690   ArrayType *&Entry = 
691     pImpl->ArrayTypes[std::make_pair(ElementType, NumElements)];
692
693   if (!Entry)
694     Entry = new (pImpl->TypeAllocator) ArrayType(ElementType, NumElements);
695   return Entry;
696 }
697
698 bool ArrayType::isValidElementType(Type *ElemTy) {
699   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
700          !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
701 }
702
703 //===----------------------------------------------------------------------===//
704 //                          VectorType Implementation
705 //===----------------------------------------------------------------------===//
706
707 VectorType::VectorType(Type *ElType, unsigned NumEl)
708   : SequentialType(VectorTyID, ElType) {
709   NumElements = NumEl;
710 }
711
712 VectorType *VectorType::get(Type *elementType, unsigned NumElements) {
713   Type *ElementType = const_cast<Type*>(elementType);
714   assert(NumElements > 0 && "#Elements of a VectorType must be greater than 0");
715   assert(isValidElementType(ElementType) &&
716          "Elements of a VectorType must be a primitive type");
717   
718   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
719   VectorType *&Entry = ElementType->getContext().pImpl
720     ->VectorTypes[std::make_pair(ElementType, NumElements)];
721
722   if (!Entry)
723     Entry = new (pImpl->TypeAllocator) VectorType(ElementType, NumElements);
724   return Entry;
725 }
726
727 bool VectorType::isValidElementType(Type *ElemTy) {
728   return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
729     ElemTy->isPointerTy();
730 }
731
732 //===----------------------------------------------------------------------===//
733 //                         PointerType Implementation
734 //===----------------------------------------------------------------------===//
735
736 PointerType *PointerType::get(Type *EltTy, unsigned AddressSpace) {
737   assert(EltTy && "Can't get a pointer to <null> type!");
738   assert(isValidElementType(EltTy) && "Invalid type for pointer element!");
739   
740   LLVMContextImpl *CImpl = EltTy->getContext().pImpl;
741   
742   // Since AddressSpace #0 is the common case, we special case it.
743   PointerType *&Entry = AddressSpace == 0 ? CImpl->PointerTypes[EltTy]
744      : CImpl->ASPointerTypes[std::make_pair(EltTy, AddressSpace)];
745
746   if (!Entry)
747     Entry = new (CImpl->TypeAllocator) PointerType(EltTy, AddressSpace);
748   return Entry;
749 }
750
751
752 PointerType::PointerType(Type *E, unsigned AddrSpace)
753   : SequentialType(PointerTyID, E) {
754 #ifndef NDEBUG
755   const unsigned oldNCT = NumContainedTys;
756 #endif
757   setSubclassData(AddrSpace);
758   // Check for miscompile. PR11652.
759   assert(oldNCT == NumContainedTys && "bitfield written out of bounds?");
760 }
761
762 PointerType *Type::getPointerTo(unsigned addrs) {
763   return PointerType::get(this, addrs);
764 }
765
766 bool PointerType::isValidElementType(Type *ElemTy) {
767   return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
768          !ElemTy->isMetadataTy();
769 }