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