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