clang 23.0.0git
CodeGenTypes.cpp
Go to the documentation of this file.
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"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Module.h"
30
31using namespace clang;
32using namespace CodeGen;
33
35 : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
36 Target(cgm.getTarget()) {
37 SkippedLayout = false;
38 LongDoubleReferenced = false;
39}
40
42 for (llvm::FoldingSet<CGFunctionInfo>::iterator
43 I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
44 delete &*I++;
45}
46
48
50 return CGM.getCodeGenOpts();
51}
52
54 llvm::StructType *Ty,
55 StringRef suffix) {
57 llvm::raw_svector_ostream OS(TypeName);
58 OS << RD->getKindName() << '.';
59
60 // FIXME: We probably want to make more tweaks to the printing policy. For
61 // example, we should probably enable PrintCanonicalTypes and
62 // FullyQualifiedNames.
66
67 // Name the codegen type after the typedef name
68 // if there is no tag type name available
69 if (RD->getIdentifier()) {
70 // FIXME: We should not have to check for a null decl context here.
71 // Right now we do it because the implicit Obj-C decls don't have one.
72 if (RD->getDeclContext())
73 RD->printQualifiedName(OS, Policy);
74 else
75 RD->printName(OS, Policy);
76 } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
77 // FIXME: We should not have to check for a null decl context here.
78 // Right now we do it because the implicit Obj-C decls don't have one.
79 if (TDD->getDeclContext())
80 TDD->printQualifiedName(OS, Policy);
81 else
82 TDD->printName(OS);
83 } else
84 OS << "anon";
85
86 if (!suffix.empty())
87 OS << suffix;
88
89 Ty->setName(OS.str());
90}
91
92/// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from
93/// ConvertType in that it is used to convert to the memory representation for
94/// a type. For example, the scalar representation for _Bool is i1, but the
95/// memory representation is usually i8 or i32, depending on the target.
96///
97/// We generally assume that the alloc size of this type under the LLVM
98/// data layout is the same as the size of the AST type. The alignment
99/// does not have to match: Clang should always use explicit alignments
100/// and packed structs as necessary to produce the layout it needs.
101/// But the size does need to be exactly right or else things like struct
102/// layout will break.
104 if (T->isConstantMatrixType()) {
105 const Type *Ty = Context.getCanonicalType(T).getTypePtr();
107 llvm::Type *IRElemTy = ConvertType(MT->getElementType());
108 if (Context.getLangOpts().HLSL && T->isConstantMatrixBoolType())
109 IRElemTy = ConvertTypeForMem(Context.BoolTy);
110 return llvm::ArrayType::get(IRElemTy, MT->getNumElementsFlattened());
111 }
112
113 llvm::Type *R = ConvertType(T);
114
115 // Check for the boolean vector case.
116 if (T->isExtVectorBoolType()) {
117 auto *FixedVT = cast<llvm::FixedVectorType>(R);
118
119 if (Context.getLangOpts().HLSL) {
120 llvm::Type *IRElemTy = ConvertTypeForMem(Context.BoolTy);
121 return llvm::FixedVectorType::get(IRElemTy, FixedVT->getNumElements());
122 }
123
124 // Pad to at least one byte.
125 uint64_t BytePadded = std::max<uint64_t>(FixedVT->getNumElements(), 8);
126 return llvm::IntegerType::get(FixedVT->getContext(), BytePadded);
127 }
128
129 // If T is _Bool or a _BitInt type, ConvertType will produce an IR type
130 // with the exact semantic bit-width of the AST type; for example,
131 // _BitInt(17) will turn into i17. In memory, however, we need to store
132 // such values extended to their full storage size as decided by AST
133 // layout; this is an ABI requirement. Ideally, we would always use an
134 // integer type that's just the bit-size of the AST type; for example, if
135 // sizeof(_BitInt(17)) == 4, _BitInt(17) would turn into i32. That is what's
136 // returned by convertTypeForLoadStore. However, that type does not
137 // always satisfy the size requirement on memory representation types
138 // describe above. For example, a 32-bit platform might reasonably set
139 // sizeof(_BitInt(65)) == 12, but i96 is likely to have to have an alloc size
140 // of 16 bytes in the LLVM data layout. In these cases, we simply return
141 // a byte array of the appropriate size.
142 if (T->isBitIntType()) {
144 return llvm::ArrayType::get(CGM.Int8Ty,
145 Context.getTypeSizeInChars(T).getQuantity());
146 return llvm::IntegerType::get(getLLVMContext(),
147 (unsigned)Context.getTypeSize(T));
148 }
149
150 if (R->isIntegerTy(1))
151 return llvm::IntegerType::get(getLLVMContext(),
152 (unsigned)Context.getTypeSize(T));
153
154 // Else, don't map it.
155 return R;
156}
157
159 llvm::Type *LLVMTy) {
160 if (!LLVMTy)
161 LLVMTy = ConvertType(ASTTy);
162
163 CharUnits ASTSize = Context.getTypeSizeInChars(ASTTy);
164 CharUnits LLVMSize =
166 return ASTSize != LLVMSize;
167}
168
170 llvm::Type *LLVMTy) {
171 if (!LLVMTy)
172 LLVMTy = ConvertType(T);
173
174 if (T->isBitIntType())
175 return llvm::Type::getIntNTy(
176 getLLVMContext(), Context.getTypeSizeInChars(T).getQuantity() * 8);
177
178 if (LLVMTy->isIntegerTy(1))
179 return llvm::IntegerType::get(getLLVMContext(),
180 (unsigned)Context.getTypeSize(T));
181
182 if (T->isConstantMatrixBoolType()) {
183 // Matrices are loaded and stored atomically as vectors. Therefore we
184 // construct a FixedVectorType here instead of returning
185 // ConvertTypeForMem(T) which would return an ArrayType instead.
186 const Type *Ty = Context.getCanonicalType(T).getTypePtr();
188 llvm::Type *IRElemTy = ConvertTypeForMem(MT->getElementType());
189 return llvm::FixedVectorType::get(IRElemTy, MT->getNumElementsFlattened());
190 }
191
192 if (T->isExtVectorBoolType())
193 return ConvertTypeForMem(T);
194
195 return LLVMTy;
196}
197
198/// isRecordLayoutComplete - Return true if the specified type is already
199/// completely laid out.
201 llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
202 RecordDeclTypes.find(Ty);
203 return I != RecordDeclTypes.end() && !I->second->isOpaque();
204}
205
206/// isFuncParamTypeConvertible - Return true if the specified type in a
207/// function parameter or result position can be converted to an IR type at this
208/// point. This boils down to being whether it is complete.
210 // Some ABIs cannot have their member pointers represented in IR unless
211 // certain circumstances have been reached.
212 if (const auto *MPT = Ty->getAs<MemberPointerType>())
214
215 // If this isn't a tagged type, we can convert it!
216 const TagType *TT = Ty->getAs<TagType>();
217 if (!TT) return true;
218
219 // Incomplete types cannot be converted.
220 return !TT->isIncompleteType();
221}
222
223
224/// Code to verify a given function type is complete, i.e. the return type
225/// and all of the parameter types are complete. Also check to see if we are in
226/// a RS_StructPointer context, and if so whether any struct types have been
227/// pended. If so, we don't want to ask the ABI lowering code to handle a type
228/// that cannot be converted to an IR type.
231 return false;
232
233 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
234 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
235 if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
236 return false;
237
238 return true;
239}
240
241/// UpdateCompletedType - When we find the full definition for a TagDecl,
242/// replace the 'opaque' type we previously made for it if applicable.
244 CanQualType T = CGM.getContext().getCanonicalTagType(TD);
245 // If this is an enum being completed, then we flush all non-struct types from
246 // the cache. This allows function types and other things that may be derived
247 // from the enum to be recomputed.
248 if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
249 // Only flush the cache if we've actually already converted this type.
250 if (TypeCache.count(T->getTypePtr())) {
251 // Okay, we formed some types based on this. We speculated that the enum
252 // would be lowered to i32, so we only need to flush the cache if this
253 // didn't happen.
254 if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
255 TypeCache.clear();
256 }
257 // If necessary, provide the full definition of a type only used with a
258 // declaration so far.
259 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
260 DI->completeType(ED);
261 return;
262 }
263
264 // If we completed a RecordDecl that we previously used and converted to an
265 // anonymous type, then go ahead and complete it now.
266 const RecordDecl *RD = cast<RecordDecl>(TD);
267 if (RD->isDependentType()) return;
268
269 // Only complete it if we converted it already. If we haven't converted it
270 // yet, we'll just do it lazily.
271 if (RecordDeclTypes.count(T.getTypePtr()))
273
274 // If necessary, provide the full definition of a type only used with a
275 // declaration so far.
276 if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
277 DI->completeType(RD);
278}
279
281 CanQualType T = Context.getCanonicalTagType(RD);
282 T = Context.getCanonicalType(T);
283
284 const Type *Ty = T.getTypePtr();
285 if (RecordsWithOpaqueMemberPointers.count(Ty)) {
286 TypeCache.clear();
287 RecordsWithOpaqueMemberPointers.clear();
288 }
289}
290
291static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
292 const llvm::fltSemantics &format,
293 bool UseNativeHalf = false) {
294 if (&format == &llvm::APFloat::IEEEhalf()) {
295 if (UseNativeHalf)
296 return llvm::Type::getHalfTy(VMContext);
297 else
298 return llvm::Type::getInt16Ty(VMContext);
299 }
300 if (&format == &llvm::APFloat::BFloat())
301 return llvm::Type::getBFloatTy(VMContext);
302 if (&format == &llvm::APFloat::IEEEsingle())
303 return llvm::Type::getFloatTy(VMContext);
304 if (&format == &llvm::APFloat::IEEEdouble())
305 return llvm::Type::getDoubleTy(VMContext);
306 if (&format == &llvm::APFloat::IEEEquad())
307 return llvm::Type::getFP128Ty(VMContext);
308 if (&format == &llvm::APFloat::PPCDoubleDouble())
309 return llvm::Type::getPPC_FP128Ty(VMContext);
310 if (&format == &llvm::APFloat::x87DoubleExtended())
311 return llvm::Type::getX86_FP80Ty(VMContext);
312 llvm_unreachable("Unknown float format!");
313}
314
315llvm::Type *CodeGenTypes::ConvertFunctionTypeInternal(QualType QFT) {
316 assert(QFT.isCanonical());
317 const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr());
318 // First, check whether we can build the full function type. If the
319 // function type depends on an incomplete type (e.g. a struct or enum), we
320 // cannot lower the function type.
321 if (!isFuncTypeConvertible(FT)) {
322 // This function's type depends on an incomplete tag type.
323
324 // Force conversion of all the relevant record types, to make sure
325 // we re-convert the FunctionType when appropriate.
326 if (const auto *RD = FT->getReturnType()->getAsRecordDecl())
328 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
329 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
330 if (const auto *RD = FPT->getParamType(i)->getAsRecordDecl())
332
333 SkippedLayout = true;
334
335 // Return a placeholder type.
336 return llvm::StructType::get(getLLVMContext());
337 }
338
339 // The function type can be built; call the appropriate routines to
340 // build it.
341 const CGFunctionInfo *FI;
342 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
345 } else {
346 const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
349 }
350
351 llvm::Type *ResultType = nullptr;
352 // If there is something higher level prodding our CGFunctionInfo, then
353 // don't recurse into it again.
354 if (FunctionsBeingProcessed.count(FI)) {
355
356 ResultType = llvm::StructType::get(getLLVMContext());
357 SkippedLayout = true;
358 } else {
359
360 // Otherwise, we're good to go, go ahead and convert it.
361 ResultType = GetFunctionType(*FI);
362 }
363
364 return ResultType;
365}
366
367/// ConvertType - Convert the specified type to its LLVM form.
369 T = Context.getCanonicalType(T);
370
371 const Type *Ty = T.getTypePtr();
372
373 // For the device-side compilation, CUDA device builtin surface/texture types
374 // may be represented in different types.
375 if (Context.getLangOpts().CUDAIsDevice) {
376 if (T->isCUDADeviceBuiltinSurfaceType()) {
377 if (auto *Ty = CGM.getTargetCodeGenInfo()
378 .getCUDADeviceBuiltinSurfaceDeviceType())
379 return Ty;
380 } else if (T->isCUDADeviceBuiltinTextureType()) {
381 if (auto *Ty = CGM.getTargetCodeGenInfo()
382 .getCUDADeviceBuiltinTextureDeviceType())
383 return Ty;
384 }
385 }
386
387 // RecordTypes are cached and processed specially.
388 if (const auto *RT = dyn_cast<RecordType>(Ty))
389 return ConvertRecordDeclType(RT->getDecl()->getDefinitionOrSelf());
390
391 llvm::Type *CachedType = nullptr;
392 auto TCI = TypeCache.find(Ty);
393 if (TCI != TypeCache.end())
394 CachedType = TCI->second;
395 // With expensive checks, check that the type we compute matches the
396 // cached type.
397#ifndef EXPENSIVE_CHECKS
398 if (CachedType)
399 return CachedType;
400#endif
401
402 // If we don't have it in the cache, convert it now.
403 llvm::Type *ResultType = nullptr;
404 switch (Ty->getTypeClass()) {
405 case Type::Record: // Handled above.
406#define TYPE(Class, Base)
407#define ABSTRACT_TYPE(Class, Base)
408#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
409#define DEPENDENT_TYPE(Class, Base) case Type::Class:
410#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
411#include "clang/AST/TypeNodes.inc"
412 llvm_unreachable("Non-canonical or dependent types aren't possible.");
413
414 case Type::Builtin: {
415 switch (cast<BuiltinType>(Ty)->getKind()) {
416 case BuiltinType::Void:
417 case BuiltinType::ObjCId:
418 case BuiltinType::ObjCClass:
419 case BuiltinType::ObjCSel:
420 // LLVM void type can only be used as the result of a function call. Just
421 // map to the same as char.
422 ResultType = llvm::Type::getInt8Ty(getLLVMContext());
423 break;
424
425 case BuiltinType::Bool:
426 // Note that we always return bool as i1 for use as a scalar type.
427 ResultType = llvm::Type::getInt1Ty(getLLVMContext());
428 break;
429
430 case BuiltinType::Char_S:
431 case BuiltinType::Char_U:
432 case BuiltinType::SChar:
433 case BuiltinType::UChar:
434 case BuiltinType::Short:
435 case BuiltinType::UShort:
436 case BuiltinType::Int:
437 case BuiltinType::UInt:
438 case BuiltinType::Long:
439 case BuiltinType::ULong:
440 case BuiltinType::LongLong:
441 case BuiltinType::ULongLong:
442 case BuiltinType::WChar_S:
443 case BuiltinType::WChar_U:
444 case BuiltinType::Char8:
445 case BuiltinType::Char16:
446 case BuiltinType::Char32:
447 case BuiltinType::ShortAccum:
448 case BuiltinType::Accum:
449 case BuiltinType::LongAccum:
450 case BuiltinType::UShortAccum:
451 case BuiltinType::UAccum:
452 case BuiltinType::ULongAccum:
453 case BuiltinType::ShortFract:
454 case BuiltinType::Fract:
455 case BuiltinType::LongFract:
456 case BuiltinType::UShortFract:
457 case BuiltinType::UFract:
458 case BuiltinType::ULongFract:
459 case BuiltinType::SatShortAccum:
460 case BuiltinType::SatAccum:
461 case BuiltinType::SatLongAccum:
462 case BuiltinType::SatUShortAccum:
463 case BuiltinType::SatUAccum:
464 case BuiltinType::SatULongAccum:
465 case BuiltinType::SatShortFract:
466 case BuiltinType::SatFract:
467 case BuiltinType::SatLongFract:
468 case BuiltinType::SatUShortFract:
469 case BuiltinType::SatUFract:
470 case BuiltinType::SatULongFract:
471 ResultType = llvm::IntegerType::get(getLLVMContext(),
472 static_cast<unsigned>(Context.getTypeSize(T)));
473 break;
474
475 case BuiltinType::Float16:
476 ResultType =
477 getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T),
478 /* UseNativeHalf = */ true);
479 break;
480
481 case BuiltinType::Half:
482 // Half FP can either be storage-only (lowered to i16) or native.
483 ResultType = getTypeForFormat(
484 getLLVMContext(), Context.getFloatTypeSemantics(T),
485 Context.getLangOpts().NativeHalfType ||
486 !Context.getTargetInfo().useFP16ConversionIntrinsics());
487 break;
488 case BuiltinType::LongDouble:
489 LongDoubleReferenced = true;
490 [[fallthrough]];
491 case BuiltinType::BFloat16:
492 case BuiltinType::Float:
493 case BuiltinType::Double:
494 case BuiltinType::Float128:
495 case BuiltinType::Ibm128:
496 ResultType = getTypeForFormat(getLLVMContext(),
497 Context.getFloatTypeSemantics(T),
498 /* UseNativeHalf = */ false);
499 break;
500
501 case BuiltinType::NullPtr:
502 // Model std::nullptr_t as i8*
503 ResultType = llvm::PointerType::getUnqual(getLLVMContext());
504 break;
505
506 case BuiltinType::UInt128:
507 case BuiltinType::Int128:
508 ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
509 break;
510
511#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
512 case BuiltinType::Id:
513#include "clang/Basic/OpenCLImageTypes.def"
514#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
515 case BuiltinType::Id:
516#include "clang/Basic/OpenCLExtensionTypes.def"
517 case BuiltinType::OCLSampler:
518 case BuiltinType::OCLEvent:
519 case BuiltinType::OCLClkEvent:
520 case BuiltinType::OCLQueue:
521 case BuiltinType::OCLReserveID:
522 ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
523 break;
524#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
525 case BuiltinType::Id:
526#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
527 case BuiltinType::Id:
528#include "clang/Basic/AArch64ACLETypes.def"
529 {
531 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
532 // The `__mfp8` type maps to `<1 x i8>` which can't be used to build
533 // a <N x i8> vector type, hence bypass the call to `ConvertType` for
534 // the element type and create the vector type directly.
535 auto *EltTy = Info.ElementType->isMFloat8Type()
536 ? llvm::Type::getInt8Ty(getLLVMContext())
537 : ConvertType(Info.ElementType);
538 auto *VTy = llvm::VectorType::get(EltTy, Info.EC);
539 switch (Info.NumVectors) {
540 default:
541 llvm_unreachable("Expected 1, 2, 3 or 4 vectors!");
542 case 1:
543 return VTy;
544 case 2:
545 return llvm::StructType::get(VTy, VTy);
546 case 3:
547 return llvm::StructType::get(VTy, VTy, VTy);
548 case 4:
549 return llvm::StructType::get(VTy, VTy, VTy, VTy);
550 }
551 }
552 case BuiltinType::SveCount:
553 return llvm::TargetExtType::get(getLLVMContext(), "aarch64.svcount");
554 case BuiltinType::MFloat8:
555 return llvm::VectorType::get(llvm::Type::getInt8Ty(getLLVMContext()), 1,
556 false);
557#define PPC_VECTOR_TYPE(Name, Id, Size) \
558 case BuiltinType::Id: \
559 ResultType = \
560 llvm::FixedVectorType::get(ConvertType(Context.BoolTy), Size); \
561 break;
562#include "clang/Basic/PPCTypes.def"
563#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
564#include "clang/Basic/RISCVVTypes.def"
565 {
567 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
568 if (Info.NumVectors != 1) {
569 unsigned I8EltCount =
570 Info.EC.getKnownMinValue() *
571 ConvertType(Info.ElementType)->getScalarSizeInBits() / 8;
572 return llvm::TargetExtType::get(
573 getLLVMContext(), "riscv.vector.tuple",
574 llvm::ScalableVectorType::get(
575 llvm::Type::getInt8Ty(getLLVMContext()), I8EltCount),
576 Info.NumVectors);
577 }
578 return llvm::ScalableVectorType::get(ConvertType(Info.ElementType),
579 Info.EC.getKnownMinValue());
580 }
581#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
582 case BuiltinType::Id: { \
583 if (BuiltinType::Id == BuiltinType::WasmExternRef) \
584 ResultType = CGM.getTargetCodeGenInfo().getWasmExternrefReferenceType(); \
585 else \
586 llvm_unreachable("Unexpected wasm reference builtin type!"); \
587 } break;
588#include "clang/Basic/WebAssemblyReferenceTypes.def"
589#define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \
590 case BuiltinType::Id: \
591 return llvm::PointerType::get(getLLVMContext(), AS);
592#define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \
593 case BuiltinType::Id: \
594 return llvm::TargetExtType::get(getLLVMContext(), "amdgcn.named.barrier", \
595 {}, {Scope});
596#include "clang/Basic/AMDGPUTypes.def"
597#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
598#include "clang/Basic/HLSLIntangibleTypes.def"
599 ResultType = CGM.getHLSLRuntime().convertHLSLSpecificType(Ty);
600 break;
601 case BuiltinType::Dependent:
602#define BUILTIN_TYPE(Id, SingletonId)
603#define PLACEHOLDER_TYPE(Id, SingletonId) \
604 case BuiltinType::Id:
605#include "clang/AST/BuiltinTypes.def"
606 llvm_unreachable("Unexpected placeholder builtin type!");
607 }
608 break;
609 }
610 case Type::Auto:
611 case Type::DeducedTemplateSpecialization:
612 llvm_unreachable("Unexpected undeduced type!");
613 case Type::Complex: {
614 llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
615 ResultType = llvm::StructType::get(EltTy, EltTy);
616 break;
617 }
618 case Type::LValueReference:
619 case Type::RValueReference: {
620 const ReferenceType *RTy = cast<ReferenceType>(Ty);
621 QualType ETy = RTy->getPointeeType();
622 unsigned AS = getTargetAddressSpace(ETy);
623 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
624 break;
625 }
626 case Type::Pointer: {
627 const PointerType *PTy = cast<PointerType>(Ty);
628 QualType ETy = PTy->getPointeeType();
629 unsigned AS = getTargetAddressSpace(ETy);
630 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
631 break;
632 }
633
634 case Type::VariableArray: {
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(A->getElementType());
641 break;
642 }
643 case Type::IncompleteArray: {
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(A->getElementType());
650 if (!ResultType->isSized()) {
651 SkippedLayout = true;
652 ResultType = llvm::Type::getInt8Ty(getLLVMContext());
653 }
654 ResultType = llvm::ArrayType::get(ResultType, 0);
655 break;
656 }
657 case Type::ArrayParameter:
658 case Type::ConstantArray: {
660 llvm::Type *EltTy = ConvertTypeForMem(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(getLLVMContext());
667 }
668
669 ResultType = llvm::ArrayType::get(EltTy, A->getZExtSize());
670 break;
671 }
672 case Type::ExtVector:
673 case Type::Vector: {
674 const auto *VT = cast<VectorType>(Ty);
675 // An ext_vector_type of Bool is really a vector of bits.
676 llvm::Type *IRElemTy = VT->isPackedVectorBoolType(Context)
677 ? llvm::Type::getInt1Ty(getLLVMContext())
678 : VT->getElementType()->isMFloat8Type()
679 ? llvm::Type::getInt8Ty(getLLVMContext())
680 : ConvertType(VT->getElementType());
681 ResultType = llvm::FixedVectorType::get(IRElemTy, VT->getNumElements());
682 break;
683 }
684 case Type::ConstantMatrix: {
686 ResultType =
687 llvm::FixedVectorType::get(ConvertType(MT->getElementType()),
688 MT->getNumRows() * MT->getNumColumns());
689 break;
690 }
691 case Type::FunctionNoProto:
692 case Type::FunctionProto:
693 ResultType = ConvertFunctionTypeInternal(T);
694 break;
695 case Type::ObjCObject:
696 ResultType = ConvertType(cast<ObjCObjectType>(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>(Ty)];
704 if (!T)
705 T = llvm::StructType::create(getLLVMContext());
706 ResultType = T;
707 break;
708 }
709
710 case Type::ObjCObjectPointer:
711 ResultType = llvm::PointerType::getUnqual(getLLVMContext());
712 break;
713
714 case Type::Enum: {
715 const auto *ED = Ty->castAsEnumDecl();
716 if (ED->isCompleteDefinition() || ED->isFixed())
717 return ConvertType(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(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>(Ty)->getPointeeType();
733 unsigned AS = Context.getTargetAddressSpace(FTy.getAddressSpace());
734 ResultType = llvm::PointerType::get(getLLVMContext(), AS);
735 break;
736 }
737
738 case Type::MemberPointer: {
739 auto *MPTy = cast<MemberPointerType>(Ty);
740 if (!getCXXABI().isMemberPointerConvertible(MPTy)) {
741 CanQualType T = CGM.getContext().getCanonicalTagType(
742 MPTy->getMostRecentCXXRecordDecl());
743 auto Insertion =
744 RecordsWithOpaqueMemberPointers.try_emplace(T.getTypePtr());
745 if (Insertion.second)
746 Insertion.first->second = llvm::StructType::create(getLLVMContext());
747 ResultType = Insertion.first->second;
748 } else {
749 ResultType = getCXXABI().ConvertMemberPointerType(MPTy);
750 }
751 break;
752 }
753
754 case Type::Atomic: {
755 QualType valueType = cast<AtomicType>(Ty)->getValueType();
756 ResultType = ConvertTypeForMem(valueType);
757
758 // Pad out to the inflated size if necessary.
759 uint64_t valueSize = Context.getTypeSize(valueType);
760 uint64_t atomicSize = Context.getTypeSize(Ty);
761 if (valueSize != atomicSize) {
762 assert(valueSize < atomicSize);
763 llvm::Type *elts[] = {
764 ResultType,
765 llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
766 };
767 ResultType =
768 llvm::StructType::get(getLLVMContext(), llvm::ArrayRef(elts));
769 }
770 break;
771 }
772 case Type::Pipe: {
773 ResultType = CGM.getOpenCLRuntime().getPipeType(cast<PipeType>(Ty));
774 break;
775 }
776 case Type::BitInt: {
777 const auto &EIT = cast<BitIntType>(Ty);
778 ResultType = llvm::Type::getIntNTy(getLLVMContext(), EIT->getNumBits());
779 break;
780 }
781 case Type::HLSLAttributedResource:
782 case Type::HLSLInlineSpirv:
783 ResultType = CGM.getHLSLRuntime().convertHLSLSpecificType(Ty);
784 break;
785 }
786
787 assert(ResultType && "Didn't convert a type?");
788 assert((!CachedType || CachedType == ResultType) &&
789 "Cached type doesn't match computed type");
790
791 TypeCache[Ty] = ResultType;
792 return ResultType;
793}
794
798
800 return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
801}
802
803/// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
805 // TagDecl's are not necessarily unique, instead use the (clang)
806 // type connected to the decl.
807 const Type *Key = Context.getCanonicalTagType(RD).getTypePtr();
808
809 llvm::StructType *&Entry = RecordDeclTypes[Key];
810
811 // If we don't have a StructType at all yet, create the forward declaration.
812 if (!Entry) {
813 Entry = llvm::StructType::create(getLLVMContext());
814 addRecordTypeName(RD, Entry, "");
815 }
816 llvm::StructType *Ty = Entry;
817
818 // If this is still a forward declaration, or the LLVM type is already
819 // complete, there's nothing more to do.
820 RD = RD->getDefinition();
821 if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
822 return Ty;
823
824 // Force conversion of non-virtual base classes recursively.
825 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
826 for (const auto &I : CRD->bases()) {
827 if (I.isVirtual()) continue;
828 ConvertRecordDeclType(I.getType()->castAsRecordDecl());
829 }
830 }
831
832 // Layout fields.
833 std::unique_ptr<CGRecordLayout> Layout = ComputeRecordLayout(RD, Ty);
834 CGRecordLayouts[Key] = std::move(Layout);
835
836 // If this struct blocked a FunctionType conversion, then recompute whatever
837 // was derived from that.
838 // FIXME: This is hugely overconservative.
839 if (SkippedLayout)
840 TypeCache.clear();
841
842 return Ty;
843}
844
845/// getCGRecordLayout - Return record layout info for the given record decl.
846const CGRecordLayout &
848 const Type *Key = Context.getCanonicalTagType(RD).getTypePtr();
849
850 auto I = CGRecordLayouts.find(Key);
851 if (I != CGRecordLayouts.end())
852 return *I->second;
853 // Compute the type information.
855
856 // Now try again.
857 I = CGRecordLayouts.find(Key);
858
859 assert(I != CGRecordLayouts.end() &&
860 "Unable to find record layout information for type");
861 return *I->second;
862}
863
865 assert((T->isAnyPointerType() || T->isBlockPointerType() ||
866 T->isNullPtrType()) &&
867 "Invalid type");
868 return isZeroInitializable(T);
869}
870
872 if (T->getAs<PointerType>() || T->isNullPtrType())
873 return Context.getTargetNullPointerValue(T) == 0;
874
875 if (const auto *AT = Context.getAsArrayType(T)) {
877 return true;
878 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
879 if (Context.getConstantArrayElementCount(CAT) == 0)
880 return true;
881 T = Context.getBaseElementType(T);
882 }
883
884 // Records are non-zero-initializable if they contain any
885 // non-zero-initializable subobjects.
886 if (const auto *RD = T->getAsRecordDecl())
887 return isZeroInitializable(RD);
888
889 // We have to ask the ABI about member pointers.
890 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
891 return getCXXABI().isZeroInitializable(MPT);
892
893 // HLSL Inline SPIR-V types are non-zero-initializable.
894 if (T->getAs<HLSLInlineSpirvType>())
895 return false;
896
897 // Everything else is okay.
898 return true;
899}
900
904
906 // Return the address space for the type. If the type is a
907 // function type without an address space qualifier, the
908 // program address space is used. Otherwise, the target picks
909 // the best address space based on the type information
910 return T->isFunctionType() && !T.hasAddressSpace()
911 ? getDataLayout().getProgramAddressSpace()
912 : getContext().getTargetAddressSpace(T.getAddressSpace());
913}
Defines the clang::ASTContext interface.
static llvm::Type * getTypeForFormat(llvm::LLVMContext &VMContext, const llvm::fltSemantics &format, bool UseNativeHalf=false)
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
static CharUnits getTypeAllocSize(CodeGenModule &CGM, llvm::Type *type)
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:843
unsigned getTargetAddressSpace(LangAS AS) const
QualType getElementType() const
Definition TypeBase.h:3735
unsigned getIndexTypeCVRQualifiers() const
Definition TypeBase.h:3745
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CanQual< T > CreateUnsafe(QualType Other)
Builds a canonical type from a QualType.
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
Implements C++ ABI-specific code generation functions.
Definition CGCXXABI.h:43
virtual bool isMemberPointerConvertible(const MemberPointerType *MPT) const
Return whether or not a member pointers type is convertible to an IR type.
Definition CGCXXABI.h:213
virtual llvm::Type * ConvertMemberPointerType(const MemberPointerType *MPT)
Find the LLVM type used to represent the given member pointer type.
Definition CGCXXABI.cpp:42
virtual bool isZeroInitializable(const MemberPointerType *MPT)
Return true if the given member pointer can be zero-initialized (in the C++ sense) with an LLVM zeroi...
Definition CGCXXABI.cpp:120
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
bool isZeroInitializable() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer.
This class organizes the cross-function state that is used while generating LLVM code.
bool isPaddedAtomicType(QualType type)
CodeGenTypes(CodeGenModule &cgm)
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
CGCXXABI & getCXXABI() const
bool isPointerZeroInitializable(QualType T)
Check if the pointer type can be zero-initialized (in the C++ sense) with an LLVM zeroinitializer.
const CodeGenOptions & getCodeGenOpts() const
ASTContext & getContext() const
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
Definition CGCall.cpp:251
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition CGCall.cpp:1703
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i....
const TargetInfo & getTarget() const
std::unique_ptr< CGRecordLayout > ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty)
Compute a new LLVM record layout object for the given record.
llvm::Type * convertTypeForLoadStore(QualType T, llvm::Type *LLVMTy=nullptr)
Given that T is a scalar type, return the IR type that should be used for load and store operations.
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
unsigned getTargetAddressSpace(QualType T) const
llvm::StructType * ConvertRecordDeclType(const RecordDecl *TD)
ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
void RefreshTypeCacheForClass(const CXXRecordDecl *RD)
Remove stale types from the type cache when an inheritance model gets assigned to a class.
bool isRecordLayoutComplete(const Type *Ty) const
isRecordLayoutComplete - Return true if the specified type is already completely laid out.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
CodeGenModule & getCGM() const
void UpdateCompletedType(const TagDecl *TD)
UpdateCompletedType - When we find the full definition for a TagDecl, replace the 'opaque' type we pr...
llvm::LLVMContext & getLLVMContext()
bool typeRequiresSplitIntoByteArray(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
Check whether the given type needs to be laid out in memory using an opaque byte-array type because i...
const llvm::DataLayout & getDataLayout() const
bool isFuncParamTypeConvertible(QualType Ty)
isFuncParamTypeConvertible - Return true if the specified type in a function parameter or result posi...
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
void addRecordTypeName(const RecordDecl *RD, llvm::StructType *Ty, StringRef suffix)
addRecordTypeName - Compute a name from the given record decl with an optional suffix and name the gi...
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3761
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3837
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4388
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4407
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4404
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4410
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
DeclContext * getDeclContext()
Definition DeclBase.h:448
Represents an enum.
Definition Decl.h:4010
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4465
QualType getReturnType() const
Definition TypeBase.h:4805
Represents a C array with an unspecified size.
Definition TypeBase.h:3910
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4352
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3654
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition Decl.cpp:1687
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3329
QualType getPointeeType() const
Definition TypeBase.h:3339
A (possibly-)qualified type.
Definition TypeBase.h:937
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8292
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8418
bool isCanonical() const
Definition TypeBase.h:8349
Represents a struct/union/class.
Definition Decl.h:4324
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4508
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3574
QualType getPointeeType() const
Definition TypeBase.h:3592
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
StringRef getKindName() const
Definition Decl.h:3910
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3815
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:3951
void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:5023
bool isDependentType() const
Whether this declaration declares a type that is dependent, i.e., a type that somehow depends on temp...
Definition Decl.h:3860
bool isMFloat8Type() const
Definition TypeBase.h:8916
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
TypeClass getTypeClass() const
Definition TypeBase.h:2385
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3967
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
Describes how types, statements, expressions, and declarations should be printed.
unsigned SuppressInlineNamespace
Suppress printing parts of scope specifiers that correspond to inline namespaces.