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