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