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