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