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