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