1//===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===//
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 is the code that handles AST -> LLVM type lowering.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenTypes.h"
14#include "CGCXXABI.h"
15#include "CGCall.h"
16#include "CGDebugInfo.h"
17#include "CGHLSLRuntime.h"
18#include "CGOpenCLRuntime.h"
19#include "CGRecordLayout.h"
20#include "TargetInfo.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/MatrixUtils.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/CodeGen/CGFunctionInfo.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Module.h"
31
32using namespace clang;
33using namespace CodeGen;
34
35CodeGenTypes::CodeGenTypes(CodeGenModule &cgm)
36 : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
37 Target(cgm.getTarget()) {
38 SkippedLayout = false;
39 LongDoubleReferenced = false;
40}
41
42CodeGenTypes::~CodeGenTypes() {
43 for (llvm::FoldingSet<CGFunctionInfo>::iterator
44 I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
45 delete &*I++;
46}
47
48CGCXXABI &CodeGenTypes::getCXXABI() const { return getCGM().getCXXABI(); }
49
50const CodeGenOptions &CodeGenTypes::getCodeGenOpts() const {
51 return CGM.getCodeGenOpts();
52}
53
54void CodeGenTypes::addRecordTypeName(const RecordDecl *RD,
55 llvm::StructType *Ty,
56 StringRef suffix) {
57 SmallString<256> TypeName;
58 llvm::raw_svector_ostream OS(TypeName);
59 OS << RD->getKindName() << '.';
60
61 // FIXME: We probably want to make more tweaks to the printing policy. For
62 // example, we should probably enable PrintCanonicalTypes and
63 // FullyQualifiedNames.
64 PrintingPolicy Policy = RD->getASTContext().getPrintingPolicy();
65 Policy.SuppressInlineNamespace =
66 llvm::to_underlying(E: PrintingPolicy::SuppressInlineNamespaceMode::None);
67
68 // Name the codegen type after the typedef name
69 // if there is no tag type name available
70 if (RD->getIdentifier()) {
71 // FIXME: We should not have to check for a null decl context here.
72 // Right now we do it because the implicit Obj-C decls don't have one.
73 if (RD->getDeclContext())
74 RD->printQualifiedName(OS, Policy);
75 else
76 RD->printName(OS, Policy);
77 } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
78 // FIXME: We should not have to check for a null decl context here.
79 // Right now we do it because the implicit Obj-C decls don't have one.
80 if (TDD->getDeclContext())
81 TDD->printQualifiedName(OS, Policy);
82 else
83 TDD->printName(OS);
84 } else
85 OS << "anon";
86
87 if (!suffix.empty())
88 OS << suffix;
89
90 Ty->setName(OS.str());
91}
92
93/// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
94/// ConvertType in that it is used to convert to the memory representation for
95/// a type. For example, the scalar representation for _Bool is i1, but the
96/// memory representation is usually i8 or i32, depending on the target.
97///
98/// We generally assume that the alloc size of this type under the LLVM
99/// data layout is the same as the size of the AST type. The alignment
100/// does not have to match: Clang should always use explicit alignments
101/// and packed structs as necessary to produce the layout it needs.
102/// But the size does need to be exactly right or else things like struct
103/// layout will break.
104llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
105 if (T->isConstantMatrixType()) {
106 const Type *Ty = Context.getCanonicalType(T).getTypePtr();
107 const ConstantMatrixType *MT = cast<ConstantMatrixType>(Val: Ty);
108 llvm::Type *IRElemTy = ConvertType(T: MT->getElementType());
109 if (Context.getLangOpts().HLSL) {
110 if (T->isConstantMatrixBoolType())
111 IRElemTy = ConvertTypeForMem(T: Context.BoolTy);
112
113 unsigned NumRows = MT->getNumRows();
114 unsigned NumCols = MT->getNumColumns();
115 bool IsRowMajor = isMatrixRowMajor(LangOpts: Context.getLangOpts(), T);
116 unsigned VecLen = IsRowMajor ? NumCols : NumRows;
117 unsigned ArrayLen = IsRowMajor ? NumRows : NumCols;
118 llvm::Type *VecTy = llvm::FixedVectorType::get(ElementType: IRElemTy, NumElts: VecLen);
119 return llvm::ArrayType::get(ElementType: VecTy, NumElements: ArrayLen);
120 }
121 return llvm::ArrayType::get(ElementType: IRElemTy, NumElements: MT->getNumElementsFlattened());
122 }
123
124 llvm::Type *R = ConvertType(T);
125
126 // Check for the boolean vector case.
127 if (T->isExtVectorBoolType()) {
128 auto *FixedVT = cast<llvm::FixedVectorType>(Val: R);
129
130 if (Context.getLangOpts().HLSL) {
131 llvm::Type *IRElemTy = ConvertTypeForMem(T: Context.BoolTy);
132 return llvm::FixedVectorType::get(ElementType: IRElemTy, NumElts: FixedVT->getNumElements());
133 }
134
135 // Pad to at least one byte.
136 uint64_t BytePadded = std::max<uint64_t>(a: FixedVT->getNumElements(), b: 8);
137 return llvm::IntegerType::get(C&: FixedVT->getContext(), NumBits: BytePadded);
138 }
139
140 // If T is _Bool or a _BitInt type, ConvertType will produce an IR type
141 // with the exact semantic bit-width of the AST type; for example,
142 // _BitInt(17) will turn into i17. In memory, however, we need to store
143 // such values extended to their full storage size as decided by AST
144 // layout; this is an ABI requirement. Ideally, we would always use an
145 // integer type that's just the bit-size of the AST type; for example, if
146 // sizeof(_BitInt(17)) == 4, _BitInt(17) would turn into i32. That is what's
147 // returned by convertTypeForLoadStore. However, that type does not
148 // always satisfy the size requirement on memory representation types
149 // describe above. For example, a 32-bit platform might reasonably set
150 // sizeof(_BitInt(65)) == 12, but i96 is likely to have to have an alloc size
151 // of 16 bytes in the LLVM data layout. In these cases, we simply return
152 // a byte array of the appropriate size.
153 if (T->isBitIntType()) {
154 if (typeRequiresSplitIntoByteArray(ASTTy: T, LLVMTy: R))
155 return llvm::ArrayType::get(ElementType: CGM.Int8Ty,
156 NumElements: Context.getTypeSizeInChars(T).getQuantity());
157 return llvm::IntegerType::get(C&: getLLVMContext(),
158 NumBits: (unsigned)Context.getTypeSize(T));
159 }
160
161 if (R->isIntegerTy(BitWidth: 1))
162 return llvm::IntegerType::get(C&: getLLVMContext(),
163 NumBits: (unsigned)Context.getTypeSize(T));
164
165 // Else, don't map it.
166 return R;
167}
168
169bool CodeGenTypes::typeRequiresSplitIntoByteArray(QualType ASTTy,
170 llvm::Type *LLVMTy) {
171 if (!LLVMTy)
172 LLVMTy = ConvertType(T: ASTTy);
173
174 CharUnits ASTSize = Context.getTypeSizeInChars(T: ASTTy);
175 CharUnits LLVMSize =
176 CharUnits::fromQuantity(Quantity: getDataLayout().getTypeAllocSize(Ty: LLVMTy));
177 return ASTSize != LLVMSize;
178}
179
180llvm::Type *CodeGenTypes::convertTypeForLoadStore(QualType T,
181 llvm::Type *LLVMTy) {
182 if (!LLVMTy)
183 LLVMTy = ConvertType(T);
184
185 if (T->isBitIntType())
186 return llvm::Type::getIntNTy(
187 C&: getLLVMContext(), N: Context.getTypeSizeInChars(T).getQuantity() * 8);
188
189 if (LLVMTy->isIntegerTy(BitWidth: 1))
190 return llvm::IntegerType::get(C&: getLLVMContext(),
191 NumBits: (unsigned)Context.getTypeSize(T));
192
193 if (T->isConstantMatrixBoolType()) {
194 // Matrices are loaded and stored atomically as vectors. Therefore we
195 // construct a FixedVectorType here instead of returning
196 // ConvertTypeForMem(T) which would return an ArrayType instead.
197 const Type *Ty = Context.getCanonicalType(T).getTypePtr();
198 const ConstantMatrixType *MT = cast<ConstantMatrixType>(Val: Ty);
199 llvm::Type *IRElemTy = ConvertTypeForMem(T: MT->getElementType());
200 return llvm::FixedVectorType::get(ElementType: IRElemTy, NumElts: MT->getNumElementsFlattened());
201 }
202
203 if (T->isExtVectorBoolType())
204 return ConvertTypeForMem(T);
205
206 return LLVMTy;
207}
208
209/// isRecordLayoutComplete - Return true if the specified type is already
210/// completely laid out.
211bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const {
212 llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
213 RecordDeclTypes.find(Val: Ty);
214 return I != RecordDeclTypes.end() && !I->second->isOpaque();
215}
216
217/// isFuncParamTypeConvertible - Return true if the specified type in a
218/// function parameter or result position can be converted to an IR type at this
219/// point. This boils down to being whether it is complete.
220bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) {
221 // Some ABIs cannot have their member pointers represented in IR unless
222 // certain circumstances have been reached.
223 if (const auto *MPT = Ty->getAs<MemberPointerType>())
224 return getCXXABI().isMemberPointerConvertible(MPT);
225
226 // If this isn't a tagged type, we can convert it!
227 const TagType *TT = Ty->getAs<TagType>();
228 if (!TT) return true;
229
230 // Incomplete types cannot be converted.
231 return !TT->isIncompleteType();
232}
233
234
235/// Code to verify a given function type is complete, i.e. the return type
236/// and all of the parameter types are complete. Also check to see if we are in
237/// a RS_StructPointer context, and if so whether any struct types have been
238/// pended. If so, we don't want to ask the ABI lowering code to handle a type
239/// that cannot be converted to an IR type.
240bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) {
241 if (!isFuncParamTypeConvertible(Ty: FT->getReturnType()))
242 return false;
243
244 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Val: FT))
245 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
246 if (!isFuncParamTypeConvertible(Ty: FPT->getParamType(i)))
247 return false;
248
249 return true;
250}
251
252/// UpdateCompletedType - When we find the full definition for a TagDecl,
253/// replace the 'opaque' type we previously made for it if applicable.
254void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
255 CanQualType T = CGM.getContext().getCanonicalTagType(TD);
256 // If this is an enum being completed, then we flush all non-struct types from
257 // the cache. This allows function types and other things that may be derived
258 // from the enum to be recomputed.
259 if (const EnumDecl *ED = dyn_cast<EnumDecl>(Val: TD)) {
260 // Only flush the cache if we've actually already converted this type.
261 if (TypeCache.count(Val: T->getTypePtr())) {
262 // Okay, we formed some types based on this. We speculated that the enum
263 // would be lowered to i32, so we only need to flush the cache if this
264 // didn't happen.
265 if (!ConvertType(T: ED->getIntegerType())->isIntegerTy(BitWidth: 32))
266 TypeCache.clear();
267 }
268 // If necessary, provide the full definition of a type only used with a
269 // declaration so far.
270 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
271 DI->completeType(ED);
272 return;
273 }
274
275 // If we completed a RecordDecl that we previously used and converted to an
276 // anonymous type, then go ahead and complete it now.
277 const RecordDecl *RD = cast<RecordDecl>(Val: TD);
278 if (RD->isDependentType()) return;
279
280 // Only complete it if we converted it already. If we haven't converted it
281 // yet, we'll just do it lazily.
282 if (RecordDeclTypes.count(Val: T.getTypePtr()))
283 ConvertRecordDeclType(TD: RD);
284
285 // If necessary, provide the full definition of a type only used with a
286 // declaration so far.
287 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
288 DI->completeType(RD);
289}
290
291void CodeGenTypes::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
292 CanQualType T = Context.getCanonicalTagType(TD: RD);
293 T = Context.getCanonicalType(T);
294
295 const Type *Ty = T.getTypePtr();
296 if (RecordsWithOpaqueMemberPointers.count(Val: Ty)) {
297 TypeCache.clear();
298 RecordsWithOpaqueMemberPointers.clear();
299 }
300}
301
302llvm::Type *CodeGenTypes::ConvertFunctionTypeInternal(QualType QFT) {
303 assert(QFT.isCanonical());
304 const FunctionType *FT = cast<FunctionType>(Val: QFT.getTypePtr());
305 // First, check whether we can build the full function type. If the
306 // function type depends on an incomplete type (e.g. a struct or enum), we
307 // cannot lower the function type.
308 if (!isFuncTypeConvertible(FT)) {
309 // This function's type depends on an incomplete tag type.
310
311 // Force conversion of all the relevant record types, to make sure
312 // we re-convert the FunctionType when appropriate.
313 if (const auto *RD = FT->getReturnType()->getAsRecordDecl())
314 ConvertRecordDeclType(TD: RD);
315 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Val: FT))
316 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
317 if (const auto *RD = FPT->getParamType(i)->getAsRecordDecl())
318 ConvertRecordDeclType(TD: RD);
319
320 SkippedLayout = true;
321
322 // Return a placeholder type.
323 return llvm::StructType::get(Context&: getLLVMContext());
324 }
325
326 // The function type can be built; call the appropriate routines to
327 // build it.
328 const CGFunctionInfo *FI;
329 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Val: FT)) {
330 FI = &arrangeFreeFunctionType(
331 Ty: CanQual<FunctionProtoType>::CreateUnsafe(Other: QualType(FPT, 0)));
332 } else {
333 const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(Val: FT);
334 FI = &arrangeFreeFunctionType(
335 Ty: CanQual<FunctionNoProtoType>::CreateUnsafe(Other: QualType(FNPT, 0)));
336 }
337
338 llvm::Type *ResultType = nullptr;
339 // If there is something higher level prodding our CGFunctionInfo, then
340 // don't recurse into it again.
341 if (FunctionsBeingProcessed.count(Ptr: FI)) {
342
343 ResultType = llvm::StructType::get(Context&: getLLVMContext());
344 SkippedLayout = true;
345 } else {
346
347 // Otherwise, we're good to go, go ahead and convert it.
348 ResultType = GetFunctionType(Info: *FI);
349 }
350
351 return ResultType;
352}
353
354/// ConvertType - Convert the specified type to its LLVM form.
355llvm::Type *CodeGenTypes::ConvertType(QualType T) {
356 T = Context.getCanonicalType(T);
357
358 const Type *Ty = T.getTypePtr();
359
360 // For the device-side compilation, CUDA device builtin surface/texture types
361 // may be represented in different types.
362 if (Context.getLangOpts().CUDAIsDevice) {
363 if (T->isCUDADeviceBuiltinSurfaceType()) {
364 if (auto *Ty = CGM.getTargetCodeGenInfo()
365 .getCUDADeviceBuiltinSurfaceDeviceType())
366 return Ty;
367 } else if (T->isCUDADeviceBuiltinTextureType()) {
368 if (auto *Ty = CGM.getTargetCodeGenInfo()
369 .getCUDADeviceBuiltinTextureDeviceType())
370 return Ty;
371 }
372 }
373
374 // RecordTypes are cached and processed specially.
375 if (const auto *RT = dyn_cast<RecordType>(Val: Ty))
376 return ConvertRecordDeclType(TD: RT->getDecl()->getDefinitionOrSelf());
377
378 llvm::Type *CachedType = nullptr;
379 auto TCI = TypeCache.find(Val: Ty);
380 if (TCI != TypeCache.end())
381 CachedType = TCI->second;
382 // With expensive checks, check that the type we compute matches the
383 // cached type.
384#ifndef EXPENSIVE_CHECKS
385 if (CachedType)
386 return CachedType;
387#endif
388
389 // If we don't have it in the cache, convert it now.
390 llvm::Type *ResultType = nullptr;
391 switch (Ty->getTypeClass()) {
392 case Type::Record: // Handled above.
393#define TYPE(Class, Base)
394#define ABSTRACT_TYPE(Class, Base)
395#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
396#define DEPENDENT_TYPE(Class, Base) case Type::Class:
397#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
398#include "clang/AST/TypeNodes.inc"
399 llvm_unreachable("Non-canonical or dependent types aren't possible.");
400
401 case Type::Builtin: {
402 switch (cast<BuiltinType>(Val: Ty)->getKind()) {
403 case BuiltinType::Void:
404 case BuiltinType::ObjCId:
405 case BuiltinType::ObjCClass:
406 case BuiltinType::ObjCSel:
407 // LLVM void type can only be used as the result of a function call. Just
408 // map to the same as char.
409 ResultType = llvm::Type::getInt8Ty(C&: getLLVMContext());
410 break;
411
412 case BuiltinType::Bool:
413 // Note that we always return bool as i1 for use as a scalar type.
414 ResultType = llvm::Type::getInt1Ty(C&: getLLVMContext());
415 break;
416
417 case BuiltinType::Char_S:
418 case BuiltinType::Char_U:
419 case BuiltinType::SChar:
420 case BuiltinType::UChar:
421 case BuiltinType::Short:
422 case BuiltinType::UShort:
423 case BuiltinType::Int:
424 case BuiltinType::UInt:
425 case BuiltinType::Long:
426 case BuiltinType::ULong:
427 case BuiltinType::LongLong:
428 case BuiltinType::ULongLong:
429 case BuiltinType::WChar_S:
430 case BuiltinType::WChar_U:
431 case BuiltinType::Char8:
432 case BuiltinType::Char16:
433 case BuiltinType::Char32:
434 case BuiltinType::ShortAccum:
435 case BuiltinType::Accum:
436 case BuiltinType::LongAccum:
437 case BuiltinType::UShortAccum:
438 case BuiltinType::UAccum:
439 case BuiltinType::ULongAccum:
440 case BuiltinType::ShortFract:
441 case BuiltinType::Fract:
442 case BuiltinType::LongFract:
443 case BuiltinType::UShortFract:
444 case BuiltinType::UFract:
445 case BuiltinType::ULongFract:
446 case BuiltinType::SatShortAccum:
447 case BuiltinType::SatAccum:
448 case BuiltinType::SatLongAccum:
449 case BuiltinType::SatUShortAccum:
450 case BuiltinType::SatUAccum:
451 case BuiltinType::SatULongAccum:
452 case BuiltinType::SatShortFract:
453 case BuiltinType::SatFract:
454 case BuiltinType::SatLongFract:
455 case BuiltinType::SatUShortFract:
456 case BuiltinType::SatUFract:
457 case BuiltinType::SatULongFract:
458 ResultType = llvm::IntegerType::get(C&: getLLVMContext(),
459 NumBits: static_cast<unsigned>(Context.getTypeSize(T)));
460 break;
461
462 case BuiltinType::Float16:
463 ResultType = llvm::Type::getFloatingPointTy(
464 C&: getLLVMContext(), S: Context.getFloatTypeSemantics(T));
465 break;
466
467 case BuiltinType::Half:
468 // Half FP can either be storage-only (lowered to i16 for ABI purposes) or
469 // native.
470 ResultType = llvm::Type::getFloatingPointTy(
471 C&: getLLVMContext(), S: Context.getFloatTypeSemantics(T));
472 break;
473 case BuiltinType::LongDouble:
474 LongDoubleReferenced = true;
475 [[fallthrough]];
476 case BuiltinType::BFloat16:
477 case BuiltinType::Float:
478 case BuiltinType::Double:
479 case BuiltinType::Float128:
480 case BuiltinType::Ibm128:
481 ResultType = llvm::Type::getFloatingPointTy(
482 C&: getLLVMContext(), S: Context.getFloatTypeSemantics(T));
483 break;
484
485 case BuiltinType::NullPtr:
486 // Model std::nullptr_t as i8*
487 ResultType = llvm::PointerType::getUnqual(C&: getLLVMContext());
488 break;
489
490 case BuiltinType::UInt128:
491 case BuiltinType::Int128:
492 ResultType = llvm::IntegerType::get(C&: getLLVMContext(), NumBits: 128);
493 break;
494
495#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
496 case BuiltinType::Id:
497#include "clang/Basic/OpenCLImageTypes.def"
498#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
499 case BuiltinType::Id:
500#include "clang/Basic/OpenCLExtensionTypes.def"
501 case BuiltinType::OCLSampler:
502 case BuiltinType::OCLEvent:
503 case BuiltinType::OCLClkEvent:
504 case BuiltinType::OCLQueue:
505 case BuiltinType::OCLReserveID:
506 ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(T: Ty);
507 break;
508#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
509 case BuiltinType::Id:
510#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
511 case BuiltinType::Id:
512#include "clang/Basic/AArch64ACLETypes.def"
513 {
514 ASTContext::BuiltinVectorTypeInfo Info =
515 Context.getBuiltinVectorTypeInfo(VecTy: cast<BuiltinType>(Val: Ty));
516 // The `__mfp8` type maps to `<1 x i8>` which can't be used to build
517 // a <N x i8> vector type, hence bypass the call to `ConvertType` for
518 // the element type and create the vector type directly.
519 auto *EltTy = Info.ElementType->isMFloat8Type()
520 ? llvm::Type::getInt8Ty(C&: getLLVMContext())
521 : ConvertType(T: Info.ElementType);
522 auto *VTy = llvm::VectorType::get(ElementType: EltTy, EC: Info.EC);
523 switch (Info.NumVectors) {
524 default:
525 llvm_unreachable("Expected 1, 2, 3 or 4 vectors!");
526 case 1:
527 return VTy;
528 case 2:
529 return llvm::StructType::get(elt1: VTy, elts: VTy);
530 case 3:
531 return llvm::StructType::get(elt1: VTy, elts: VTy, elts: VTy);
532 case 4:
533 return llvm::StructType::get(elt1: VTy, elts: VTy, elts: VTy, elts: VTy);
534 }
535 }
536 case BuiltinType::SveCount:
537 return llvm::TargetExtType::get(Context&: getLLVMContext(), Name: "aarch64.svcount");
538 case BuiltinType::MFloat8:
539 return llvm::VectorType::get(ElementType: llvm::Type::getInt8Ty(C&: getLLVMContext()), NumElements: 1,
540 Scalable: false);
541#define PPC_VECTOR_TYPE(Name, Id, Size) \
542 case BuiltinType::Id: \
543 ResultType = \
544 llvm::FixedVectorType::get(ConvertType(Context.BoolTy), Size); \
545 break;
546#include "clang/Basic/PPCTypes.def"
547#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
548#include "clang/Basic/RISCVVTypes.def"
549 {
550 ASTContext::BuiltinVectorTypeInfo Info =
551 Context.getBuiltinVectorTypeInfo(VecTy: cast<BuiltinType>(Val: Ty));
552 if (Info.NumVectors != 1) {
553 unsigned I8EltCount =
554 Info.EC.getKnownMinValue() *
555 ConvertType(T: Info.ElementType)->getScalarSizeInBits() / 8;
556 return llvm::TargetExtType::get(
557 Context&: getLLVMContext(), Name: "riscv.vector.tuple",
558 Types: llvm::ScalableVectorType::get(
559 ElementType: llvm::Type::getInt8Ty(C&: getLLVMContext()), MinNumElts: I8EltCount),
560 Ints: Info.NumVectors);
561 }
562 return llvm::ScalableVectorType::get(ElementType: ConvertType(T: Info.ElementType),
563 MinNumElts: Info.EC.getKnownMinValue());
564 }
565#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
566 case BuiltinType::Id: { \
567 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
568 ResultType = CGM.getTargetCodeGenInfo().getWasmExternrefReferenceType(); \
569 else \
570 llvm_unreachable("Unexpected wasm reference builtin type!"); \
571 } break;
572#include "clang/Basic/WebAssemblyReferenceTypes.def"
573#define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \
574 case BuiltinType::Id: { \
575 if (BuiltinType::Id == BuiltinType::AMDGPUTexture) { \
576 return llvm::FixedVectorType::get( \
577 llvm::Type::getInt32Ty(getLLVMContext()), 8); \
578 } \
579 return llvm::PointerType::get(getLLVMContext(), AS); \
580 }
581#define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \
582 case BuiltinType::Id: \
583 return llvm::TargetExtType::get(getLLVMContext(), "amdgcn.named.barrier", \
584 {}, {Scope});
585#define AMDGPU_FEATURE_PREDICATE_TYPE(Name, Id, SingletonId, Width, Align) \
586 case BuiltinType::Id: \
587 return ConvertType(getContext().getLogicalOperationType());
588#include "clang/Basic/AMDGPUTypes.def"
589#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
590#include "clang/Basic/HLSLIntangibleTypes.def"
591 ResultType = CGM.getHLSLRuntime().convertHLSLSpecificType(T: Ty);
592 break;
593#define SPIRV_TYPE(Name, Id, SingletonId) \
594 case BuiltinType::Id: \
595 return llvm::TargetExtType::get(getLLVMContext(), "spirv.Event");
596#include "clang/Basic/SPIRVTypes.def"
597 case BuiltinType::Dependent:
598#define BUILTIN_TYPE(Id, SingletonId)
599#define PLACEHOLDER_TYPE(Id, SingletonId) \
600 case BuiltinType::Id:
601#include "clang/AST/BuiltinTypes.def"
602 llvm_unreachable("Unexpected placeholder builtin type!");
603 }
604 break;
605 }
606 case Type::Auto:
607 case Type::DeducedTemplateSpecialization:
608 llvm_unreachable("Unexpected undeduced type!");
609 case Type::Complex: {
610 llvm::Type *EltTy = ConvertType(T: cast<ComplexType>(Val: Ty)->getElementType());
611 ResultType = llvm::StructType::get(elt1: EltTy, elts: EltTy);
612 break;
613 }
614 case Type::LValueReference:
615 case Type::RValueReference: {
616 const ReferenceType *RTy = cast<ReferenceType>(Val: Ty);
617 QualType ETy = RTy->getPointeeType();
618 unsigned AS = getTargetAddressSpace(T: ETy);
619 ResultType = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: AS);
620 break;
621 }
622 case Type::Pointer: {
623 const PointerType *PTy = cast<PointerType>(Val: Ty);
624 QualType ETy = PTy->getPointeeType();
625 if (ETy.getAddressSpace() == LangAS::wasm_funcref) {
626 ResultType = CGM.getTargetCodeGenInfo().getWasmFuncrefReferenceType();
627 break;
628 }
629 unsigned AS = getTargetAddressSpace(T: ETy);
630 ResultType = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: AS);
631 break;
632 }
633
634 case Type::VariableArray: {
635 const VariableArrayType *A = cast<VariableArrayType>(Val: Ty);
636 assert(A->getIndexTypeCVRQualifiers() == 0 &&
637 "FIXME: We only handle trivial array types so far!");
638 // VLAs resolve to the innermost element type; this matches
639 // the return of alloca, and there isn't any obviously better choice.
640 ResultType = ConvertTypeForMem(T: A->getElementType());
641 break;
642 }
643 case Type::IncompleteArray: {
644 const IncompleteArrayType *A = cast<IncompleteArrayType>(Val: Ty);
645 assert(A->getIndexTypeCVRQualifiers() == 0 &&
646 "FIXME: We only handle trivial array types so far!");
647 // int X[] -> [0 x int], unless the element type is not sized. If it is
648 // unsized (e.g. an incomplete struct) just use [0 x i8].
649 ResultType = ConvertTypeForMem(T: A->getElementType());
650 if (!ResultType->isSized()) {
651 SkippedLayout = true;
652 ResultType = llvm::Type::getInt8Ty(C&: getLLVMContext());
653 }
654 ResultType = llvm::ArrayType::get(ElementType: ResultType, NumElements: 0);
655 break;
656 }
657 case Type::ArrayParameter:
658 case Type::ConstantArray: {
659 const ConstantArrayType *A = cast<ConstantArrayType>(Val: Ty);
660 llvm::Type *EltTy = ConvertTypeForMem(T: A->getElementType());
661
662 // Lower arrays of undefined struct type to arrays of i8 just to have a
663 // concrete type.
664 if (!EltTy->isSized()) {
665 SkippedLayout = true;
666 EltTy = llvm::Type::getInt8Ty(C&: getLLVMContext());
667 }
668
669 ResultType = llvm::ArrayType::get(ElementType: EltTy, NumElements: A->getZExtSize());
670 break;
671 }
672 case Type::ExtVector:
673 case Type::Vector: {
674 const auto *VT = cast<VectorType>(Val: Ty);
675 // An ext_vector_type of Bool is really a vector of bits.
676 llvm::Type *IRElemTy = VT->isPackedVectorBoolType(ctx: Context)
677 ? llvm::Type::getInt1Ty(C&: getLLVMContext())
678 : VT->getElementType()->isMFloat8Type()
679 ? llvm::Type::getInt8Ty(C&: getLLVMContext())
680 : ConvertType(T: VT->getElementType());
681 ResultType = llvm::FixedVectorType::get(ElementType: IRElemTy, NumElts: VT->getNumElements());
682 break;
683 }
684 case Type::ConstantMatrix: {
685 const ConstantMatrixType *MT = cast<ConstantMatrixType>(Val: Ty);
686 ResultType =
687 llvm::FixedVectorType::get(ElementType: ConvertType(T: MT->getElementType()),
688 NumElts: MT->getNumRows() * MT->getNumColumns());
689 break;
690 }
691 case Type::FunctionNoProto:
692 case Type::FunctionProto:
693 ResultType = ConvertFunctionTypeInternal(QFT: T);
694 break;
695 case Type::ObjCObject:
696 ResultType = ConvertType(T: cast<ObjCObjectType>(Val: Ty)->getBaseType());
697 break;
698
699 case Type::ObjCInterface: {
700 // Objective-C interfaces are always opaque (outside of the
701 // runtime, which can do whatever it likes); we never refine
702 // these.
703 llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Val: Ty)];
704 if (!T)
705 T = llvm::StructType::create(Context&: getLLVMContext());
706 ResultType = T;
707 break;
708 }
709
710 case Type::ObjCObjectPointer:
711 ResultType = llvm::PointerType::getUnqual(C&: getLLVMContext());
712 break;
713
714 case Type::Enum: {
715 const auto *ED = Ty->castAsEnumDecl();
716 if (ED->isCompleteDefinition() || ED->isFixed())
717 return ConvertType(T: ED->getIntegerType());
718 // Return a placeholder 'i32' type. This can be changed later when the
719 // type is defined (see UpdateCompletedType), but is likely to be the
720 // "right" answer.
721 ResultType = llvm::Type::getInt32Ty(C&: getLLVMContext());
722 break;
723 }
724
725 case Type::BlockPointer: {
726 // Block pointers lower to function type. For function type,
727 // getTargetAddressSpace() returns default address space for
728 // function pointer i.e. program address space. Therefore, for block
729 // pointers, it is important to pass the pointee AST address space when
730 // calling getTargetAddressSpace(), to ensure that we get the LLVM IR
731 // address space for data pointers and not function pointers.
732 const QualType FTy = cast<BlockPointerType>(Val: Ty)->getPointeeType();
733 unsigned AS = Context.getTargetAddressSpace(AS: FTy.getAddressSpace());
734 ResultType = llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: AS);
735 break;
736 }
737
738 case Type::MemberPointer: {
739 auto *MPTy = cast<MemberPointerType>(Val: Ty);
740 if (!getCXXABI().isMemberPointerConvertible(MPT: MPTy)) {
741 CanQualType T = CGM.getContext().getCanonicalTagType(
742 TD: MPTy->getMostRecentCXXRecordDecl());
743 auto Insertion =
744 RecordsWithOpaqueMemberPointers.try_emplace(Key: T.getTypePtr());
745 if (Insertion.second)
746 Insertion.first->second = llvm::StructType::create(Context&: getLLVMContext());
747 ResultType = Insertion.first->second;
748 } else {
749 ResultType = getCXXABI().ConvertMemberPointerType(MPT: MPTy);
750 }
751 break;
752 }
753
754 case Type::Atomic: {
755 QualType valueType = cast<AtomicType>(Val: Ty)->getValueType();
756 ResultType = ConvertTypeForMem(T: valueType);
757
758 // Pad out to the inflated size if necessary.
759 uint64_t valueSize = Context.getTypeSize(T: valueType);
760 uint64_t atomicSize = Context.getTypeSize(T: Ty);
761 if (valueSize != atomicSize) {
762 assert(valueSize < atomicSize);
763 llvm::Type *elts[] = {
764 ResultType,
765 llvm::ArrayType::get(ElementType: CGM.Int8Ty, NumElements: (atomicSize - valueSize) / 8)
766 };
767 ResultType =
768 llvm::StructType::get(Context&: getLLVMContext(), Elements: llvm::ArrayRef(elts));
769 }
770 break;
771 }
772 case Type::Pipe: {
773 ResultType = CGM.getOpenCLRuntime().getPipeType(T: cast<PipeType>(Val: Ty));
774 break;
775 }
776 case Type::BitInt: {
777 const auto &EIT = cast<BitIntType>(Val: Ty);
778 ResultType = llvm::Type::getIntNTy(C&: getLLVMContext(), N: EIT->getNumBits());
779 break;
780 }
781 case Type::HLSLAttributedResource:
782 case Type::HLSLInlineSpirv:
783 ResultType = CGM.getHLSLRuntime().convertHLSLSpecificType(T: Ty);
784 break;
785 case Type::OverflowBehavior:
786 ResultType =
787 ConvertType(T: dyn_cast<OverflowBehaviorType>(Val: Ty)->getUnderlyingType());
788 break;
789 }
790
791 assert(ResultType && "Didn't convert a type?");
792 assert((!CachedType || CachedType == ResultType) &&
793 "Cached type doesn't match computed type");
794
795 TypeCache[Ty] = ResultType;
796 return ResultType;
797}
798
799bool CodeGenModule::isPaddedAtomicType(QualType type) {
800 return isPaddedAtomicType(type: type->castAs<AtomicType>());
801}
802
803bool CodeGenModule::isPaddedAtomicType(const AtomicType *type) {
804 return Context.getTypeSize(T: type) != Context.getTypeSize(T: type->getValueType());
805}
806
807/// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
808llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
809 // TagDecl's are not necessarily unique, instead use the (clang)
810 // type connected to the decl.
811 const Type *Key = Context.getCanonicalTagType(TD: RD).getTypePtr();
812
813 llvm::StructType *&Entry = RecordDeclTypes[Key];
814
815 // If we don't have a StructType at all yet, create the forward declaration.
816 if (!Entry) {
817 Entry = llvm::StructType::create(Context&: getLLVMContext());
818 addRecordTypeName(RD, Ty: Entry, suffix: "");
819 }
820 llvm::StructType *Ty = Entry;
821
822 // If this is still a forward declaration, or the LLVM type is already
823 // complete, there's nothing more to do.
824 RD = RD->getDefinition();
825 if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
826 return Ty;
827
828 // Force conversion of non-virtual base classes recursively.
829 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
830 for (const auto &I : CRD->bases()) {
831 if (I.isVirtual()) continue;
832 ConvertRecordDeclType(RD: I.getType()->castAsRecordDecl());
833 }
834 }
835
836 // Layout fields.
837 std::unique_ptr<CGRecordLayout> Layout = ComputeRecordLayout(D: RD, Ty);
838 CGRecordLayouts[Key] = std::move(Layout);
839
840 // If this struct blocked a FunctionType conversion, then recompute whatever
841 // was derived from that.
842 // FIXME: This is hugely overconservative.
843 if (SkippedLayout)
844 TypeCache.clear();
845
846 return Ty;
847}
848
849/// getCGRecordLayout - Return record layout info for the given record decl.
850const CGRecordLayout &
851CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) {
852 const Type *Key = Context.getCanonicalTagType(TD: RD).getTypePtr();
853
854 auto I = CGRecordLayouts.find(Val: Key);
855 if (I != CGRecordLayouts.end())
856 return *I->second;
857 // Compute the type information.
858 ConvertRecordDeclType(RD);
859
860 // Now try again.
861 I = CGRecordLayouts.find(Val: Key);
862
863 assert(I != CGRecordLayouts.end() &&
864 "Unable to find record layout information for type");
865 return *I->second;
866}
867
868bool CodeGenTypes::isPointerZeroInitializable(QualType T) {
869 assert((T->isAnyPointerType() || T->isBlockPointerType() ||
870 T->isNullPtrType()) &&
871 "Invalid type");
872 return isZeroInitializable(T);
873}
874
875bool CodeGenTypes::isZeroInitializable(QualType T) {
876 if (T->getAs<PointerType>() || T->isNullPtrType())
877 return Context.getTargetNullPointerValue(QT: T) == 0;
878
879 if (const auto *AT = Context.getAsArrayType(T)) {
880 if (isa<IncompleteArrayType>(Val: AT))
881 return true;
882 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT))
883 if (Context.getConstantArrayElementCount(CA: CAT) == 0)
884 return true;
885 T = Context.getBaseElementType(QT: T);
886 }
887
888 // Records are non-zero-initializable if they contain any
889 // non-zero-initializable subobjects.
890 if (const auto *RD = T->getAsRecordDecl())
891 return isZeroInitializable(RD);
892
893 // We have to ask the ABI about member pointers.
894 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
895 return getCXXABI().isZeroInitializable(MPT);
896
897 // HLSL Inline SPIR-V types are non-zero-initializable.
898 if (T->getAs<HLSLInlineSpirvType>())
899 return false;
900
901 // Everything else is okay.
902 return true;
903}
904
905bool CodeGenTypes::isZeroInitializable(const RecordDecl *RD) {
906 return getCGRecordLayout(RD).isZeroInitializable();
907}
908
909unsigned CodeGenTypes::getTargetAddressSpace(QualType T) const {
910 // Return the address space for the type. If the type is a
911 // function type without an address space qualifier, the
912 // program address space is used. Otherwise, the target picks
913 // the best address space based on the type information
914 return T->isFunctionType() && !T.hasAddressSpace()
915 ? getDataLayout().getProgramAddressSpace()
916 : getContext().getTargetAddressSpace(AS: T.getAddressSpace());
917}
918