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