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 "CGCall.h"
16 #include "CGCXXABI.h"
17 #include "CGRecordLayout.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Target/TargetData.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 CodeGenTypes::CodeGenTypes(CodeGenModule &CGM)
31   : Context(CGM.getContext()), Target(Context.getTargetInfo()),
32     TheModule(CGM.getModule()), TheTargetData(CGM.getTargetData()),
33     TheABIInfo(CGM.getTargetCodeGenInfo().getABIInfo()),
34     TheCXXABI(CGM.getCXXABI()),
35     CodeGenOpts(CGM.getCodeGenOpts()), CGM(CGM) {
36   SkippedLayout = false;
37 }
38 
39 CodeGenTypes::~CodeGenTypes() {
40   for (llvm::DenseMap<const Type *, CGRecordLayout *>::iterator
41          I = CGRecordLayouts.begin(), E = CGRecordLayouts.end();
42       I != E; ++I)
43     delete I->second;
44 
45   for (llvm::FoldingSet<CGFunctionInfo>::iterator
46        I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; )
47     delete &*I++;
48 }
49 
50 void CodeGenTypes::addRecordTypeName(const RecordDecl *RD,
51                                      llvm::StructType *Ty,
52                                      StringRef suffix) {
53   SmallString<256> TypeName;
54   llvm::raw_svector_ostream OS(TypeName);
55   OS << RD->getKindName() << '.';
56 
57   // Name the codegen type after the typedef name
58   // if there is no tag type name available
59   if (RD->getIdentifier()) {
60     // FIXME: We should not have to check for a null decl context here.
61     // Right now we do it because the implicit Obj-C decls don't have one.
62     if (RD->getDeclContext())
63       OS << RD->getQualifiedNameAsString();
64     else
65       RD->printName(OS);
66   } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) {
67     // FIXME: We should not have to check for a null decl context here.
68     // Right now we do it because the implicit Obj-C decls don't have one.
69     if (TDD->getDeclContext())
70       OS << TDD->getQualifiedNameAsString();
71     else
72       TDD->printName(OS);
73   } else
74     OS << "anon";
75 
76   if (!suffix.empty())
77     OS << suffix;
78 
79   Ty->setName(OS.str());
80 }
81 
82 /// ConvertTypeForMem - Convert type T into a llvm::Type.  This differs from
83 /// ConvertType in that it is used to convert to the memory representation for
84 /// a type.  For example, the scalar representation for _Bool is i1, but the
85 /// memory representation is usually i8 or i32, depending on the target.
86 llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T){
87   llvm::Type *R = ConvertType(T);
88 
89   // If this is a non-bool type, don't map it.
90   if (!R->isIntegerTy(1))
91     return R;
92 
93   // Otherwise, return an integer of the target-specified size.
94   return llvm::IntegerType::get(getLLVMContext(),
95                                 (unsigned)Context.getTypeSize(T));
96 }
97 
98 
99 /// isRecordLayoutComplete - Return true if the specified type is already
100 /// completely laid out.
101 bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const {
102   llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I =
103   RecordDeclTypes.find(Ty);
104   return I != RecordDeclTypes.end() && !I->second->isOpaque();
105 }
106 
107 static bool
108 isSafeToConvert(QualType T, CodeGenTypes &CGT,
109                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked);
110 
111 
112 /// isSafeToConvert - Return true if it is safe to convert the specified record
113 /// decl to IR and lay it out, false if doing so would cause us to get into a
114 /// recursive compilation mess.
115 static bool
116 isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT,
117                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
118   // If we have already checked this type (maybe the same type is used by-value
119   // multiple times in multiple structure fields, don't check again.
120   if (!AlreadyChecked.insert(RD)) return true;
121 
122   const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr();
123 
124   // If this type is already laid out, converting it is a noop.
125   if (CGT.isRecordLayoutComplete(Key)) return true;
126 
127   // If this type is currently being laid out, we can't recursively compile it.
128   if (CGT.isRecordBeingLaidOut(Key))
129     return false;
130 
131   // If this type would require laying out bases that are currently being laid
132   // out, don't do it.  This includes virtual base classes which get laid out
133   // when a class is translated, even though they aren't embedded by-value into
134   // the class.
135   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
136     for (CXXRecordDecl::base_class_const_iterator I = CRD->bases_begin(),
137          E = CRD->bases_end(); I != E; ++I)
138       if (!isSafeToConvert(I->getType()->getAs<RecordType>()->getDecl(),
139                            CGT, AlreadyChecked))
140         return false;
141   }
142 
143   // If this type would require laying out members that are currently being laid
144   // out, don't do it.
145   for (RecordDecl::field_iterator I = RD->field_begin(),
146        E = RD->field_end(); I != E; ++I)
147     if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked))
148       return false;
149 
150   // If there are no problems, lets do it.
151   return true;
152 }
153 
154 /// isSafeToConvert - Return true if it is safe to convert this field type,
155 /// which requires the structure elements contained by-value to all be
156 /// recursively safe to convert.
157 static bool
158 isSafeToConvert(QualType T, CodeGenTypes &CGT,
159                 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) {
160   T = T.getCanonicalType();
161 
162   // If this is a record, check it.
163   if (const RecordType *RT = dyn_cast<RecordType>(T))
164     return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked);
165 
166   // If this is an array, check the elements, which are embedded inline.
167   if (const ArrayType *AT = dyn_cast<ArrayType>(T))
168     return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked);
169 
170   // Otherwise, there is no concern about transforming this.  We only care about
171   // things that are contained by-value in a structure that can have another
172   // structure as a member.
173   return true;
174 }
175 
176 
177 /// isSafeToConvert - Return true if it is safe to convert the specified record
178 /// decl to IR and lay it out, false if doing so would cause us to get into a
179 /// recursive compilation mess.
180 static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) {
181   // If no structs are being laid out, we can certainly do this one.
182   if (CGT.noRecordsBeingLaidOut()) return true;
183 
184   llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked;
185   return isSafeToConvert(RD, CGT, AlreadyChecked);
186 }
187 
188 
189 /// isFuncTypeArgumentConvertible - Return true if the specified type in a
190 /// function argument or result position can be converted to an IR type at this
191 /// point.  This boils down to being whether it is complete, as well as whether
192 /// we've temporarily deferred expanding the type because we're in a recursive
193 /// context.
194 bool CodeGenTypes::isFuncTypeArgumentConvertible(QualType Ty) {
195   // If this isn't a tagged type, we can convert it!
196   const TagType *TT = Ty->getAs<TagType>();
197   if (TT == 0) return true;
198 
199 
200   // If it's a tagged type used by-value, but is just a forward decl, we can't
201   // convert it.  Note that getDefinition()==0 is not the same as !isDefinition.
202   if (TT->getDecl()->getDefinition() == 0)
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 == 0) 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 argument 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 (!isFuncTypeArgumentConvertible(FT->getResultType()))
227     return false;
228 
229   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT))
230     for (unsigned i = 0, e = FPT->getNumArgs(); i != e; i++)
231       if (!isFuncTypeArgumentConvertible(FPT->getArgType(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     return;
253   }
254 
255   // If we completed a RecordDecl that we previously used and converted to an
256   // anonymous type, then go ahead and complete it now.
257   const RecordDecl *RD = cast<RecordDecl>(TD);
258   if (RD->isDependentType()) return;
259 
260   // Only complete it if we converted it already.  If we haven't converted it
261   // yet, we'll just do it lazily.
262   if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr()))
263     ConvertRecordDeclType(RD);
264 }
265 
266 static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext,
267                                     const llvm::fltSemantics &format) {
268   if (&format == &llvm::APFloat::IEEEhalf)
269     return llvm::Type::getInt16Ty(VMContext);
270   if (&format == &llvm::APFloat::IEEEsingle)
271     return llvm::Type::getFloatTy(VMContext);
272   if (&format == &llvm::APFloat::IEEEdouble)
273     return llvm::Type::getDoubleTy(VMContext);
274   if (&format == &llvm::APFloat::IEEEquad)
275     return llvm::Type::getFP128Ty(VMContext);
276   if (&format == &llvm::APFloat::PPCDoubleDouble)
277     return llvm::Type::getPPC_FP128Ty(VMContext);
278   if (&format == &llvm::APFloat::x87DoubleExtended)
279     return llvm::Type::getX86_FP80Ty(VMContext);
280   llvm_unreachable("Unknown float format!");
281 }
282 
283 /// ConvertType - Convert the specified type to its LLVM form.
284 llvm::Type *CodeGenTypes::ConvertType(QualType T) {
285   T = Context.getCanonicalType(T);
286 
287   const Type *Ty = T.getTypePtr();
288 
289   // RecordTypes are cached and processed specially.
290   if (const RecordType *RT = dyn_cast<RecordType>(Ty))
291     return ConvertRecordDeclType(RT->getDecl());
292 
293   // See if type is already cached.
294   llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty);
295   // If type is found in map then use it. Otherwise, convert type T.
296   if (TCI != TypeCache.end())
297     return TCI->second;
298 
299   // If we don't have it in the cache, convert it now.
300   llvm::Type *ResultType = 0;
301   switch (Ty->getTypeClass()) {
302   case Type::Record: // Handled above.
303 #define TYPE(Class, Base)
304 #define ABSTRACT_TYPE(Class, Base)
305 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
306 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
307 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
308 #include "clang/AST/TypeNodes.def"
309     llvm_unreachable("Non-canonical or dependent types aren't possible.");
310 
311   case Type::Builtin: {
312     switch (cast<BuiltinType>(Ty)->getKind()) {
313     case BuiltinType::Void:
314     case BuiltinType::ObjCId:
315     case BuiltinType::ObjCClass:
316     case BuiltinType::ObjCSel:
317       // LLVM void type can only be used as the result of a function call.  Just
318       // map to the same as char.
319       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
320       break;
321 
322     case BuiltinType::Bool:
323       // Note that we always return bool as i1 for use as a scalar type.
324       ResultType = llvm::Type::getInt1Ty(getLLVMContext());
325       break;
326 
327     case BuiltinType::Char_S:
328     case BuiltinType::Char_U:
329     case BuiltinType::SChar:
330     case BuiltinType::UChar:
331     case BuiltinType::Short:
332     case BuiltinType::UShort:
333     case BuiltinType::Int:
334     case BuiltinType::UInt:
335     case BuiltinType::Long:
336     case BuiltinType::ULong:
337     case BuiltinType::LongLong:
338     case BuiltinType::ULongLong:
339     case BuiltinType::WChar_S:
340     case BuiltinType::WChar_U:
341     case BuiltinType::Char16:
342     case BuiltinType::Char32:
343       ResultType = llvm::IntegerType::get(getLLVMContext(),
344                                  static_cast<unsigned>(Context.getTypeSize(T)));
345       break;
346 
347     case BuiltinType::Half:
348       // Half is special: it might be lowered to i16 (and will be storage-only
349       // type),. or can be represented as a set of native operations.
350 
351       // FIXME: Ask target which kind of half FP it prefers (storage only vs
352       // native).
353       ResultType = llvm::Type::getInt16Ty(getLLVMContext());
354       break;
355     case BuiltinType::Float:
356     case BuiltinType::Double:
357     case BuiltinType::LongDouble:
358       ResultType = getTypeForFormat(getLLVMContext(),
359                                     Context.getFloatTypeSemantics(T));
360       break;
361 
362     case BuiltinType::NullPtr:
363       // Model std::nullptr_t as i8*
364       ResultType = llvm::Type::getInt8PtrTy(getLLVMContext());
365       break;
366 
367     case BuiltinType::UInt128:
368     case BuiltinType::Int128:
369       ResultType = llvm::IntegerType::get(getLLVMContext(), 128);
370       break;
371 
372     case BuiltinType::Dependent:
373 #define BUILTIN_TYPE(Id, SingletonId)
374 #define PLACEHOLDER_TYPE(Id, SingletonId) \
375     case BuiltinType::Id:
376 #include "clang/AST/BuiltinTypes.def"
377       llvm_unreachable("Unexpected placeholder builtin type!");
378     }
379     break;
380   }
381   case Type::Complex: {
382     llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
383     ResultType = llvm::StructType::get(EltTy, EltTy, NULL);
384     break;
385   }
386   case Type::LValueReference:
387   case Type::RValueReference: {
388     const ReferenceType *RTy = cast<ReferenceType>(Ty);
389     QualType ETy = RTy->getPointeeType();
390     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
391     unsigned AS = Context.getTargetAddressSpace(ETy);
392     ResultType = llvm::PointerType::get(PointeeType, AS);
393     break;
394   }
395   case Type::Pointer: {
396     const PointerType *PTy = cast<PointerType>(Ty);
397     QualType ETy = PTy->getPointeeType();
398     llvm::Type *PointeeType = ConvertTypeForMem(ETy);
399     if (PointeeType->isVoidTy())
400       PointeeType = llvm::Type::getInt8Ty(getLLVMContext());
401     unsigned AS = Context.getTargetAddressSpace(ETy);
402     ResultType = llvm::PointerType::get(PointeeType, AS);
403     break;
404   }
405 
406   case Type::VariableArray: {
407     const VariableArrayType *A = cast<VariableArrayType>(Ty);
408     assert(A->getIndexTypeCVRQualifiers() == 0 &&
409            "FIXME: We only handle trivial array types so far!");
410     // VLAs resolve to the innermost element type; this matches
411     // the return of alloca, and there isn't any obviously better choice.
412     ResultType = ConvertTypeForMem(A->getElementType());
413     break;
414   }
415   case Type::IncompleteArray: {
416     const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty);
417     assert(A->getIndexTypeCVRQualifiers() == 0 &&
418            "FIXME: We only handle trivial array types so far!");
419     // int X[] -> [0 x int], unless the element type is not sized.  If it is
420     // unsized (e.g. an incomplete struct) just use [0 x i8].
421     ResultType = ConvertTypeForMem(A->getElementType());
422     if (!ResultType->isSized()) {
423       SkippedLayout = true;
424       ResultType = llvm::Type::getInt8Ty(getLLVMContext());
425     }
426     ResultType = llvm::ArrayType::get(ResultType, 0);
427     break;
428   }
429   case Type::ConstantArray: {
430     const ConstantArrayType *A = cast<ConstantArrayType>(Ty);
431     llvm::Type *EltTy = ConvertTypeForMem(A->getElementType());
432 
433     // Lower arrays of undefined struct type to arrays of i8 just to have a
434     // concrete type.
435     if (!EltTy->isSized()) {
436       SkippedLayout = true;
437       EltTy = llvm::Type::getInt8Ty(getLLVMContext());
438     }
439 
440     ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue());
441     break;
442   }
443   case Type::ExtVector:
444   case Type::Vector: {
445     const VectorType *VT = cast<VectorType>(Ty);
446     ResultType = llvm::VectorType::get(ConvertType(VT->getElementType()),
447                                        VT->getNumElements());
448     break;
449   }
450   case Type::FunctionNoProto:
451   case Type::FunctionProto: {
452     const FunctionType *FT = cast<FunctionType>(Ty);
453     // First, check whether we can build the full function type.  If the
454     // function type depends on an incomplete type (e.g. a struct or enum), we
455     // cannot lower the function type.
456     if (!isFuncTypeConvertible(FT)) {
457       // This function's type depends on an incomplete tag type.
458       // Return a placeholder type.
459       ResultType = llvm::StructType::get(getLLVMContext());
460 
461       SkippedLayout = true;
462       break;
463     }
464 
465     // While we're converting the argument types for a function, we don't want
466     // to recursively convert any pointed-to structs.  Converting directly-used
467     // structs is ok though.
468     if (!RecordsBeingLaidOut.insert(Ty)) {
469       ResultType = llvm::StructType::get(getLLVMContext());
470 
471       SkippedLayout = true;
472       break;
473     }
474 
475     // The function type can be built; call the appropriate routines to
476     // build it.
477     const CGFunctionInfo *FI;
478     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
479       FI = &arrangeFunctionType(
480                    CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT, 0)));
481     } else {
482       const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT);
483       FI = &arrangeFunctionType(
484                 CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT, 0)));
485     }
486 
487     // If there is something higher level prodding our CGFunctionInfo, then
488     // don't recurse into it again.
489     if (FunctionsBeingProcessed.count(FI)) {
490 
491       ResultType = llvm::StructType::get(getLLVMContext());
492       SkippedLayout = true;
493     } else {
494 
495       // Otherwise, we're good to go, go ahead and convert it.
496       ResultType = GetFunctionType(*FI);
497     }
498 
499     RecordsBeingLaidOut.erase(Ty);
500 
501     if (SkippedLayout)
502       TypeCache.clear();
503 
504     if (RecordsBeingLaidOut.empty())
505       while (!DeferredRecords.empty())
506         ConvertRecordDeclType(DeferredRecords.pop_back_val());
507     break;
508   }
509 
510   case Type::ObjCObject:
511     ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType());
512     break;
513 
514   case Type::ObjCInterface: {
515     // Objective-C interfaces are always opaque (outside of the
516     // runtime, which can do whatever it likes); we never refine
517     // these.
518     llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)];
519     if (!T)
520       T = llvm::StructType::create(getLLVMContext());
521     ResultType = T;
522     break;
523   }
524 
525   case Type::ObjCObjectPointer: {
526     // Protocol qualifications do not influence the LLVM type, we just return a
527     // pointer to the underlying interface type. We don't need to worry about
528     // recursive conversion.
529     llvm::Type *T =
530       ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
531     ResultType = T->getPointerTo();
532     break;
533   }
534 
535   case Type::Enum: {
536     const EnumDecl *ED = cast<EnumType>(Ty)->getDecl();
537     if (ED->isCompleteDefinition() || ED->isFixed())
538       return ConvertType(ED->getIntegerType());
539     // Return a placeholder 'i32' type.  This can be changed later when the
540     // type is defined (see UpdateCompletedType), but is likely to be the
541     // "right" answer.
542     ResultType = llvm::Type::getInt32Ty(getLLVMContext());
543     break;
544   }
545 
546   case Type::BlockPointer: {
547     const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType();
548     llvm::Type *PointeeType = ConvertTypeForMem(FTy);
549     unsigned AS = Context.getTargetAddressSpace(FTy);
550     ResultType = llvm::PointerType::get(PointeeType, AS);
551     break;
552   }
553 
554   case Type::MemberPointer: {
555     ResultType =
556       getCXXABI().ConvertMemberPointerType(cast<MemberPointerType>(Ty));
557     break;
558   }
559 
560   case Type::Atomic: {
561     ResultType = ConvertTypeForMem(cast<AtomicType>(Ty)->getValueType());
562     break;
563   }
564   }
565 
566   assert(ResultType && "Didn't convert a type?");
567 
568   TypeCache[Ty] = ResultType;
569   return ResultType;
570 }
571 
572 /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union.
573 llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) {
574   // TagDecl's are not necessarily unique, instead use the (clang)
575   // type connected to the decl.
576   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
577 
578   llvm::StructType *&Entry = RecordDeclTypes[Key];
579 
580   // If we don't have a StructType at all yet, create the forward declaration.
581   if (Entry == 0) {
582     Entry = llvm::StructType::create(getLLVMContext());
583     addRecordTypeName(RD, Entry, "");
584   }
585   llvm::StructType *Ty = Entry;
586 
587   // If this is still a forward declaration, or the LLVM type is already
588   // complete, there's nothing more to do.
589   RD = RD->getDefinition();
590   if (RD == 0 || !RD->isCompleteDefinition() || !Ty->isOpaque())
591     return Ty;
592 
593   // If converting this type would cause us to infinitely loop, don't do it!
594   if (!isSafeToConvert(RD, *this)) {
595     DeferredRecords.push_back(RD);
596     return Ty;
597   }
598 
599   // Okay, this is a definition of a type.  Compile the implementation now.
600   bool InsertResult = RecordsBeingLaidOut.insert(Key); (void)InsertResult;
601   assert(InsertResult && "Recursively compiling a struct?");
602 
603   // Force conversion of non-virtual base classes recursively.
604   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
605     for (CXXRecordDecl::base_class_const_iterator i = CRD->bases_begin(),
606          e = CRD->bases_end(); i != e; ++i) {
607       if (i->isVirtual()) continue;
608 
609       ConvertRecordDeclType(i->getType()->getAs<RecordType>()->getDecl());
610     }
611   }
612 
613   // Layout fields.
614   CGRecordLayout *Layout = ComputeRecordLayout(RD, Ty);
615   CGRecordLayouts[Key] = Layout;
616 
617   // We're done laying out this struct.
618   bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult;
619   assert(EraseResult && "struct not in RecordsBeingLaidOut set?");
620 
621   // If this struct blocked a FunctionType conversion, then recompute whatever
622   // was derived from that.
623   // FIXME: This is hugely overconservative.
624   if (SkippedLayout)
625     TypeCache.clear();
626 
627   // If we're done converting the outer-most record, then convert any deferred
628   // structs as well.
629   if (RecordsBeingLaidOut.empty())
630     while (!DeferredRecords.empty())
631       ConvertRecordDeclType(DeferredRecords.pop_back_val());
632 
633   return Ty;
634 }
635 
636 /// getCGRecordLayout - Return record layout info for the given record decl.
637 const CGRecordLayout &
638 CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) {
639   const Type *Key = Context.getTagDeclType(RD).getTypePtr();
640 
641   const CGRecordLayout *Layout = CGRecordLayouts.lookup(Key);
642   if (!Layout) {
643     // Compute the type information.
644     ConvertRecordDeclType(RD);
645 
646     // Now try again.
647     Layout = CGRecordLayouts.lookup(Key);
648   }
649 
650   assert(Layout && "Unable to find record layout information for type");
651   return *Layout;
652 }
653 
654 bool CodeGenTypes::isZeroInitializable(QualType T) {
655   // No need to check for member pointers when not compiling C++.
656   if (!Context.getLangOptions().CPlusPlus)
657     return true;
658 
659   T = Context.getBaseElementType(T);
660 
661   // Records are non-zero-initializable if they contain any
662   // non-zero-initializable subobjects.
663   if (const RecordType *RT = T->getAs<RecordType>()) {
664     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
665     return isZeroInitializable(RD);
666   }
667 
668   // We have to ask the ABI about member pointers.
669   if (const MemberPointerType *MPT = T->getAs<MemberPointerType>())
670     return getCXXABI().isZeroInitializable(MPT);
671 
672   // Everything else is okay.
673   return true;
674 }
675 
676 bool CodeGenTypes::isZeroInitializable(const CXXRecordDecl *RD) {
677   return getCGRecordLayout(RD).isZeroInitializable();
678 }
679