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 "CGOpenCLRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/CodeGen/CGFunctionInfo.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Module.h"
28 
29 using namespace clang;
30 using namespace CodeGen;
31 
32 #ifndef NDEBUG
33 #include "llvm/Support/CommandLine.h"
34 // TODO: turn on by default when defined(EXPENSIVE_CHECKS) once check-clang is
35 // -verify-type-cache clean.
36 static llvm::cl::opt<bool> VerifyTypeCache(
37     "verify-type-cache",
38     llvm::cl::desc("Verify that the type cache matches the computed type"),
39     llvm::cl::init(false), llvm::cl::Hidden);
40 #endif
41 
CodeGenTypes(CodeGenModule & cgm)42 CodeGenTypes::CodeGenTypes(CodeGenModule &cgm)
43   : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
44     Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()),
45     TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) {
46   SkippedLayout = false;
47 }
48 
~CodeGenTypes()49 CodeGenTypes::~CodeGenTypes() {
50   for (llvm::FoldingSet<CGFunctionInfo>::iterator
51        I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
52     delete &*I++;
53 }
54 
getCodeGenOpts() const55 const CodeGenOptions &CodeGenTypes::getCodeGenOpts() const {
56   return CGM.getCodeGenOpts();
57 }
58 
addRecordTypeName(const RecordDecl * RD,llvm::StructType * Ty,StringRef suffix)59 void CodeGenTypes::addRecordTypeName(const RecordDecl *RD,
60                                      llvm::StructType *Ty,
61                                      StringRef suffix) {
62   SmallString<256> TypeName;
63   llvm::raw_svector_ostream OS(TypeName);
64   OS << RD->getKindName() << '.';
65 
66   // FIXME: We probably want to make more tweaks to the printing policy. For
67   // example, we should probably enable PrintCanonicalTypes and
68   // FullyQualifiedNames.
69   PrintingPolicy Policy = RD->getASTContext().getPrintingPolicy();
70   Policy.SuppressInlineNamespace = false;
71 
72   // Name the codegen type after the typedef name
73   // if there is no tag type name available
74   if (RD->getIdentifier()) {
75     // FIXME: We should not have to check for a null decl context here.
76     // Right now we do it because the implicit Obj-C decls don't have one.
77     if (RD->getDeclContext())
78       RD->printQualifiedName(OS, Policy);
79     else
80       RD->printName(OS);
81   } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
82     // FIXME: We should not have to check for a null decl context here.
83     // Right now we do it because the implicit Obj-C decls don't have one.
84     if (TDD->getDeclContext())
85       TDD->printQualifiedName(OS, Policy);
86     else
87       TDD->printName(OS);
88   } else
89     OS << "anon";
90 
91   if (!suffix.empty())
92     OS << suffix;
93 
94   Ty->setName(OS.str());
95 }
96 
97 /// ConvertTypeForMem - Convert type T into a llvm::Type.  This differs from
98 /// ConvertType in that it is used to convert to the memory representation for
99 /// a type.  For example, the scalar representation for _Bool is i1, but the
100 /// memory representation is usually i8 or i32, depending on the target.
ConvertTypeForMem(QualType T,bool ForBitField)101 llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T, bool ForBitField) {
102   if (T->isConstantMatrixType()) {
103     const Type *Ty = Context.getCanonicalType(T).getTypePtr();
104     const ConstantMatrixType *MT = cast<ConstantMatrixType>(Ty);
105     return llvm::ArrayType::get(ConvertType(MT->getElementType()),
106                                 MT->getNumRows() * MT->getNumColumns());
107   }
108 
109   llvm::Type *R = ConvertType(T);
110 
111   // If this is a bool type, or an ExtIntType in a bitfield representation,
112   // map this integer to the target-specified size.
113   if ((ForBitField && T->isExtIntType()) ||
114       (!T->isExtIntType() && R->isIntegerTy(1)))
115     return llvm::IntegerType::get(getLLVMContext(),
116                                   (unsigned)Context.getTypeSize(T));
117 
118   // Else, don't map it.
119   return R;
120 }
121 
122 /// isRecordLayoutComplete - Return true if the specified type is already
123 /// completely laid out.
isRecordLayoutComplete(const Type * Ty) const124 bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const {
125   llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
126   RecordDeclTypes.find(Ty);
127   return I != RecordDeclTypes.end() && !I->second->isOpaque();
128 }
129 
130 static bool
131 isSafeToConvert(QualType T, CodeGenTypes &CGT,
132                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked);
133 
134 
135 /// isSafeToConvert - Return true if it is safe to convert the specified record
136 /// decl to IR and lay it out, false if doing so would cause us to get into a
137 /// recursive compilation mess.
138 static bool
isSafeToConvert(const RecordDecl * RD,CodeGenTypes & CGT,llvm::SmallPtrSet<const RecordDecl *,16> & AlreadyChecked)139 isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT,
140                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
141   // If we have already checked this type (maybe the same type is used by-value
142   // multiple times in multiple structure fields, don't check again.
143   if (!AlreadyChecked.insert(RD).second)
144     return true;
145 
146   const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr();
147 
148   // If this type is already laid out, converting it is a noop.
149   if (CGT.isRecordLayoutComplete(Key)) return true;
150 
151   // If this type is currently being laid out, we can't recursively compile it.
152   if (CGT.isRecordBeingLaidOut(Key))
153     return false;
154 
155   // If this type would require laying out bases that are currently being laid
156   // out, don't do it.  This includes virtual base classes which get laid out
157   // when a class is translated, even though they aren't embedded by-value into
158   // the class.
159   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
160     for (const auto &I : CRD->bases())
161       if (!isSafeToConvert(I.getType()->castAs<RecordType>()->getDecl(), CGT,
162                            AlreadyChecked))
163         return false;
164   }
165 
166   // If this type would require laying out members that are currently being laid
167   // out, don't do it.
168   for (const auto *I : RD->fields())
169     if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked))
170       return false;
171 
172   // If there are no problems, lets do it.
173   return true;
174 }
175 
176 /// isSafeToConvert - Return true if it is safe to convert this field type,
177 /// which requires the structure elements contained by-value to all be
178 /// recursively safe to convert.
179 static bool
isSafeToConvert(QualType T,CodeGenTypes & CGT,llvm::SmallPtrSet<const RecordDecl *,16> & AlreadyChecked)180 isSafeToConvert(QualType T, CodeGenTypes &CGT,
181                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
182   // Strip off atomic type sugar.
183   if (const auto *AT = T->getAs<AtomicType>())
184     T = AT->getValueType();
185 
186   // If this is a record, check it.
187   if (const auto *RT = T->getAs<RecordType>())
188     return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked);
189 
190   // If this is an array, check the elements, which are embedded inline.
191   if (const auto *AT = CGT.getContext().getAsArrayType(T))
192     return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked);
193 
194   // Otherwise, there is no concern about transforming this.  We only care about
195   // things that are contained by-value in a structure that can have another
196   // structure as a member.
197   return true;
198 }
199 
200 
201 /// isSafeToConvert - Return true if it is safe to convert the specified record
202 /// decl to IR and lay it out, false if doing so would cause us to get into a
203 /// recursive compilation mess.
isSafeToConvert(const RecordDecl * RD,CodeGenTypes & CGT)204 static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) {
205   // If no structs are being laid out, we can certainly do this one.
206   if (CGT.noRecordsBeingLaidOut()) return true;
207 
208   llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked;
209   return isSafeToConvert(RD, CGT, AlreadyChecked);
210 }
211 
212 /// isFuncParamTypeConvertible - Return true if the specified type in a
213 /// function parameter or result position can be converted to an IR type at this
214 /// point.  This boils down to being whether it is complete, as well as whether
215 /// we've temporarily deferred expanding the type because we're in a recursive
216 /// context.
isFuncParamTypeConvertible(QualType Ty)217 bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) {
218   // Some ABIs cannot have their member pointers represented in IR unless
219   // certain circumstances have been reached.
220   if (const auto *MPT = Ty->getAs<MemberPointerType>())
221     return getCXXABI().isMemberPointerConvertible(MPT);
222 
223   // If this isn't a tagged type, we can convert it!
224   const TagType *TT = Ty->getAs<TagType>();
225   if (!TT) return true;
226 
227   // Incomplete types cannot be converted.
228   if (TT->isIncompleteType())
229     return false;
230 
231   // If this is an enum, then it is always safe to convert.
232   const RecordType *RT = dyn_cast<RecordType>(TT);
233   if (!RT) return true;
234 
235   // Otherwise, we have to be careful.  If it is a struct that we're in the
236   // process of expanding, then we can't convert the function type.  That's ok
237   // though because we must be in a pointer context under the struct, so we can
238   // just convert it to a dummy type.
239   //
240   // We decide this by checking whether ConvertRecordDeclType returns us an
241   // opaque type for a struct that we know is defined.
242   return isSafeToConvert(RT->getDecl(), *this);
243 }
244 
245 
246 /// Code to verify a given function type is complete, i.e. the return type
247 /// and all of the parameter types are complete.  Also check to see if we are in
248 /// a RS_StructPointer context, and if so whether any struct types have been
249 /// pended.  If so, we don't want to ask the ABI lowering code to handle a type
250 /// that cannot be converted to an IR type.
isFuncTypeConvertible(const FunctionType * FT)251 bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) {
252   if (!isFuncParamTypeConvertible(FT->getReturnType()))
253     return false;
254 
255   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
256     for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
257       if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
258         return false;
259 
260   return true;
261 }
262 
263 /// UpdateCompletedType - When we find the full definition for a TagDecl,
264 /// replace the 'opaque' type we previously made for it if applicable.
UpdateCompletedType(const TagDecl * TD)265 void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
266   // If this is an enum being completed, then we flush all non-struct types from
267   // the cache.  This allows function types and other things that may be derived
268   // from the enum to be recomputed.
269   if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
270     // Only flush the cache if we've actually already converted this type.
271     if (TypeCache.count(ED->getTypeForDecl())) {
272       // Okay, we formed some types based on this.  We speculated that the enum
273       // would be lowered to i32, so we only need to flush the cache if this
274       // didn't happen.
275       if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
276         TypeCache.clear();
277     }
278     // If necessary, provide the full definition of a type only used with a
279     // declaration so far.
280     if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
281       DI->completeType(ED);
282     return;
283   }
284 
285   // If we completed a RecordDecl that we previously used and converted to an
286   // anonymous type, then go ahead and complete it now.
287   const RecordDecl *RD = cast<RecordDecl>(TD);
288   if (RD->isDependentType()) return;
289 
290   // Only complete it if we converted it already.  If we haven't converted it
291   // yet, we'll just do it lazily.
292   if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr()))
293     ConvertRecordDeclType(RD);
294 
295   // If necessary, provide the full definition of a type only used with a
296   // declaration so far.
297   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
298     DI->completeType(RD);
299 }
300 
RefreshTypeCacheForClass(const CXXRecordDecl * RD)301 void CodeGenTypes::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
302   QualType T = Context.getRecordType(RD);
303   T = Context.getCanonicalType(T);
304 
305   const Type *Ty = T.getTypePtr();
306   if (RecordsWithOpaqueMemberPointers.count(Ty)) {
307     TypeCache.clear();
308     RecordsWithOpaqueMemberPointers.clear();
309   }
310 }
311 
getTypeForFormat(llvm::LLVMContext & VMContext,const llvm::fltSemantics & format,bool UseNativeHalf=false)312 static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
313                                     const llvm::fltSemantics &format,
314                                     bool UseNativeHalf = false) {
315   if (&format == &llvm::APFloat::IEEEhalf()) {
316     if (UseNativeHalf)
317       return llvm::Type::getHalfTy(VMContext);
318     else
319       return llvm::Type::getInt16Ty(VMContext);
320   }
321   if (&format == &llvm::APFloat::BFloat())
322     return llvm::Type::getBFloatTy(VMContext);
323   if (&format == &llvm::APFloat::IEEEsingle())
324     return llvm::Type::getFloatTy(VMContext);
325   if (&format == &llvm::APFloat::IEEEdouble())
326     return llvm::Type::getDoubleTy(VMContext);
327   if (&format == &llvm::APFloat::IEEEquad())
328     return llvm::Type::getFP128Ty(VMContext);
329   if (&format == &llvm::APFloat::PPCDoubleDouble())
330     return llvm::Type::getPPC_FP128Ty(VMContext);
331   if (&format == &llvm::APFloat::x87DoubleExtended())
332     return llvm::Type::getX86_FP80Ty(VMContext);
333   llvm_unreachable("Unknown float format!");
334 }
335 
ConvertFunctionTypeInternal(QualType QFT)336 llvm::Type *CodeGenTypes::ConvertFunctionTypeInternal(QualType QFT) {
337   assert(QFT.isCanonical());
338   const Type *Ty = QFT.getTypePtr();
339   const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr());
340   // First, check whether we can build the full function type.  If the
341   // function type depends on an incomplete type (e.g. a struct or enum), we
342   // cannot lower the function type.
343   if (!isFuncTypeConvertible(FT)) {
344     // This function's type depends on an incomplete tag type.
345 
346     // Force conversion of all the relevant record types, to make sure
347     // we re-convert the FunctionType when appropriate.
348     if (const RecordType *RT = FT->getReturnType()->getAs<RecordType>())
349       ConvertRecordDeclType(RT->getDecl());
350     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
351       for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
352         if (const RecordType *RT = FPT->getParamType(i)->getAs<RecordType>())
353           ConvertRecordDeclType(RT->getDecl());
354 
355     SkippedLayout = true;
356 
357     // Return a placeholder type.
358     return llvm::StructType::get(getLLVMContext());
359   }
360 
361   // While we're converting the parameter types for a function, we don't want
362   // to recursively convert any pointed-to structs.  Converting directly-used
363   // structs is ok though.
364   if (!RecordsBeingLaidOut.insert(Ty).second) {
365     SkippedLayout = true;
366     return llvm::StructType::get(getLLVMContext());
367   }
368 
369   // The function type can be built; call the appropriate routines to
370   // build it.
371   const CGFunctionInfo *FI;
372   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
373     FI = &arrangeFreeFunctionType(
374         CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT, 0)));
375   } else {
376     const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
377     FI = &arrangeFreeFunctionType(
378         CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT, 0)));
379   }
380 
381   llvm::Type *ResultType = nullptr;
382   // If there is something higher level prodding our CGFunctionInfo, then
383   // don't recurse into it again.
384   if (FunctionsBeingProcessed.count(FI)) {
385 
386     ResultType = llvm::StructType::get(getLLVMContext());
387     SkippedLayout = true;
388   } else {
389 
390     // Otherwise, we're good to go, go ahead and convert it.
391     ResultType = GetFunctionType(*FI);
392   }
393 
394   RecordsBeingLaidOut.erase(Ty);
395 
396   if (RecordsBeingLaidOut.empty())
397     while (!DeferredRecords.empty())
398       ConvertRecordDeclType(DeferredRecords.pop_back_val());
399   return ResultType;
400 }
401 
402 /// ConvertType - Convert the specified type to its LLVM form.
ConvertType(QualType T)403 llvm::Type *CodeGenTypes::ConvertType(QualType T) {
404   T = Context.getCanonicalType(T);
405 
406   const Type *Ty = T.getTypePtr();
407 
408   // For the device-side compilation, CUDA device builtin surface/texture types
409   // may be represented in different types.
410   if (Context.getLangOpts().CUDAIsDevice) {
411     if (T->isCUDADeviceBuiltinSurfaceType()) {
412       if (auto *Ty = CGM.getTargetCodeGenInfo()
413                          .getCUDADeviceBuiltinSurfaceDeviceType())
414         return Ty;
415     } else if (T->isCUDADeviceBuiltinTextureType()) {
416       if (auto *Ty = CGM.getTargetCodeGenInfo()
417                          .getCUDADeviceBuiltinTextureDeviceType())
418         return Ty;
419     }
420   }
421 
422   // RecordTypes are cached and processed specially.
423   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
424     return ConvertRecordDeclType(RT->getDecl());
425 
426   // The LLVM type we return for a given Clang type may not always be the same,
427   // most notably when dealing with recursive structs. We mark these potential
428   // cases with ShouldUseCache below. Builtin types cannot be recursive.
429   // TODO: when clang uses LLVM opaque pointers we won't be able to represent
430   // recursive types with LLVM types, making this logic much simpler.
431   llvm::Type *CachedType = nullptr;
432   bool ShouldUseCache =
433       Ty->isBuiltinType() ||
434       (noRecordsBeingLaidOut() && FunctionsBeingProcessed.empty());
435   if (ShouldUseCache) {
436     llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI =
437         TypeCache.find(Ty);
438     if (TCI != TypeCache.end())
439       CachedType = TCI->second;
440     if (CachedType) {
441 #ifndef NDEBUG
442       if (!VerifyTypeCache)
443         return CachedType;
444 #else
445       return CachedType;
446 #endif
447     }
448   }
449 
450   // If we don't have it in the cache, convert it now.
451   llvm::Type *ResultType = nullptr;
452   switch (Ty->getTypeClass()) {
453   case Type::Record: // Handled above.
454 #define TYPE(Class, Base)
455 #define ABSTRACT_TYPE(Class, Base)
456 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
457 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
458 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
459 #include "clang/AST/TypeNodes.inc"
460     llvm_unreachable("Non-canonical or dependent types aren't possible.");
461 
462   case Type::Builtin: {
463     switch (cast<BuiltinType>(Ty)->getKind()) {
464     case BuiltinType::Void:
465     case BuiltinType::ObjCId:
466     case BuiltinType::ObjCClass:
467     case BuiltinType::ObjCSel:
468       // LLVM void type can only be used as the result of a function call.  Just
469       // map to the same as char.
470       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
471       break;
472 
473     case BuiltinType::Bool:
474       // Note that we always return bool as i1 for use as a scalar type.
475       ResultType = llvm::Type::getInt1Ty(getLLVMContext());
476       break;
477 
478     case BuiltinType::Char_S:
479     case BuiltinType::Char_U:
480     case BuiltinType::SChar:
481     case BuiltinType::UChar:
482     case BuiltinType::Short:
483     case BuiltinType::UShort:
484     case BuiltinType::Int:
485     case BuiltinType::UInt:
486     case BuiltinType::Long:
487     case BuiltinType::ULong:
488     case BuiltinType::LongLong:
489     case BuiltinType::ULongLong:
490     case BuiltinType::WChar_S:
491     case BuiltinType::WChar_U:
492     case BuiltinType::Char8:
493     case BuiltinType::Char16:
494     case BuiltinType::Char32:
495     case BuiltinType::ShortAccum:
496     case BuiltinType::Accum:
497     case BuiltinType::LongAccum:
498     case BuiltinType::UShortAccum:
499     case BuiltinType::UAccum:
500     case BuiltinType::ULongAccum:
501     case BuiltinType::ShortFract:
502     case BuiltinType::Fract:
503     case BuiltinType::LongFract:
504     case BuiltinType::UShortFract:
505     case BuiltinType::UFract:
506     case BuiltinType::ULongFract:
507     case BuiltinType::SatShortAccum:
508     case BuiltinType::SatAccum:
509     case BuiltinType::SatLongAccum:
510     case BuiltinType::SatUShortAccum:
511     case BuiltinType::SatUAccum:
512     case BuiltinType::SatULongAccum:
513     case BuiltinType::SatShortFract:
514     case BuiltinType::SatFract:
515     case BuiltinType::SatLongFract:
516     case BuiltinType::SatUShortFract:
517     case BuiltinType::SatUFract:
518     case BuiltinType::SatULongFract:
519       ResultType = llvm::IntegerType::get(getLLVMContext(),
520                                  static_cast<unsigned>(Context.getTypeSize(T)));
521       break;
522 
523     case BuiltinType::Float16:
524       ResultType =
525           getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T),
526                            /* UseNativeHalf = */ true);
527       break;
528 
529     case BuiltinType::Half:
530       // Half FP can either be storage-only (lowered to i16) or native.
531       ResultType = getTypeForFormat(
532           getLLVMContext(), Context.getFloatTypeSemantics(T),
533           Context.getLangOpts().NativeHalfType ||
534               !Context.getTargetInfo().useFP16ConversionIntrinsics());
535       break;
536     case BuiltinType::BFloat16:
537     case BuiltinType::Float:
538     case BuiltinType::Double:
539     case BuiltinType::LongDouble:
540     case BuiltinType::Float128:
541       ResultType = getTypeForFormat(getLLVMContext(),
542                                     Context.getFloatTypeSemantics(T),
543                                     /* UseNativeHalf = */ false);
544       break;
545 
546     case BuiltinType::NullPtr:
547       // Model std::nullptr_t as i8*
548       ResultType = llvm::Type::getInt8PtrTy(getLLVMContext());
549       break;
550 
551     case BuiltinType::UInt128:
552     case BuiltinType::Int128:
553       ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
554       break;
555 
556 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
557     case BuiltinType::Id:
558 #include "clang/Basic/OpenCLImageTypes.def"
559 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
560     case BuiltinType::Id:
561 #include "clang/Basic/OpenCLExtensionTypes.def"
562     case BuiltinType::OCLSampler:
563     case BuiltinType::OCLEvent:
564     case BuiltinType::OCLClkEvent:
565     case BuiltinType::OCLQueue:
566     case BuiltinType::OCLReserveID:
567       ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
568       break;
569     case BuiltinType::SveInt8:
570     case BuiltinType::SveUint8:
571     case BuiltinType::SveInt8x2:
572     case BuiltinType::SveUint8x2:
573     case BuiltinType::SveInt8x3:
574     case BuiltinType::SveUint8x3:
575     case BuiltinType::SveInt8x4:
576     case BuiltinType::SveUint8x4:
577     case BuiltinType::SveInt16:
578     case BuiltinType::SveUint16:
579     case BuiltinType::SveInt16x2:
580     case BuiltinType::SveUint16x2:
581     case BuiltinType::SveInt16x3:
582     case BuiltinType::SveUint16x3:
583     case BuiltinType::SveInt16x4:
584     case BuiltinType::SveUint16x4:
585     case BuiltinType::SveInt32:
586     case BuiltinType::SveUint32:
587     case BuiltinType::SveInt32x2:
588     case BuiltinType::SveUint32x2:
589     case BuiltinType::SveInt32x3:
590     case BuiltinType::SveUint32x3:
591     case BuiltinType::SveInt32x4:
592     case BuiltinType::SveUint32x4:
593     case BuiltinType::SveInt64:
594     case BuiltinType::SveUint64:
595     case BuiltinType::SveInt64x2:
596     case BuiltinType::SveUint64x2:
597     case BuiltinType::SveInt64x3:
598     case BuiltinType::SveUint64x3:
599     case BuiltinType::SveInt64x4:
600     case BuiltinType::SveUint64x4:
601     case BuiltinType::SveBool:
602     case BuiltinType::SveFloat16:
603     case BuiltinType::SveFloat16x2:
604     case BuiltinType::SveFloat16x3:
605     case BuiltinType::SveFloat16x4:
606     case BuiltinType::SveFloat32:
607     case BuiltinType::SveFloat32x2:
608     case BuiltinType::SveFloat32x3:
609     case BuiltinType::SveFloat32x4:
610     case BuiltinType::SveFloat64:
611     case BuiltinType::SveFloat64x2:
612     case BuiltinType::SveFloat64x3:
613     case BuiltinType::SveFloat64x4:
614     case BuiltinType::SveBFloat16:
615     case BuiltinType::SveBFloat16x2:
616     case BuiltinType::SveBFloat16x3:
617     case BuiltinType::SveBFloat16x4: {
618       ASTContext::BuiltinVectorTypeInfo Info =
619           Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
620       return llvm::ScalableVectorType::get(ConvertType(Info.ElementType),
621                                            Info.EC.getKnownMinValue() *
622                                                Info.NumVectors);
623     }
624 #define PPC_VECTOR_TYPE(Name, Id, Size) \
625     case BuiltinType::Id: \
626       ResultType = \
627         llvm::FixedVectorType::get(ConvertType(Context.BoolTy), Size); \
628       break;
629 #include "clang/Basic/PPCTypes.def"
630 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
631 #include "clang/Basic/RISCVVTypes.def"
632     {
633       ASTContext::BuiltinVectorTypeInfo Info =
634           Context.getBuiltinVectorTypeInfo(cast<BuiltinType>(Ty));
635       return llvm::ScalableVectorType::get(ConvertType(Info.ElementType),
636                                            Info.EC.getKnownMinValue() *
637                                            Info.NumVectors);
638     }
639    case BuiltinType::Dependent:
640 #define BUILTIN_TYPE(Id, SingletonId)
641 #define PLACEHOLDER_TYPE(Id, SingletonId) \
642     case BuiltinType::Id:
643 #include "clang/AST/BuiltinTypes.def"
644       llvm_unreachable("Unexpected placeholder builtin type!");
645     }
646     break;
647   }
648   case Type::Auto:
649   case Type::DeducedTemplateSpecialization:
650     llvm_unreachable("Unexpected undeduced type!");
651   case Type::Complex: {
652     llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
653     ResultType = llvm::StructType::get(EltTy, EltTy);
654     break;
655   }
656   case Type::LValueReference:
657   case Type::RValueReference: {
658     const ReferenceType *RTy = cast<ReferenceType>(Ty);
659     QualType ETy = RTy->getPointeeType();
660     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
661     unsigned AS = Context.getTargetAddressSpace(ETy);
662     ResultType = llvm::PointerType::get(PointeeType, AS);
663     break;
664   }
665   case Type::Pointer: {
666     const PointerType *PTy = cast<PointerType>(Ty);
667     QualType ETy = PTy->getPointeeType();
668     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
669     if (PointeeType->isVoidTy())
670       PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
671 
672     unsigned AS = PointeeType->isFunctionTy()
673                       ? getDataLayout().getProgramAddressSpace()
674                       : Context.getTargetAddressSpace(ETy);
675 
676     ResultType = llvm::PointerType::get(PointeeType, AS);
677     break;
678   }
679 
680   case Type::VariableArray: {
681     const VariableArrayType *A = cast<VariableArrayType>(Ty);
682     assert(A->getIndexTypeCVRQualifiers() == 0 &&
683            "FIXME: We only handle trivial array types so far!");
684     // VLAs resolve to the innermost element type; this matches
685     // the return of alloca, and there isn't any obviously better choice.
686     ResultType = ConvertTypeForMem(A->getElementType());
687     break;
688   }
689   case Type::IncompleteArray: {
690     const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
691     assert(A->getIndexTypeCVRQualifiers() == 0 &&
692            "FIXME: We only handle trivial array types so far!");
693     // int X[] -> [0 x int], unless the element type is not sized.  If it is
694     // unsized (e.g. an incomplete struct) just use [0 x i8].
695     ResultType = ConvertTypeForMem(A->getElementType());
696     if (!ResultType->isSized()) {
697       SkippedLayout = true;
698       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
699     }
700     ResultType = llvm::ArrayType::get(ResultType, 0);
701     break;
702   }
703   case Type::ConstantArray: {
704     const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
705     llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
706 
707     // Lower arrays of undefined struct type to arrays of i8 just to have a
708     // concrete type.
709     if (!EltTy->isSized()) {
710       SkippedLayout = true;
711       EltTy = llvm::Type::getInt8Ty(getLLVMContext());
712     }
713 
714     ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
715     break;
716   }
717   case Type::ExtVector:
718   case Type::Vector: {
719     const VectorType *VT = cast<VectorType>(Ty);
720     ResultType = llvm::FixedVectorType::get(ConvertType(VT->getElementType()),
721                                             VT->getNumElements());
722     break;
723   }
724   case Type::ConstantMatrix: {
725     const ConstantMatrixType *MT = cast<ConstantMatrixType>(Ty);
726     ResultType =
727         llvm::FixedVectorType::get(ConvertType(MT->getElementType()),
728                                    MT->getNumRows() * MT->getNumColumns());
729     break;
730   }
731   case Type::FunctionNoProto:
732   case Type::FunctionProto:
733     ResultType = ConvertFunctionTypeInternal(T);
734     break;
735   case Type::ObjCObject:
736     ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
737     break;
738 
739   case Type::ObjCInterface: {
740     // Objective-C interfaces are always opaque (outside of the
741     // runtime, which can do whatever it likes); we never refine
742     // these.
743     llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
744     if (!T)
745       T = llvm::StructType::create(getLLVMContext());
746     ResultType = T;
747     break;
748   }
749 
750   case Type::ObjCObjectPointer: {
751     // Protocol qualifications do not influence the LLVM type, we just return a
752     // pointer to the underlying interface type. We don't need to worry about
753     // recursive conversion.
754     llvm::Type *T =
755       ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
756     ResultType = T->getPointerTo();
757     break;
758   }
759 
760   case Type::Enum: {
761     const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
762     if (ED->isCompleteDefinition() || ED->isFixed())
763       return ConvertType(ED->getIntegerType());
764     // Return a placeholder 'i32' type.  This can be changed later when the
765     // type is defined (see UpdateCompletedType), but is likely to be the
766     // "right" answer.
767     ResultType = llvm::Type::getInt32Ty(getLLVMContext());
768     break;
769   }
770 
771   case Type::BlockPointer: {
772     const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
773     llvm::Type *PointeeType = CGM.getLangOpts().OpenCL
774                                   ? CGM.getGenericBlockLiteralType()
775                                   : ConvertTypeForMem(FTy);
776     unsigned AS = Context.getTargetAddressSpace(FTy);
777     ResultType = llvm::PointerType::get(PointeeType, AS);
778     break;
779   }
780 
781   case Type::MemberPointer: {
782     auto *MPTy = cast<MemberPointerType>(Ty);
783     if (!getCXXABI().isMemberPointerConvertible(MPTy)) {
784       RecordsWithOpaqueMemberPointers.insert(MPTy->getClass());
785       ResultType = llvm::StructType::create(getLLVMContext());
786     } else {
787       ResultType = getCXXABI().ConvertMemberPointerType(MPTy);
788     }
789     break;
790   }
791 
792   case Type::Atomic: {
793     QualType valueType = cast<AtomicType>(Ty)->getValueType();
794     ResultType = ConvertTypeForMem(valueType);
795 
796     // Pad out to the inflated size if necessary.
797     uint64_t valueSize = Context.getTypeSize(valueType);
798     uint64_t atomicSize = Context.getTypeSize(Ty);
799     if (valueSize != atomicSize) {
800       assert(valueSize < atomicSize);
801       llvm::Type *elts[] = {
802         ResultType,
803         llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
804       };
805       ResultType = llvm::StructType::get(getLLVMContext(),
806                                          llvm::makeArrayRef(elts));
807     }
808     break;
809   }
810   case Type::Pipe: {
811     ResultType = CGM.getOpenCLRuntime().getPipeType(cast<PipeType>(Ty));
812     break;
813   }
814   case Type::ExtInt: {
815     const auto &EIT = cast<ExtIntType>(Ty);
816     ResultType = llvm::Type::getIntNTy(getLLVMContext(), EIT->getNumBits());
817     break;
818   }
819   }
820 
821   assert(ResultType && "Didn't convert a type?");
822 
823 #ifndef NDEBUG
824   if (CachedType) {
825     assert(CachedType == ResultType &&
826            "Cached type doesn't match computed type");
827   }
828 #endif
829 
830   if (ShouldUseCache)
831     TypeCache[Ty] = ResultType;
832   return ResultType;
833 }
834 
isPaddedAtomicType(QualType type)835 bool CodeGenModule::isPaddedAtomicType(QualType type) {
836   return isPaddedAtomicType(type->castAs<AtomicType>());
837 }
838 
isPaddedAtomicType(const AtomicType * type)839 bool CodeGenModule::isPaddedAtomicType(const AtomicType *type) {
840   return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
841 }
842 
843 /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
ConvertRecordDeclType(const RecordDecl * RD)844 llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
845   // TagDecl's are not necessarily unique, instead use the (clang)
846   // type connected to the decl.
847   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
848 
849   llvm::StructType *&Entry = RecordDeclTypes[Key];
850 
851   // If we don't have a StructType at all yet, create the forward declaration.
852   if (!Entry) {
853     Entry = llvm::StructType::create(getLLVMContext());
854     addRecordTypeName(RD, Entry, "");
855   }
856   llvm::StructType *Ty = Entry;
857 
858   // If this is still a forward declaration, or the LLVM type is already
859   // complete, there's nothing more to do.
860   RD = RD->getDefinition();
861   if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
862     return Ty;
863 
864   // If converting this type would cause us to infinitely loop, don't do it!
865   if (!isSafeToConvert(RD, *this)) {
866     DeferredRecords.push_back(RD);
867     return Ty;
868   }
869 
870   // Okay, this is a definition of a type.  Compile the implementation now.
871   bool InsertResult = RecordsBeingLaidOut.insert(Key).second;
872   (void)InsertResult;
873   assert(InsertResult && "Recursively compiling a struct?");
874 
875   // Force conversion of non-virtual base classes recursively.
876   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
877     for (const auto &I : CRD->bases()) {
878       if (I.isVirtual()) continue;
879       ConvertRecordDeclType(I.getType()->castAs<RecordType>()->getDecl());
880     }
881   }
882 
883   // Layout fields.
884   std::unique_ptr<CGRecordLayout> Layout = ComputeRecordLayout(RD, Ty);
885   CGRecordLayouts[Key] = std::move(Layout);
886 
887   // We're done laying out this struct.
888   bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
889   assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
890 
891   // If this struct blocked a FunctionType conversion, then recompute whatever
892   // was derived from that.
893   // FIXME: This is hugely overconservative.
894   if (SkippedLayout)
895     TypeCache.clear();
896 
897   // If we're done converting the outer-most record, then convert any deferred
898   // structs as well.
899   if (RecordsBeingLaidOut.empty())
900     while (!DeferredRecords.empty())
901       ConvertRecordDeclType(DeferredRecords.pop_back_val());
902 
903   return Ty;
904 }
905 
906 /// getCGRecordLayout - Return record layout info for the given record decl.
907 const CGRecordLayout &
getCGRecordLayout(const RecordDecl * RD)908 CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) {
909   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
910 
911   auto I = CGRecordLayouts.find(Key);
912   if (I != CGRecordLayouts.end())
913     return *I->second;
914   // Compute the type information.
915   ConvertRecordDeclType(RD);
916 
917   // Now try again.
918   I = CGRecordLayouts.find(Key);
919 
920   assert(I != CGRecordLayouts.end() &&
921          "Unable to find record layout information for type");
922   return *I->second;
923 }
924 
isPointerZeroInitializable(QualType T)925 bool CodeGenTypes::isPointerZeroInitializable(QualType T) {
926   assert((T->isAnyPointerType() || T->isBlockPointerType()) && "Invalid type");
927   return isZeroInitializable(T);
928 }
929 
isZeroInitializable(QualType T)930 bool CodeGenTypes::isZeroInitializable(QualType T) {
931   if (T->getAs<PointerType>())
932     return Context.getTargetNullPointerValue(T) == 0;
933 
934   if (const auto *AT = Context.getAsArrayType(T)) {
935     if (isa<IncompleteArrayType>(AT))
936       return true;
937     if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
938       if (Context.getConstantArrayElementCount(CAT) == 0)
939         return true;
940     T = Context.getBaseElementType(T);
941   }
942 
943   // Records are non-zero-initializable if they contain any
944   // non-zero-initializable subobjects.
945   if (const RecordType *RT = T->getAs<RecordType>()) {
946     const RecordDecl *RD = RT->getDecl();
947     return isZeroInitializable(RD);
948   }
949 
950   // We have to ask the ABI about member pointers.
951   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
952     return getCXXABI().isZeroInitializable(MPT);
953 
954   // Everything else is okay.
955   return true;
956 }
957 
isZeroInitializable(const RecordDecl * RD)958 bool CodeGenTypes::isZeroInitializable(const RecordDecl *RD) {
959   return getCGRecordLayout(RD).isZeroInitializable();
960 }
961