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 "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/RecordLayout.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Target/TargetData.h"
23 
24 #include "CGCall.h"
25 #include "CGRecordLayoutBuilder.h"
26 
27 using namespace clang;
28 using namespace CodeGen;
29 
30 CodeGenTypes::CodeGenTypes(ASTContext &Ctx, llvm::Module& M,
31                            const llvm::TargetData &TD)
32   : Context(Ctx), Target(Ctx.Target), TheModule(M), TheTargetData(TD),
33     TheABIInfo(0) {
34 }
35 
36 CodeGenTypes::~CodeGenTypes() {
37   for (llvm::DenseMap<const Type *, CGRecordLayout *>::iterator
38          I = CGRecordLayouts.begin(), E = CGRecordLayouts.end();
39       I != E; ++I)
40     delete I->second;
41   {
42     llvm::FoldingSet<CGFunctionInfo>::iterator
43          I = FunctionInfos.begin(), E = FunctionInfos.end();
44     while (I != E)
45       delete &*I++;
46   }
47   delete TheABIInfo;
48 }
49 
50 /// ConvertType - Convert the specified type to its LLVM form.
51 const llvm::Type *CodeGenTypes::ConvertType(QualType T) {
52   llvm::PATypeHolder Result = ConvertTypeRecursive(T);
53 
54   // Any pointers that were converted defered evaluation of their pointee type,
55   // creating an opaque type instead.  This is in order to avoid problems with
56   // circular types.  Loop through all these defered pointees, if any, and
57   // resolve them now.
58   while (!PointersToResolve.empty()) {
59     std::pair<QualType, llvm::OpaqueType*> P =
60       PointersToResolve.back();
61     PointersToResolve.pop_back();
62     // We can handle bare pointers here because we know that the only pointers
63     // to the Opaque type are P.second and from other types.  Refining the
64     // opqaue type away will invalidate P.second, but we don't mind :).
65     const llvm::Type *NT = ConvertTypeForMemRecursive(P.first);
66     P.second->refineAbstractTypeTo(NT);
67   }
68 
69   return Result;
70 }
71 
72 const llvm::Type *CodeGenTypes::ConvertTypeRecursive(QualType T) {
73   T = Context.getCanonicalType(T);
74 
75   // See if type is already cached.
76   llvm::DenseMap<Type *, llvm::PATypeHolder>::iterator
77     I = TypeCache.find(T.getTypePtr());
78   // If type is found in map and this is not a definition for a opaque
79   // place holder type then use it. Otherwise, convert type T.
80   if (I != TypeCache.end())
81     return I->second.get();
82 
83   const llvm::Type *ResultType = ConvertNewType(T);
84   TypeCache.insert(std::make_pair(T.getTypePtr(),
85                                   llvm::PATypeHolder(ResultType)));
86   return ResultType;
87 }
88 
89 const llvm::Type *CodeGenTypes::ConvertTypeForMemRecursive(QualType T) {
90   const llvm::Type *ResultType = ConvertTypeRecursive(T);
91   if (ResultType == llvm::Type::getInt1Ty(getLLVMContext()))
92     return llvm::IntegerType::get(getLLVMContext(),
93                                   (unsigned)Context.getTypeSize(T));
94   return ResultType;
95 }
96 
97 /// ConvertTypeForMem - Convert type T into a llvm::Type.  This differs from
98 /// ConvertType in that it is used to convert to the memory representation for
99 /// a type.  For example, the scalar representation for _Bool is i1, but the
100 /// memory representation is usually i8 or i32, depending on the target.
101 const llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T) {
102   const llvm::Type *R = ConvertType(T);
103 
104   // If this is a non-bool type, don't map it.
105   if (R != llvm::Type::getInt1Ty(getLLVMContext()))
106     return R;
107 
108   // Otherwise, return an integer of the target-specified size.
109   return llvm::IntegerType::get(getLLVMContext(),
110                                 (unsigned)Context.getTypeSize(T));
111 
112 }
113 
114 // Code to verify a given function type is complete, i.e. the return type
115 // and all of the argument types are complete.
116 static const TagType *VerifyFuncTypeComplete(const Type* T) {
117   const FunctionType *FT = cast<FunctionType>(T);
118   if (const TagType* TT = FT->getResultType()->getAs<TagType>())
119     if (!TT->getDecl()->isDefinition())
120       return TT;
121   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(T))
122     for (unsigned i = 0; i < FPT->getNumArgs(); i++)
123       if (const TagType* TT = FPT->getArgType(i)->getAs<TagType>())
124         if (!TT->getDecl()->isDefinition())
125           return TT;
126   return 0;
127 }
128 
129 /// UpdateCompletedType - When we find the full definition for a TagDecl,
130 /// replace the 'opaque' type we previously made for it if applicable.
131 void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) {
132   const Type *Key = Context.getTagDeclType(TD).getTypePtr();
133   llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI =
134     TagDeclTypes.find(Key);
135   if (TDTI == TagDeclTypes.end()) return;
136 
137   // Remember the opaque LLVM type for this tagdecl.
138   llvm::PATypeHolder OpaqueHolder = TDTI->second;
139   assert(isa<llvm::OpaqueType>(OpaqueHolder.get()) &&
140          "Updating compilation of an already non-opaque type?");
141 
142   // Remove it from TagDeclTypes so that it will be regenerated.
143   TagDeclTypes.erase(TDTI);
144 
145   // Generate the new type.
146   const llvm::Type *NT = ConvertTagDeclType(TD);
147 
148   // Refine the old opaque type to its new definition.
149   cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NT);
150 
151   // Since we just completed a tag type, check to see if any function types
152   // were completed along with the tag type.
153   // FIXME: This is very inefficient; if we track which function types depend
154   // on which tag types, though, it should be reasonably efficient.
155   llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator i;
156   for (i = FunctionTypes.begin(); i != FunctionTypes.end(); ++i) {
157     if (const TagType* TT = VerifyFuncTypeComplete(i->first)) {
158       // This function type still depends on an incomplete tag type; make sure
159       // that tag type has an associated opaque type.
160       ConvertTagDeclType(TT->getDecl());
161     } else {
162       // This function no longer depends on an incomplete tag type; create the
163       // function type, and refine the opaque type to the new function type.
164       llvm::PATypeHolder OpaqueHolder = i->second;
165       const llvm::Type *NFT = ConvertNewType(QualType(i->first, 0));
166       cast<llvm::OpaqueType>(OpaqueHolder.get())->refineAbstractTypeTo(NFT);
167       FunctionTypes.erase(i);
168     }
169   }
170 }
171 
172 static const llvm::Type* getTypeForFormat(llvm::LLVMContext &VMContext,
173                                           const llvm::fltSemantics &format) {
174   if (&format == &llvm::APFloat::IEEEsingle)
175     return llvm::Type::getFloatTy(VMContext);
176   if (&format == &llvm::APFloat::IEEEdouble)
177     return llvm::Type::getDoubleTy(VMContext);
178   if (&format == &llvm::APFloat::IEEEquad)
179     return llvm::Type::getFP128Ty(VMContext);
180   if (&format == &llvm::APFloat::PPCDoubleDouble)
181     return llvm::Type::getPPC_FP128Ty(VMContext);
182   if (&format == &llvm::APFloat::x87DoubleExtended)
183     return llvm::Type::getX86_FP80Ty(VMContext);
184   assert(0 && "Unknown float format!");
185   return 0;
186 }
187 
188 const llvm::Type *CodeGenTypes::ConvertNewType(QualType T) {
189   const clang::Type &Ty = *Context.getCanonicalType(T).getTypePtr();
190 
191   switch (Ty.getTypeClass()) {
192 #define TYPE(Class, Base)
193 #define ABSTRACT_TYPE(Class, Base)
194 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
195 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
196 #include "clang/AST/TypeNodes.def"
197     assert(false && "Non-canonical or dependent types aren't possible.");
198     break;
199 
200   case Type::Builtin: {
201     switch (cast<BuiltinType>(Ty).getKind()) {
202     case BuiltinType::Void:
203     case BuiltinType::ObjCId:
204     case BuiltinType::ObjCClass:
205     case BuiltinType::ObjCSel:
206       // LLVM void type can only be used as the result of a function call.  Just
207       // map to the same as char.
208       return llvm::IntegerType::get(getLLVMContext(), 8);
209 
210     case BuiltinType::Bool:
211       // Note that we always return bool as i1 for use as a scalar type.
212       return llvm::Type::getInt1Ty(getLLVMContext());
213 
214     case BuiltinType::Char_S:
215     case BuiltinType::Char_U:
216     case BuiltinType::SChar:
217     case BuiltinType::UChar:
218     case BuiltinType::Short:
219     case BuiltinType::UShort:
220     case BuiltinType::Int:
221     case BuiltinType::UInt:
222     case BuiltinType::Long:
223     case BuiltinType::ULong:
224     case BuiltinType::LongLong:
225     case BuiltinType::ULongLong:
226     case BuiltinType::WChar:
227     case BuiltinType::Char16:
228     case BuiltinType::Char32:
229       return llvm::IntegerType::get(getLLVMContext(),
230         static_cast<unsigned>(Context.getTypeSize(T)));
231 
232     case BuiltinType::Float:
233     case BuiltinType::Double:
234     case BuiltinType::LongDouble:
235       return getTypeForFormat(getLLVMContext(),
236                               Context.getFloatTypeSemantics(T));
237 
238     case BuiltinType::NullPtr: {
239       // Model std::nullptr_t as i8*
240       const llvm::Type *Ty = llvm::IntegerType::get(getLLVMContext(), 8);
241       return llvm::PointerType::getUnqual(Ty);
242     }
243 
244     case BuiltinType::UInt128:
245     case BuiltinType::Int128:
246       return llvm::IntegerType::get(getLLVMContext(), 128);
247 
248     case BuiltinType::Overload:
249     case BuiltinType::Dependent:
250     case BuiltinType::UndeducedAuto:
251       assert(0 && "Unexpected builtin type!");
252       break;
253     }
254     assert(0 && "Unknown builtin type!");
255     break;
256   }
257   case Type::FixedWidthInt:
258     return llvm::IntegerType::get(getLLVMContext(),
259                                   cast<FixedWidthIntType>(T)->getWidth());
260   case Type::Complex: {
261     const llvm::Type *EltTy =
262       ConvertTypeRecursive(cast<ComplexType>(Ty).getElementType());
263     return llvm::StructType::get(TheModule.getContext(), EltTy, EltTy, NULL);
264   }
265   case Type::LValueReference:
266   case Type::RValueReference: {
267     const ReferenceType &RTy = cast<ReferenceType>(Ty);
268     QualType ETy = RTy.getPointeeType();
269     llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
270     PointersToResolve.push_back(std::make_pair(ETy, PointeeType));
271     return llvm::PointerType::get(PointeeType, ETy.getAddressSpace());
272   }
273   case Type::Pointer: {
274     const PointerType &PTy = cast<PointerType>(Ty);
275     QualType ETy = PTy.getPointeeType();
276     llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
277     PointersToResolve.push_back(std::make_pair(ETy, PointeeType));
278     return llvm::PointerType::get(PointeeType, ETy.getAddressSpace());
279   }
280 
281   case Type::VariableArray: {
282     const VariableArrayType &A = cast<VariableArrayType>(Ty);
283     assert(A.getIndexTypeCVRQualifiers() == 0 &&
284            "FIXME: We only handle trivial array types so far!");
285     // VLAs resolve to the innermost element type; this matches
286     // the return of alloca, and there isn't any obviously better choice.
287     return ConvertTypeForMemRecursive(A.getElementType());
288   }
289   case Type::IncompleteArray: {
290     const IncompleteArrayType &A = cast<IncompleteArrayType>(Ty);
291     assert(A.getIndexTypeCVRQualifiers() == 0 &&
292            "FIXME: We only handle trivial array types so far!");
293     // int X[] -> [0 x int]
294     return llvm::ArrayType::get(ConvertTypeForMemRecursive(A.getElementType()), 0);
295   }
296   case Type::ConstantArray: {
297     const ConstantArrayType &A = cast<ConstantArrayType>(Ty);
298     const llvm::Type *EltTy = ConvertTypeForMemRecursive(A.getElementType());
299     return llvm::ArrayType::get(EltTy, A.getSize().getZExtValue());
300   }
301   case Type::ExtVector:
302   case Type::Vector: {
303     const VectorType &VT = cast<VectorType>(Ty);
304     return llvm::VectorType::get(ConvertTypeRecursive(VT.getElementType()),
305                                  VT.getNumElements());
306   }
307   case Type::FunctionNoProto:
308   case Type::FunctionProto: {
309     // First, check whether we can build the full function type.
310     if (const TagType* TT = VerifyFuncTypeComplete(&Ty)) {
311       // This function's type depends on an incomplete tag type; make sure
312       // we have an opaque type corresponding to the tag type.
313       ConvertTagDeclType(TT->getDecl());
314       // Create an opaque type for this function type, save it, and return it.
315       llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext());
316       FunctionTypes.insert(std::make_pair(&Ty, ResultType));
317       return ResultType;
318     }
319     // The function type can be built; call the appropriate routines to
320     // build it.
321     if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(&Ty))
322       return GetFunctionType(getFunctionInfo(FPT), FPT->isVariadic());
323 
324     const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(&Ty);
325     return GetFunctionType(getFunctionInfo(FNPT), true);
326   }
327 
328   case Type::ObjCInterface: {
329     // Objective-C interfaces are always opaque (outside of the
330     // runtime, which can do whatever it likes); we never refine
331     // these.
332     const llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(&Ty)];
333     if (!T)
334         T = llvm::OpaqueType::get(getLLVMContext());
335     return T;
336   }
337 
338   case Type::ObjCObjectPointer: {
339     // Protocol qualifications do not influence the LLVM type, we just return a
340     // pointer to the underlying interface type. We don't need to worry about
341     // recursive conversion.
342     const llvm::Type *T =
343       ConvertTypeRecursive(cast<ObjCObjectPointerType>(Ty).getPointeeType());
344     return llvm::PointerType::getUnqual(T);
345   }
346 
347   case Type::Record:
348   case Type::Enum: {
349     const TagDecl *TD = cast<TagType>(Ty).getDecl();
350     const llvm::Type *Res = ConvertTagDeclType(TD);
351 
352     std::string TypeName(TD->getKindName());
353     TypeName += '.';
354 
355     // Name the codegen type after the typedef name
356     // if there is no tag type name available
357     if (TD->getIdentifier())
358       // FIXME: We should not have to check for a null decl context here.
359       // Right now we do it because the implicit Obj-C decls don't have one.
360       TypeName += TD->getDeclContext() ? TD->getQualifiedNameAsString() :
361         TD->getNameAsString();
362     else if (const TypedefType *TdT = dyn_cast<TypedefType>(T))
363       // FIXME: We should not have to check for a null decl context here.
364       // Right now we do it because the implicit Obj-C decls don't have one.
365       TypeName += TdT->getDecl()->getDeclContext() ?
366         TdT->getDecl()->getQualifiedNameAsString() :
367         TdT->getDecl()->getNameAsString();
368     else
369       TypeName += "anon";
370 
371     TheModule.addTypeName(TypeName, Res);
372     return Res;
373   }
374 
375   case Type::BlockPointer: {
376     const QualType FTy = cast<BlockPointerType>(Ty).getPointeeType();
377     llvm::OpaqueType *PointeeType = llvm::OpaqueType::get(getLLVMContext());
378     PointersToResolve.push_back(std::make_pair(FTy, PointeeType));
379     return llvm::PointerType::get(PointeeType, FTy.getAddressSpace());
380   }
381 
382   case Type::MemberPointer: {
383     // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
384     // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
385     // If we ever want to support other ABIs this needs to be abstracted.
386 
387     QualType ETy = cast<MemberPointerType>(Ty).getPointeeType();
388     const llvm::Type *PtrDiffTy =
389         ConvertTypeRecursive(Context.getPointerDiffType());
390     if (ETy->isFunctionType()) {
391       return llvm::StructType::get(TheModule.getContext(), PtrDiffTy, PtrDiffTy,
392                                    NULL);
393     } else
394       return PtrDiffTy;
395   }
396 
397   case Type::TemplateSpecialization:
398     assert(false && "Dependent types can't get here");
399   }
400 
401   // FIXME: implement.
402   return llvm::OpaqueType::get(getLLVMContext());
403 }
404 
405 /// ConvertTagDeclType - Lay out a tagged decl type like struct or union or
406 /// enum.
407 const llvm::Type *CodeGenTypes::ConvertTagDeclType(const TagDecl *TD) {
408 
409   // FIXME. This may have to move to a better place.
410   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
411     for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
412          e = RD->bases_end(); i != e; ++i) {
413       if (!i->isVirtual()) {
414         const CXXRecordDecl *Base =
415           cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
416         ConvertTagDeclType(Base);
417       }
418     }
419   }
420 
421   // TagDecl's are not necessarily unique, instead use the (clang)
422   // type connected to the decl.
423   const Type *Key =
424     Context.getTagDeclType(TD).getTypePtr();
425   llvm::DenseMap<const Type*, llvm::PATypeHolder>::iterator TDTI =
426     TagDeclTypes.find(Key);
427 
428   // If we've already compiled this tag type, use the previous definition.
429   if (TDTI != TagDeclTypes.end())
430     return TDTI->second;
431 
432   // If this is still a forward definition, just define an opaque type to use
433   // for this tagged decl.
434   if (!TD->isDefinition()) {
435     llvm::Type *ResultType = llvm::OpaqueType::get(getLLVMContext());
436     TagDeclTypes.insert(std::make_pair(Key, ResultType));
437     return ResultType;
438   }
439 
440   // Okay, this is a definition of a type.  Compile the implementation now.
441 
442   if (TD->isEnum()) {
443     // Don't bother storing enums in TagDeclTypes.
444     return ConvertTypeRecursive(cast<EnumDecl>(TD)->getIntegerType());
445   }
446 
447   // This decl could well be recursive.  In this case, insert an opaque
448   // definition of this type, which the recursive uses will get.  We will then
449   // refine this opaque version later.
450 
451   // Create new OpaqueType now for later use in case this is a recursive
452   // type.  This will later be refined to the actual type.
453   llvm::PATypeHolder ResultHolder = llvm::OpaqueType::get(getLLVMContext());
454   TagDeclTypes.insert(std::make_pair(Key, ResultHolder));
455 
456   const llvm::Type *ResultType;
457   const RecordDecl *RD = cast<const RecordDecl>(TD);
458 
459   // Layout fields.
460   CGRecordLayout *Layout =
461     CGRecordLayoutBuilder::ComputeLayout(*this, RD);
462 
463   CGRecordLayouts[Key] = Layout;
464   ResultType = Layout->getLLVMType();
465 
466   // Refine our Opaque type to ResultType.  This can invalidate ResultType, so
467   // make sure to read the result out of the holder.
468   cast<llvm::OpaqueType>(ResultHolder.get())
469     ->refineAbstractTypeTo(ResultType);
470 
471   return ResultHolder.get();
472 }
473 
474 /// getLLVMFieldNo - Return llvm::StructType element number
475 /// that corresponds to the field FD.
476 unsigned CodeGenTypes::getLLVMFieldNo(const FieldDecl *FD) {
477   assert(!FD->isBitField() && "Don't use getLLVMFieldNo on bit fields!");
478 
479   llvm::DenseMap<const FieldDecl*, unsigned>::iterator I = FieldInfo.find(FD);
480   assert (I != FieldInfo.end()  && "Unable to find field info");
481   return I->second;
482 }
483 
484 /// addFieldInfo - Assign field number to field FD.
485 void CodeGenTypes::addFieldInfo(const FieldDecl *FD, unsigned No) {
486   FieldInfo[FD] = No;
487 }
488 
489 /// getBitFieldInfo - Return the BitFieldInfo  that corresponds to the field FD.
490 CodeGenTypes::BitFieldInfo CodeGenTypes::getBitFieldInfo(const FieldDecl *FD) {
491   llvm::DenseMap<const FieldDecl *, BitFieldInfo>::iterator
492     I = BitFields.find(FD);
493   assert (I != BitFields.end()  && "Unable to find bitfield info");
494   return I->second;
495 }
496 
497 /// addBitFieldInfo - Assign a start bit and a size to field FD.
498 void CodeGenTypes::addBitFieldInfo(const FieldDecl *FD, unsigned FieldNo,
499                                    unsigned Start, unsigned Size) {
500   BitFields.insert(std::make_pair(FD, BitFieldInfo(FieldNo, Start, Size)));
501 }
502 
503 /// getCGRecordLayout - Return record layout info for the given llvm::Type.
504 const CGRecordLayout &
505 CodeGenTypes::getCGRecordLayout(const TagDecl *TD) const {
506   const Type *Key =
507     Context.getTagDeclType(TD).getTypePtr();
508   llvm::DenseMap<const Type*, CGRecordLayout *>::const_iterator I
509     = CGRecordLayouts.find(Key);
510   assert (I != CGRecordLayouts.end()
511           && "Unable to find record layout information for type");
512   return *I->second;
513 }
514