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