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