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