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 
CodeGenTypes(CodeGenModule & cgm)32 CodeGenTypes::CodeGenTypes(CodeGenModule &cgm)
33   : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
34     TheDataLayout(cgm.getDataLayout()),
35     Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()),
36     TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) {
37   SkippedLayout = false;
38 }
39 
~CodeGenTypes()40 CodeGenTypes::~CodeGenTypes() {
41   llvm::DeleteContainerSeconds(CGRecordLayouts);
42 
43   for (llvm::FoldingSet<CGFunctionInfo>::iterator
44        I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
45     delete &*I++;
46 }
47 
addRecordTypeName(const RecordDecl * RD,llvm::StructType * Ty,StringRef suffix)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.
ConvertTypeForMem(QualType T)84 llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
85   llvm::Type *R = ConvertType(T);
86 
87   // If this is a non-bool type, don't map it.
88   if (!R->isIntegerTy(1))
89     return R;
90 
91   // Otherwise, return an integer of the target-specified size.
92   return llvm::IntegerType::get(getLLVMContext(),
93                                 (unsigned)Context.getTypeSize(T));
94 }
95 
96 
97 /// isRecordLayoutComplete - Return true if the specified type is already
98 /// completely laid out.
isRecordLayoutComplete(const Type * Ty) const99 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
isSafeToConvert(const RecordDecl * RD,CodeGenTypes & CGT,llvm::SmallPtrSet<const RecordDecl *,16> & AlreadyChecked)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()->getAs<RecordType>()->getDecl(),
137                            CGT, 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
isSafeToConvert(QualType T,CodeGenTypes & CGT,llvm::SmallPtrSet<const RecordDecl *,16> & AlreadyChecked)155 isSafeToConvert(QualType T, CodeGenTypes &CGT,
156                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
157   T = T.getCanonicalType();
158 
159   // If this is a record, check it.
160   if (const RecordType *RT = dyn_cast<RecordType>(T))
161     return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked);
162 
163   // If this is an array, check the elements, which are embedded inline.
164   if (const ArrayType *AT = dyn_cast<ArrayType>(T))
165     return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked);
166 
167   // Otherwise, there is no concern about transforming this.  We only care about
168   // things that are contained by-value in a structure that can have another
169   // structure as a member.
170   return true;
171 }
172 
173 
174 /// isSafeToConvert - Return true if it is safe to convert the specified record
175 /// decl to IR and lay it out, false if doing so would cause us to get into a
176 /// recursive compilation mess.
isSafeToConvert(const RecordDecl * RD,CodeGenTypes & CGT)177 static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) {
178   // If no structs are being laid out, we can certainly do this one.
179   if (CGT.noRecordsBeingLaidOut()) return true;
180 
181   llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked;
182   return isSafeToConvert(RD, CGT, AlreadyChecked);
183 }
184 
185 /// isFuncParamTypeConvertible - Return true if the specified type in a
186 /// function parameter or result position can be converted to an IR type at this
187 /// point.  This boils down to being whether it is complete, as well as whether
188 /// we've temporarily deferred expanding the type because we're in a recursive
189 /// context.
isFuncParamTypeConvertible(QualType Ty)190 bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) {
191   // Some ABIs cannot have their member pointers represented in IR unless
192   // certain circumstances have been reached.
193   if (const auto *MPT = Ty->getAs<MemberPointerType>())
194     return getCXXABI().isMemberPointerConvertible(MPT);
195 
196   // If this isn't a tagged type, we can convert it!
197   const TagType *TT = Ty->getAs<TagType>();
198   if (!TT) return true;
199 
200   // Incomplete types cannot be converted.
201   if (TT->isIncompleteType())
202     return false;
203 
204   // If this is an enum, then it is always safe to convert.
205   const RecordType *RT = dyn_cast<RecordType>(TT);
206   if (!RT) return true;
207 
208   // Otherwise, we have to be careful.  If it is a struct that we're in the
209   // process of expanding, then we can't convert the function type.  That's ok
210   // though because we must be in a pointer context under the struct, so we can
211   // just convert it to a dummy type.
212   //
213   // We decide this by checking whether ConvertRecordDeclType returns us an
214   // opaque type for a struct that we know is defined.
215   return isSafeToConvert(RT->getDecl(), *this);
216 }
217 
218 
219 /// Code to verify a given function type is complete, i.e. the return type
220 /// and all of the parameter types are complete.  Also check to see if we are in
221 /// a RS_StructPointer context, and if so whether any struct types have been
222 /// pended.  If so, we don't want to ask the ABI lowering code to handle a type
223 /// that cannot be converted to an IR type.
isFuncTypeConvertible(const FunctionType * FT)224 bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) {
225   if (!isFuncParamTypeConvertible(FT->getReturnType()))
226     return false;
227 
228   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
229     for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
230       if (!isFuncParamTypeConvertible(FPT->getParamType(i)))
231         return false;
232 
233   return true;
234 }
235 
236 /// UpdateCompletedType - When we find the full definition for a TagDecl,
237 /// replace the 'opaque' type we previously made for it if applicable.
UpdateCompletedType(const TagDecl * TD)238 void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
239   // If this is an enum being completed, then we flush all non-struct types from
240   // the cache.  This allows function types and other things that may be derived
241   // from the enum to be recomputed.
242   if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) {
243     // Only flush the cache if we've actually already converted this type.
244     if (TypeCache.count(ED->getTypeForDecl())) {
245       // Okay, we formed some types based on this.  We speculated that the enum
246       // would be lowered to i32, so we only need to flush the cache if this
247       // didn't happen.
248       if (!ConvertType(ED->getIntegerType())->isIntegerTy(32))
249         TypeCache.clear();
250     }
251     // If necessary, provide the full definition of a type only used with a
252     // declaration so far.
253     if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
254       DI->completeType(ED);
255     return;
256   }
257 
258   // If we completed a RecordDecl that we previously used and converted to an
259   // anonymous type, then go ahead and complete it now.
260   const RecordDecl *RD = cast<RecordDecl>(TD);
261   if (RD->isDependentType()) return;
262 
263   // Only complete it if we converted it already.  If we haven't converted it
264   // yet, we'll just do it lazily.
265   if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr()))
266     ConvertRecordDeclType(RD);
267 
268   // If necessary, provide the full definition of a type only used with a
269   // declaration so far.
270   if (CGDebugInfo *DI = CGM.getModuleDebugInfo())
271     DI->completeType(RD);
272 }
273 
getTypeForFormat(llvm::LLVMContext & VMContext,const llvm::fltSemantics & format,bool UseNativeHalf=false)274 static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
275                                     const llvm::fltSemantics &format,
276                                     bool UseNativeHalf = false) {
277   if (&format == &llvm::APFloat::IEEEhalf) {
278     if (UseNativeHalf)
279       return llvm::Type::getHalfTy(VMContext);
280     else
281       return llvm::Type::getInt16Ty(VMContext);
282   }
283   if (&format == &llvm::APFloat::IEEEsingle)
284     return llvm::Type::getFloatTy(VMContext);
285   if (&format == &llvm::APFloat::IEEEdouble)
286     return llvm::Type::getDoubleTy(VMContext);
287   if (&format == &llvm::APFloat::IEEEquad)
288     return llvm::Type::getFP128Ty(VMContext);
289   if (&format == &llvm::APFloat::PPCDoubleDouble)
290     return llvm::Type::getPPC_FP128Ty(VMContext);
291   if (&format == &llvm::APFloat::x87DoubleExtended)
292     return llvm::Type::getX86_FP80Ty(VMContext);
293   llvm_unreachable("Unknown float format!");
294 }
295 
296 /// ConvertType - Convert the specified type to its LLVM form.
ConvertType(QualType T)297 llvm::Type *CodeGenTypes::ConvertType(QualType T) {
298   T = Context.getCanonicalType(T);
299 
300   const Type *Ty = T.getTypePtr();
301 
302   // RecordTypes are cached and processed specially.
303   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
304     return ConvertRecordDeclType(RT->getDecl());
305 
306   // See if type is already cached.
307   llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty);
308   // If type is found in map then use it. Otherwise, convert type T.
309   if (TCI != TypeCache.end())
310     return TCI->second;
311 
312   // If we don't have it in the cache, convert it now.
313   llvm::Type *ResultType = nullptr;
314   switch (Ty->getTypeClass()) {
315   case Type::Record: // Handled above.
316 #define TYPE(Class, Base)
317 #define ABSTRACT_TYPE(Class, Base)
318 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
319 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
320 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
321 #include "clang/AST/TypeNodes.def"
322     llvm_unreachable("Non-canonical or dependent types aren't possible.");
323 
324   case Type::Builtin: {
325     switch (cast<BuiltinType>(Ty)->getKind()) {
326     case BuiltinType::Void:
327     case BuiltinType::ObjCId:
328     case BuiltinType::ObjCClass:
329     case BuiltinType::ObjCSel:
330       // LLVM void type can only be used as the result of a function call.  Just
331       // map to the same as char.
332       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
333       break;
334 
335     case BuiltinType::Bool:
336       // Note that we always return bool as i1 for use as a scalar type.
337       ResultType = llvm::Type::getInt1Ty(getLLVMContext());
338       break;
339 
340     case BuiltinType::Char_S:
341     case BuiltinType::Char_U:
342     case BuiltinType::SChar:
343     case BuiltinType::UChar:
344     case BuiltinType::Short:
345     case BuiltinType::UShort:
346     case BuiltinType::Int:
347     case BuiltinType::UInt:
348     case BuiltinType::Long:
349     case BuiltinType::ULong:
350     case BuiltinType::LongLong:
351     case BuiltinType::ULongLong:
352     case BuiltinType::WChar_S:
353     case BuiltinType::WChar_U:
354     case BuiltinType::Char16:
355     case BuiltinType::Char32:
356       ResultType = llvm::IntegerType::get(getLLVMContext(),
357                                  static_cast<unsigned>(Context.getTypeSize(T)));
358       break;
359 
360     case BuiltinType::Half:
361       // Half FP can either be storage-only (lowered to i16) or native.
362       ResultType =
363           getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T),
364                            Context.getLangOpts().NativeHalfType ||
365                                Context.getLangOpts().HalfArgsAndReturns);
366       break;
367     case BuiltinType::Float:
368     case BuiltinType::Double:
369     case BuiltinType::LongDouble:
370       ResultType = getTypeForFormat(getLLVMContext(),
371                                     Context.getFloatTypeSemantics(T),
372                                     /* UseNativeHalf = */ false);
373       break;
374 
375     case BuiltinType::NullPtr:
376       // Model std::nullptr_t as i8*
377       ResultType = llvm::Type::getInt8PtrTy(getLLVMContext());
378       break;
379 
380     case BuiltinType::UInt128:
381     case BuiltinType::Int128:
382       ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
383       break;
384 
385     case BuiltinType::OCLImage1d:
386     case BuiltinType::OCLImage1dArray:
387     case BuiltinType::OCLImage1dBuffer:
388     case BuiltinType::OCLImage2d:
389     case BuiltinType::OCLImage2dArray:
390     case BuiltinType::OCLImage3d:
391     case BuiltinType::OCLSampler:
392     case BuiltinType::OCLEvent:
393       ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty);
394       break;
395 
396     case BuiltinType::Dependent:
397 #define BUILTIN_TYPE(Id, SingletonId)
398 #define PLACEHOLDER_TYPE(Id, SingletonId) \
399     case BuiltinType::Id:
400 #include "clang/AST/BuiltinTypes.def"
401       llvm_unreachable("Unexpected placeholder builtin type!");
402     }
403     break;
404   }
405   case Type::Auto:
406     llvm_unreachable("Unexpected undeduced auto type!");
407   case Type::Complex: {
408     llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
409     ResultType = llvm::StructType::get(EltTy, EltTy, nullptr);
410     break;
411   }
412   case Type::LValueReference:
413   case Type::RValueReference: {
414     const ReferenceType *RTy = cast<ReferenceType>(Ty);
415     QualType ETy = RTy->getPointeeType();
416     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
417     unsigned AS = Context.getTargetAddressSpace(ETy);
418     ResultType = llvm::PointerType::get(PointeeType, AS);
419     break;
420   }
421   case Type::Pointer: {
422     const PointerType *PTy = cast<PointerType>(Ty);
423     QualType ETy = PTy->getPointeeType();
424     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
425     if (PointeeType->isVoidTy())
426       PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
427     unsigned AS = Context.getTargetAddressSpace(ETy);
428     ResultType = llvm::PointerType::get(PointeeType, AS);
429     break;
430   }
431 
432   case Type::VariableArray: {
433     const VariableArrayType *A = cast<VariableArrayType>(Ty);
434     assert(A->getIndexTypeCVRQualifiers() == 0 &&
435            "FIXME: We only handle trivial array types so far!");
436     // VLAs resolve to the innermost element type; this matches
437     // the return of alloca, and there isn't any obviously better choice.
438     ResultType = ConvertTypeForMem(A->getElementType());
439     break;
440   }
441   case Type::IncompleteArray: {
442     const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
443     assert(A->getIndexTypeCVRQualifiers() == 0 &&
444            "FIXME: We only handle trivial array types so far!");
445     // int X[] -> [0 x int], unless the element type is not sized.  If it is
446     // unsized (e.g. an incomplete struct) just use [0 x i8].
447     ResultType = ConvertTypeForMem(A->getElementType());
448     if (!ResultType->isSized()) {
449       SkippedLayout = true;
450       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
451     }
452     ResultType = llvm::ArrayType::get(ResultType, 0);
453     break;
454   }
455   case Type::ConstantArray: {
456     const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
457     llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
458 
459     // Lower arrays of undefined struct type to arrays of i8 just to have a
460     // concrete type.
461     if (!EltTy->isSized()) {
462       SkippedLayout = true;
463       EltTy = llvm::Type::getInt8Ty(getLLVMContext());
464     }
465 
466     ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
467     break;
468   }
469   case Type::ExtVector:
470   case Type::Vector: {
471     const VectorType *VT = cast<VectorType>(Ty);
472     ResultType = llvm::VectorType::get(ConvertType(VT->getElementType()),
473                                        VT->getNumElements());
474     break;
475   }
476   case Type::FunctionNoProto:
477   case Type::FunctionProto: {
478     const FunctionType *FT = cast<FunctionType>(Ty);
479     // First, check whether we can build the full function type.  If the
480     // function type depends on an incomplete type (e.g. a struct or enum), we
481     // cannot lower the function type.
482     if (!isFuncTypeConvertible(FT)) {
483       // This function's type depends on an incomplete tag type.
484 
485       // Force conversion of all the relevant record types, to make sure
486       // we re-convert the FunctionType when appropriate.
487       if (const RecordType *RT = FT->getReturnType()->getAs<RecordType>())
488         ConvertRecordDeclType(RT->getDecl());
489       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
490         for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++)
491           if (const RecordType *RT = FPT->getParamType(i)->getAs<RecordType>())
492             ConvertRecordDeclType(RT->getDecl());
493 
494       // Return a placeholder type.
495       ResultType = llvm::StructType::get(getLLVMContext());
496 
497       SkippedLayout = true;
498       break;
499     }
500 
501     // While we're converting the parameter types for a function, we don't want
502     // to recursively convert any pointed-to structs.  Converting directly-used
503     // structs is ok though.
504     if (!RecordsBeingLaidOut.insert(Ty).second) {
505       ResultType = llvm::StructType::get(getLLVMContext());
506 
507       SkippedLayout = true;
508       break;
509     }
510 
511     // The function type can be built; call the appropriate routines to
512     // build it.
513     const CGFunctionInfo *FI;
514     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
515       FI = &arrangeFreeFunctionType(
516                    CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT, 0)));
517     } else {
518       const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
519       FI = &arrangeFreeFunctionType(
520                 CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT, 0)));
521     }
522 
523     // If there is something higher level prodding our CGFunctionInfo, then
524     // don't recurse into it again.
525     if (FunctionsBeingProcessed.count(FI)) {
526 
527       ResultType = llvm::StructType::get(getLLVMContext());
528       SkippedLayout = true;
529     } else {
530 
531       // Otherwise, we're good to go, go ahead and convert it.
532       ResultType = GetFunctionType(*FI);
533     }
534 
535     RecordsBeingLaidOut.erase(Ty);
536 
537     if (SkippedLayout)
538       TypeCache.clear();
539 
540     if (RecordsBeingLaidOut.empty())
541       while (!DeferredRecords.empty())
542         ConvertRecordDeclType(DeferredRecords.pop_back_val());
543     break;
544   }
545 
546   case Type::ObjCObject:
547     ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
548     break;
549 
550   case Type::ObjCInterface: {
551     // Objective-C interfaces are always opaque (outside of the
552     // runtime, which can do whatever it likes); we never refine
553     // these.
554     llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
555     if (!T)
556       T = llvm::StructType::create(getLLVMContext());
557     ResultType = T;
558     break;
559   }
560 
561   case Type::ObjCObjectPointer: {
562     // Protocol qualifications do not influence the LLVM type, we just return a
563     // pointer to the underlying interface type. We don't need to worry about
564     // recursive conversion.
565     llvm::Type *T =
566       ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
567     ResultType = T->getPointerTo();
568     break;
569   }
570 
571   case Type::Enum: {
572     const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
573     if (ED->isCompleteDefinition() || ED->isFixed())
574       return ConvertType(ED->getIntegerType());
575     // Return a placeholder 'i32' type.  This can be changed later when the
576     // type is defined (see UpdateCompletedType), but is likely to be the
577     // "right" answer.
578     ResultType = llvm::Type::getInt32Ty(getLLVMContext());
579     break;
580   }
581 
582   case Type::BlockPointer: {
583     const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
584     llvm::Type *PointeeType = ConvertTypeForMem(FTy);
585     unsigned AS = Context.getTargetAddressSpace(FTy);
586     ResultType = llvm::PointerType::get(PointeeType, AS);
587     break;
588   }
589 
590   case Type::MemberPointer: {
591     if (!getCXXABI().isMemberPointerConvertible(cast<MemberPointerType>(Ty)))
592       return llvm::StructType::create(getLLVMContext());
593     ResultType =
594       getCXXABI().ConvertMemberPointerType(cast<MemberPointerType>(Ty));
595     break;
596   }
597 
598   case Type::Atomic: {
599     QualType valueType = cast<AtomicType>(Ty)->getValueType();
600     ResultType = ConvertTypeForMem(valueType);
601 
602     // Pad out to the inflated size if necessary.
603     uint64_t valueSize = Context.getTypeSize(valueType);
604     uint64_t atomicSize = Context.getTypeSize(Ty);
605     if (valueSize != atomicSize) {
606       assert(valueSize < atomicSize);
607       llvm::Type *elts[] = {
608         ResultType,
609         llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8)
610       };
611       ResultType = llvm::StructType::get(getLLVMContext(),
612                                          llvm::makeArrayRef(elts));
613     }
614     break;
615   }
616   }
617 
618   assert(ResultType && "Didn't convert a type?");
619 
620   TypeCache[Ty] = ResultType;
621   return ResultType;
622 }
623 
isPaddedAtomicType(QualType type)624 bool CodeGenModule::isPaddedAtomicType(QualType type) {
625   return isPaddedAtomicType(type->castAs<AtomicType>());
626 }
627 
isPaddedAtomicType(const AtomicType * type)628 bool CodeGenModule::isPaddedAtomicType(const AtomicType *type) {
629   return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType());
630 }
631 
632 /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
ConvertRecordDeclType(const RecordDecl * RD)633 llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
634   // TagDecl's are not necessarily unique, instead use the (clang)
635   // type connected to the decl.
636   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
637 
638   llvm::StructType *&Entry = RecordDeclTypes[Key];
639 
640   // If we don't have a StructType at all yet, create the forward declaration.
641   if (!Entry) {
642     Entry = llvm::StructType::create(getLLVMContext());
643     addRecordTypeName(RD, Entry, "");
644   }
645   llvm::StructType *Ty = Entry;
646 
647   // If this is still a forward declaration, or the LLVM type is already
648   // complete, there's nothing more to do.
649   RD = RD->getDefinition();
650   if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque())
651     return Ty;
652 
653   // If converting this type would cause us to infinitely loop, don't do it!
654   if (!isSafeToConvert(RD, *this)) {
655     DeferredRecords.push_back(RD);
656     return Ty;
657   }
658 
659   // Okay, this is a definition of a type.  Compile the implementation now.
660   bool InsertResult = RecordsBeingLaidOut.insert(Key).second;
661   (void)InsertResult;
662   assert(InsertResult && "Recursively compiling a struct?");
663 
664   // Force conversion of non-virtual base classes recursively.
665   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
666     for (const auto &I : CRD->bases()) {
667       if (I.isVirtual()) continue;
668 
669       ConvertRecordDeclType(I.getType()->getAs<RecordType>()->getDecl());
670     }
671   }
672 
673   // Layout fields.
674   CGRecordLayout *Layout = ComputeRecordLayout(RD, Ty);
675   CGRecordLayouts[Key] = Layout;
676 
677   // We're done laying out this struct.
678   bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
679   assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
680 
681   // If this struct blocked a FunctionType conversion, then recompute whatever
682   // was derived from that.
683   // FIXME: This is hugely overconservative.
684   if (SkippedLayout)
685     TypeCache.clear();
686 
687   // If we're done converting the outer-most record, then convert any deferred
688   // structs as well.
689   if (RecordsBeingLaidOut.empty())
690     while (!DeferredRecords.empty())
691       ConvertRecordDeclType(DeferredRecords.pop_back_val());
692 
693   return Ty;
694 }
695 
696 /// getCGRecordLayout - Return record layout info for the given record decl.
697 const CGRecordLayout &
getCGRecordLayout(const RecordDecl * RD)698 CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) {
699   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
700 
701   const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
702   if (!Layout) {
703     // Compute the type information.
704     ConvertRecordDeclType(RD);
705 
706     // Now try again.
707     Layout = CGRecordLayouts.lookup(Key);
708   }
709 
710   assert(Layout && "Unable to find record layout information for type");
711   return *Layout;
712 }
713 
isZeroInitializable(QualType T)714 bool CodeGenTypes::isZeroInitializable(QualType T) {
715   // No need to check for member pointers when not compiling C++.
716   if (!Context.getLangOpts().CPlusPlus)
717     return true;
718 
719   T = Context.getBaseElementType(T);
720 
721   // Records are non-zero-initializable if they contain any
722   // non-zero-initializable subobjects.
723   if (const RecordType *RT = T->getAs<RecordType>()) {
724     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
725     return isZeroInitializable(RD);
726   }
727 
728   // We have to ask the ABI about member pointers.
729   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
730     return getCXXABI().isZeroInitializable(MPT);
731 
732   // Everything else is okay.
733   return true;
734 }
735 
isZeroInitializable(const CXXRecordDecl * RD)736 bool CodeGenTypes::isZeroInitializable(const CXXRecordDecl *RD) {
737   return getCGRecordLayout(RD).isZeroInitializable();
738 }
739