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