1 //===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This is the code that handles AST -> LLVM type lowering. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenTypes.h" 14 #include "CGCXXABI.h" 15 #include "CGCall.h" 16 #include "CGOpenCLRuntime.h" 17 #include "CGRecordLayout.h" 18 #include "TargetInfo.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/CodeGen/CGFunctionInfo.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/Module.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 CodeGenTypes::CodeGenTypes(CodeGenModule &cgm) 32 : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()), 33 Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()), 34 TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) { 35 SkippedLayout = false; 36 } 37 38 CodeGenTypes::~CodeGenTypes() { 39 for (llvm::FoldingSet<CGFunctionInfo>::iterator 40 I = FunctionInfos.begin(), E = FunctionInfos.end(); I != E; ) 41 delete &*I++; 42 } 43 44 const CodeGenOptions &CodeGenTypes::getCodeGenOpts() const { 45 return CGM.getCodeGenOpts(); 46 } 47 48 void CodeGenTypes::addRecordTypeName(const RecordDecl *RD, 49 llvm::StructType *Ty, 50 StringRef suffix) { 51 SmallString<256> TypeName; 52 llvm::raw_svector_ostream OS(TypeName); 53 OS << RD->getKindName() << '.'; 54 55 // Name the codegen type after the typedef name 56 // if there is no tag type name available 57 if (RD->getIdentifier()) { 58 // FIXME: We should not have to check for a null decl context here. 59 // Right now we do it because the implicit Obj-C decls don't have one. 60 if (RD->getDeclContext()) 61 RD->printQualifiedName(OS); 62 else 63 RD->printName(OS); 64 } else if (const TypedefNameDecl *TDD = RD->getTypedefNameForAnonDecl()) { 65 // FIXME: We should not have to check for a null decl context here. 66 // Right now we do it because the implicit Obj-C decls don't have one. 67 if (TDD->getDeclContext()) 68 TDD->printQualifiedName(OS); 69 else 70 TDD->printName(OS); 71 } else 72 OS << "anon"; 73 74 if (!suffix.empty()) 75 OS << suffix; 76 77 Ty->setName(OS.str()); 78 } 79 80 /// ConvertTypeForMem - Convert type T into a llvm::Type. This differs from 81 /// ConvertType in that it is used to convert to the memory representation for 82 /// a type. For example, the scalar representation for _Bool is i1, but the 83 /// memory representation is usually i8 or i32, depending on the target. 84 llvm::Type *CodeGenTypes::ConvertTypeForMem(QualType T, bool ForBitField) { 85 if (T->isConstantMatrixType()) { 86 const Type *Ty = Context.getCanonicalType(T).getTypePtr(); 87 const ConstantMatrixType *MT = cast<ConstantMatrixType>(Ty); 88 return llvm::ArrayType::get(ConvertType(MT->getElementType()), 89 MT->getNumRows() * MT->getNumColumns()); 90 } 91 92 llvm::Type *R = ConvertType(T); 93 94 // If this is a bool type, or an ExtIntType in a bitfield representation, 95 // map this integer to the target-specified size. 96 if ((ForBitField && T->isExtIntType()) || R->isIntegerTy(1)) 97 return llvm::IntegerType::get(getLLVMContext(), 98 (unsigned)Context.getTypeSize(T)); 99 100 // Else, don't map it. 101 return R; 102 } 103 104 /// isRecordLayoutComplete - Return true if the specified type is already 105 /// completely laid out. 106 bool CodeGenTypes::isRecordLayoutComplete(const Type *Ty) const { 107 llvm::DenseMap<const Type*, llvm::StructType *>::const_iterator I = 108 RecordDeclTypes.find(Ty); 109 return I != RecordDeclTypes.end() && !I->second->isOpaque(); 110 } 111 112 static bool 113 isSafeToConvert(QualType T, CodeGenTypes &CGT, 114 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked); 115 116 117 /// isSafeToConvert - Return true if it is safe to convert the specified record 118 /// decl to IR and lay it out, false if doing so would cause us to get into a 119 /// recursive compilation mess. 120 static bool 121 isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT, 122 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) { 123 // If we have already checked this type (maybe the same type is used by-value 124 // multiple times in multiple structure fields, don't check again. 125 if (!AlreadyChecked.insert(RD).second) 126 return true; 127 128 const Type *Key = CGT.getContext().getTagDeclType(RD).getTypePtr(); 129 130 // If this type is already laid out, converting it is a noop. 131 if (CGT.isRecordLayoutComplete(Key)) return true; 132 133 // If this type is currently being laid out, we can't recursively compile it. 134 if (CGT.isRecordBeingLaidOut(Key)) 135 return false; 136 137 // If this type would require laying out bases that are currently being laid 138 // out, don't do it. This includes virtual base classes which get laid out 139 // when a class is translated, even though they aren't embedded by-value into 140 // the class. 141 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 142 for (const auto &I : CRD->bases()) 143 if (!isSafeToConvert(I.getType()->castAs<RecordType>()->getDecl(), CGT, 144 AlreadyChecked)) 145 return false; 146 } 147 148 // If this type would require laying out members that are currently being laid 149 // out, don't do it. 150 for (const auto *I : RD->fields()) 151 if (!isSafeToConvert(I->getType(), CGT, AlreadyChecked)) 152 return false; 153 154 // If there are no problems, lets do it. 155 return true; 156 } 157 158 /// isSafeToConvert - Return true if it is safe to convert this field type, 159 /// which requires the structure elements contained by-value to all be 160 /// recursively safe to convert. 161 static bool 162 isSafeToConvert(QualType T, CodeGenTypes &CGT, 163 llvm::SmallPtrSet<const RecordDecl*, 16> &AlreadyChecked) { 164 // Strip off atomic type sugar. 165 if (const auto *AT = T->getAs<AtomicType>()) 166 T = AT->getValueType(); 167 168 // If this is a record, check it. 169 if (const auto *RT = T->getAs<RecordType>()) 170 return isSafeToConvert(RT->getDecl(), CGT, AlreadyChecked); 171 172 // If this is an array, check the elements, which are embedded inline. 173 if (const auto *AT = CGT.getContext().getAsArrayType(T)) 174 return isSafeToConvert(AT->getElementType(), CGT, AlreadyChecked); 175 176 // Otherwise, there is no concern about transforming this. We only care about 177 // things that are contained by-value in a structure that can have another 178 // structure as a member. 179 return true; 180 } 181 182 183 /// isSafeToConvert - Return true if it is safe to convert the specified record 184 /// decl to IR and lay it out, false if doing so would cause us to get into a 185 /// recursive compilation mess. 186 static bool isSafeToConvert(const RecordDecl *RD, CodeGenTypes &CGT) { 187 // If no structs are being laid out, we can certainly do this one. 188 if (CGT.noRecordsBeingLaidOut()) return true; 189 190 llvm::SmallPtrSet<const RecordDecl*, 16> AlreadyChecked; 191 return isSafeToConvert(RD, CGT, AlreadyChecked); 192 } 193 194 /// isFuncParamTypeConvertible - Return true if the specified type in a 195 /// function parameter or result position can be converted to an IR type at this 196 /// point. This boils down to being whether it is complete, as well as whether 197 /// we've temporarily deferred expanding the type because we're in a recursive 198 /// context. 199 bool CodeGenTypes::isFuncParamTypeConvertible(QualType Ty) { 200 // Some ABIs cannot have their member pointers represented in IR unless 201 // certain circumstances have been reached. 202 if (const auto *MPT = Ty->getAs<MemberPointerType>()) 203 return getCXXABI().isMemberPointerConvertible(MPT); 204 205 // If this isn't a tagged type, we can convert it! 206 const TagType *TT = Ty->getAs<TagType>(); 207 if (!TT) return true; 208 209 // Incomplete types cannot be converted. 210 if (TT->isIncompleteType()) 211 return false; 212 213 // If this is an enum, then it is always safe to convert. 214 const RecordType *RT = dyn_cast<RecordType>(TT); 215 if (!RT) return true; 216 217 // Otherwise, we have to be careful. If it is a struct that we're in the 218 // process of expanding, then we can't convert the function type. That's ok 219 // though because we must be in a pointer context under the struct, so we can 220 // just convert it to a dummy type. 221 // 222 // We decide this by checking whether ConvertRecordDeclType returns us an 223 // opaque type for a struct that we know is defined. 224 return isSafeToConvert(RT->getDecl(), *this); 225 } 226 227 228 /// Code to verify a given function type is complete, i.e. the return type 229 /// and all of the parameter types are complete. Also check to see if we are in 230 /// a RS_StructPointer context, and if so whether any struct types have been 231 /// pended. If so, we don't want to ask the ABI lowering code to handle a type 232 /// that cannot be converted to an IR type. 233 bool CodeGenTypes::isFuncTypeConvertible(const FunctionType *FT) { 234 if (!isFuncParamTypeConvertible(FT->getReturnType())) 235 return false; 236 237 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) 238 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++) 239 if (!isFuncParamTypeConvertible(FPT->getParamType(i))) 240 return false; 241 242 return true; 243 } 244 245 /// UpdateCompletedType - When we find the full definition for a TagDecl, 246 /// replace the 'opaque' type we previously made for it if applicable. 247 void CodeGenTypes::UpdateCompletedType(const TagDecl *TD) { 248 // If this is an enum being completed, then we flush all non-struct types from 249 // the cache. This allows function types and other things that may be derived 250 // from the enum to be recomputed. 251 if (const EnumDecl *ED = dyn_cast<EnumDecl>(TD)) { 252 // Only flush the cache if we've actually already converted this type. 253 if (TypeCache.count(ED->getTypeForDecl())) { 254 // Okay, we formed some types based on this. We speculated that the enum 255 // would be lowered to i32, so we only need to flush the cache if this 256 // didn't happen. 257 if (!ConvertType(ED->getIntegerType())->isIntegerTy(32)) 258 TypeCache.clear(); 259 } 260 // If necessary, provide the full definition of a type only used with a 261 // declaration so far. 262 if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) 263 DI->completeType(ED); 264 return; 265 } 266 267 // If we completed a RecordDecl that we previously used and converted to an 268 // anonymous type, then go ahead and complete it now. 269 const RecordDecl *RD = cast<RecordDecl>(TD); 270 if (RD->isDependentType()) return; 271 272 // Only complete it if we converted it already. If we haven't converted it 273 // yet, we'll just do it lazily. 274 if (RecordDeclTypes.count(Context.getTagDeclType(RD).getTypePtr())) 275 ConvertRecordDeclType(RD); 276 277 // If necessary, provide the full definition of a type only used with a 278 // declaration so far. 279 if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) 280 DI->completeType(RD); 281 } 282 283 void CodeGenTypes::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 284 QualType T = Context.getRecordType(RD); 285 T = Context.getCanonicalType(T); 286 287 const Type *Ty = T.getTypePtr(); 288 if (RecordsWithOpaqueMemberPointers.count(Ty)) { 289 TypeCache.clear(); 290 RecordsWithOpaqueMemberPointers.clear(); 291 } 292 } 293 294 static llvm::Type *getTypeForFormat(llvm::LLVMContext &VMContext, 295 const llvm::fltSemantics &format, 296 bool UseNativeHalf = false) { 297 if (&format == &llvm::APFloat::IEEEhalf()) { 298 if (UseNativeHalf) 299 return llvm::Type::getHalfTy(VMContext); 300 else 301 return llvm::Type::getInt16Ty(VMContext); 302 } 303 if (&format == &llvm::APFloat::IEEEsingle()) 304 return llvm::Type::getFloatTy(VMContext); 305 if (&format == &llvm::APFloat::IEEEdouble()) 306 return llvm::Type::getDoubleTy(VMContext); 307 if (&format == &llvm::APFloat::IEEEquad()) 308 return llvm::Type::getFP128Ty(VMContext); 309 if (&format == &llvm::APFloat::PPCDoubleDouble()) 310 return llvm::Type::getPPC_FP128Ty(VMContext); 311 if (&format == &llvm::APFloat::x87DoubleExtended()) 312 return llvm::Type::getX86_FP80Ty(VMContext); 313 llvm_unreachable("Unknown float format!"); 314 } 315 316 llvm::Type *CodeGenTypes::ConvertFunctionTypeInternal(QualType QFT) { 317 assert(QFT.isCanonical()); 318 const Type *Ty = QFT.getTypePtr(); 319 const FunctionType *FT = cast<FunctionType>(QFT.getTypePtr()); 320 // First, check whether we can build the full function type. If the 321 // function type depends on an incomplete type (e.g. a struct or enum), we 322 // cannot lower the function type. 323 if (!isFuncTypeConvertible(FT)) { 324 // This function's type depends on an incomplete tag type. 325 326 // Force conversion of all the relevant record types, to make sure 327 // we re-convert the FunctionType when appropriate. 328 if (const RecordType *RT = FT->getReturnType()->getAs<RecordType>()) 329 ConvertRecordDeclType(RT->getDecl()); 330 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) 331 for (unsigned i = 0, e = FPT->getNumParams(); i != e; i++) 332 if (const RecordType *RT = FPT->getParamType(i)->getAs<RecordType>()) 333 ConvertRecordDeclType(RT->getDecl()); 334 335 SkippedLayout = true; 336 337 // Return a placeholder type. 338 return llvm::StructType::get(getLLVMContext()); 339 } 340 341 // While we're converting the parameter types for a function, we don't want 342 // to recursively convert any pointed-to structs. Converting directly-used 343 // structs is ok though. 344 if (!RecordsBeingLaidOut.insert(Ty).second) { 345 SkippedLayout = true; 346 return llvm::StructType::get(getLLVMContext()); 347 } 348 349 // The function type can be built; call the appropriate routines to 350 // build it. 351 const CGFunctionInfo *FI; 352 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 353 FI = &arrangeFreeFunctionType( 354 CanQual<FunctionProtoType>::CreateUnsafe(QualType(FPT, 0))); 355 } else { 356 const FunctionNoProtoType *FNPT = cast<FunctionNoProtoType>(FT); 357 FI = &arrangeFreeFunctionType( 358 CanQual<FunctionNoProtoType>::CreateUnsafe(QualType(FNPT, 0))); 359 } 360 361 llvm::Type *ResultType = nullptr; 362 // If there is something higher level prodding our CGFunctionInfo, then 363 // don't recurse into it again. 364 if (FunctionsBeingProcessed.count(FI)) { 365 366 ResultType = llvm::StructType::get(getLLVMContext()); 367 SkippedLayout = true; 368 } else { 369 370 // Otherwise, we're good to go, go ahead and convert it. 371 ResultType = GetFunctionType(*FI); 372 } 373 374 RecordsBeingLaidOut.erase(Ty); 375 376 if (SkippedLayout) 377 TypeCache.clear(); 378 379 if (RecordsBeingLaidOut.empty()) 380 while (!DeferredRecords.empty()) 381 ConvertRecordDeclType(DeferredRecords.pop_back_val()); 382 return ResultType; 383 } 384 385 /// ConvertType - Convert the specified type to its LLVM form. 386 llvm::Type *CodeGenTypes::ConvertType(QualType T) { 387 T = Context.getCanonicalType(T); 388 389 const Type *Ty = T.getTypePtr(); 390 391 // For the device-side compilation, CUDA device builtin surface/texture types 392 // may be represented in different types. 393 if (Context.getLangOpts().CUDAIsDevice) { 394 if (T->isCUDADeviceBuiltinSurfaceType()) { 395 if (auto *Ty = CGM.getTargetCodeGenInfo() 396 .getCUDADeviceBuiltinSurfaceDeviceType()) 397 return Ty; 398 } else if (T->isCUDADeviceBuiltinTextureType()) { 399 if (auto *Ty = CGM.getTargetCodeGenInfo() 400 .getCUDADeviceBuiltinTextureDeviceType()) 401 return Ty; 402 } 403 } 404 405 // RecordTypes are cached and processed specially. 406 if (const RecordType *RT = dyn_cast<RecordType>(Ty)) 407 return ConvertRecordDeclType(RT->getDecl()); 408 409 // See if type is already cached. 410 llvm::DenseMap<const Type *, llvm::Type *>::iterator TCI = TypeCache.find(Ty); 411 // If type is found in map then use it. Otherwise, convert type T. 412 if (TCI != TypeCache.end()) 413 return TCI->second; 414 415 // If we don't have it in the cache, convert it now. 416 llvm::Type *ResultType = nullptr; 417 switch (Ty->getTypeClass()) { 418 case Type::Record: // Handled above. 419 #define TYPE(Class, Base) 420 #define ABSTRACT_TYPE(Class, Base) 421 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 422 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 423 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 424 #include "clang/AST/TypeNodes.inc" 425 llvm_unreachable("Non-canonical or dependent types aren't possible."); 426 427 case Type::Builtin: { 428 switch (cast<BuiltinType>(Ty)->getKind()) { 429 case BuiltinType::Void: 430 case BuiltinType::ObjCId: 431 case BuiltinType::ObjCClass: 432 case BuiltinType::ObjCSel: 433 // LLVM void type can only be used as the result of a function call. Just 434 // map to the same as char. 435 ResultType = llvm::Type::getInt8Ty(getLLVMContext()); 436 break; 437 438 case BuiltinType::Bool: 439 // Note that we always return bool as i1 for use as a scalar type. 440 ResultType = llvm::Type::getInt1Ty(getLLVMContext()); 441 break; 442 443 case BuiltinType::Char_S: 444 case BuiltinType::Char_U: 445 case BuiltinType::SChar: 446 case BuiltinType::UChar: 447 case BuiltinType::Short: 448 case BuiltinType::UShort: 449 case BuiltinType::Int: 450 case BuiltinType::UInt: 451 case BuiltinType::Long: 452 case BuiltinType::ULong: 453 case BuiltinType::LongLong: 454 case BuiltinType::ULongLong: 455 case BuiltinType::WChar_S: 456 case BuiltinType::WChar_U: 457 case BuiltinType::Char8: 458 case BuiltinType::Char16: 459 case BuiltinType::Char32: 460 case BuiltinType::ShortAccum: 461 case BuiltinType::Accum: 462 case BuiltinType::LongAccum: 463 case BuiltinType::UShortAccum: 464 case BuiltinType::UAccum: 465 case BuiltinType::ULongAccum: 466 case BuiltinType::ShortFract: 467 case BuiltinType::Fract: 468 case BuiltinType::LongFract: 469 case BuiltinType::UShortFract: 470 case BuiltinType::UFract: 471 case BuiltinType::ULongFract: 472 case BuiltinType::SatShortAccum: 473 case BuiltinType::SatAccum: 474 case BuiltinType::SatLongAccum: 475 case BuiltinType::SatUShortAccum: 476 case BuiltinType::SatUAccum: 477 case BuiltinType::SatULongAccum: 478 case BuiltinType::SatShortFract: 479 case BuiltinType::SatFract: 480 case BuiltinType::SatLongFract: 481 case BuiltinType::SatUShortFract: 482 case BuiltinType::SatUFract: 483 case BuiltinType::SatULongFract: 484 ResultType = llvm::IntegerType::get(getLLVMContext(), 485 static_cast<unsigned>(Context.getTypeSize(T))); 486 break; 487 488 case BuiltinType::Float16: 489 ResultType = 490 getTypeForFormat(getLLVMContext(), Context.getFloatTypeSemantics(T), 491 /* UseNativeHalf = */ true); 492 break; 493 494 case BuiltinType::Half: 495 // Half FP can either be storage-only (lowered to i16) or native. 496 ResultType = getTypeForFormat( 497 getLLVMContext(), Context.getFloatTypeSemantics(T), 498 Context.getLangOpts().NativeHalfType || 499 !Context.getTargetInfo().useFP16ConversionIntrinsics()); 500 break; 501 case BuiltinType::Float: 502 case BuiltinType::Double: 503 case BuiltinType::LongDouble: 504 case BuiltinType::Float128: 505 ResultType = getTypeForFormat(getLLVMContext(), 506 Context.getFloatTypeSemantics(T), 507 /* UseNativeHalf = */ false); 508 break; 509 510 case BuiltinType::NullPtr: 511 // Model std::nullptr_t as i8* 512 ResultType = llvm::Type::getInt8PtrTy(getLLVMContext()); 513 break; 514 515 case BuiltinType::UInt128: 516 case BuiltinType::Int128: 517 ResultType = llvm::IntegerType::get(getLLVMContext(), 128); 518 break; 519 520 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 521 case BuiltinType::Id: 522 #include "clang/Basic/OpenCLImageTypes.def" 523 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 524 case BuiltinType::Id: 525 #include "clang/Basic/OpenCLExtensionTypes.def" 526 case BuiltinType::OCLSampler: 527 case BuiltinType::OCLEvent: 528 case BuiltinType::OCLClkEvent: 529 case BuiltinType::OCLQueue: 530 case BuiltinType::OCLReserveID: 531 ResultType = CGM.getOpenCLRuntime().convertOpenCLSpecificType(Ty); 532 break; 533 case BuiltinType::SveInt8: 534 case BuiltinType::SveUint8: 535 return llvm::VectorType::get(llvm::IntegerType::get(getLLVMContext(), 8), 536 {16, true}); 537 case BuiltinType::SveInt16: 538 case BuiltinType::SveUint16: 539 return llvm::VectorType::get(llvm::IntegerType::get(getLLVMContext(), 16), 540 {8, true}); 541 case BuiltinType::SveInt32: 542 case BuiltinType::SveUint32: 543 return llvm::VectorType::get(llvm::IntegerType::get(getLLVMContext(), 32), 544 {4, true}); 545 case BuiltinType::SveInt64: 546 case BuiltinType::SveUint64: 547 return llvm::VectorType::get(llvm::IntegerType::get(getLLVMContext(), 64), 548 {2, true}); 549 case BuiltinType::SveFloat16: 550 return llvm::VectorType::get( 551 getTypeForFormat(getLLVMContext(), 552 Context.getFloatTypeSemantics(Context.HalfTy), 553 /* UseNativeHalf = */ true), 554 {8, true}); 555 case BuiltinType::SveFloat32: 556 return llvm::VectorType::get( 557 getTypeForFormat(getLLVMContext(), 558 Context.getFloatTypeSemantics(Context.FloatTy), 559 /* UseNativeHalf = */ false), 560 {4, true}); 561 case BuiltinType::SveFloat64: 562 return llvm::VectorType::get( 563 getTypeForFormat(getLLVMContext(), 564 Context.getFloatTypeSemantics(Context.DoubleTy), 565 /* UseNativeHalf = */ false), 566 {2, true}); 567 case BuiltinType::SveBool: 568 return llvm::VectorType::get(llvm::IntegerType::get(getLLVMContext(), 1), 569 {16, true}); 570 break; 571 case BuiltinType::Dependent: 572 #define BUILTIN_TYPE(Id, SingletonId) 573 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 574 case BuiltinType::Id: 575 #include "clang/AST/BuiltinTypes.def" 576 llvm_unreachable("Unexpected placeholder builtin type!"); 577 } 578 break; 579 } 580 case Type::Auto: 581 case Type::DeducedTemplateSpecialization: 582 llvm_unreachable("Unexpected undeduced type!"); 583 case Type::Complex: { 584 llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType()); 585 ResultType = llvm::StructType::get(EltTy, EltTy); 586 break; 587 } 588 case Type::LValueReference: 589 case Type::RValueReference: { 590 const ReferenceType *RTy = cast<ReferenceType>(Ty); 591 QualType ETy = RTy->getPointeeType(); 592 llvm::Type *PointeeType = ConvertTypeForMem(ETy); 593 unsigned AS = Context.getTargetAddressSpace(ETy); 594 ResultType = llvm::PointerType::get(PointeeType, AS); 595 break; 596 } 597 case Type::Pointer: { 598 const PointerType *PTy = cast<PointerType>(Ty); 599 QualType ETy = PTy->getPointeeType(); 600 llvm::Type *PointeeType = ConvertTypeForMem(ETy); 601 if (PointeeType->isVoidTy()) 602 PointeeType = llvm::Type::getInt8Ty(getLLVMContext()); 603 604 unsigned AS = PointeeType->isFunctionTy() 605 ? getDataLayout().getProgramAddressSpace() 606 : Context.getTargetAddressSpace(ETy); 607 608 ResultType = llvm::PointerType::get(PointeeType, AS); 609 break; 610 } 611 612 case Type::VariableArray: { 613 const VariableArrayType *A = cast<VariableArrayType>(Ty); 614 assert(A->getIndexTypeCVRQualifiers() == 0 && 615 "FIXME: We only handle trivial array types so far!"); 616 // VLAs resolve to the innermost element type; this matches 617 // the return of alloca, and there isn't any obviously better choice. 618 ResultType = ConvertTypeForMem(A->getElementType()); 619 break; 620 } 621 case Type::IncompleteArray: { 622 const IncompleteArrayType *A = cast<IncompleteArrayType>(Ty); 623 assert(A->getIndexTypeCVRQualifiers() == 0 && 624 "FIXME: We only handle trivial array types so far!"); 625 // int X[] -> [0 x int], unless the element type is not sized. If it is 626 // unsized (e.g. an incomplete struct) just use [0 x i8]. 627 ResultType = ConvertTypeForMem(A->getElementType()); 628 if (!ResultType->isSized()) { 629 SkippedLayout = true; 630 ResultType = llvm::Type::getInt8Ty(getLLVMContext()); 631 } 632 ResultType = llvm::ArrayType::get(ResultType, 0); 633 break; 634 } 635 case Type::ConstantArray: { 636 const ConstantArrayType *A = cast<ConstantArrayType>(Ty); 637 llvm::Type *EltTy = ConvertTypeForMem(A->getElementType()); 638 639 // Lower arrays of undefined struct type to arrays of i8 just to have a 640 // concrete type. 641 if (!EltTy->isSized()) { 642 SkippedLayout = true; 643 EltTy = llvm::Type::getInt8Ty(getLLVMContext()); 644 } 645 646 ResultType = llvm::ArrayType::get(EltTy, A->getSize().getZExtValue()); 647 break; 648 } 649 case Type::ExtVector: 650 case Type::Vector: { 651 const VectorType *VT = cast<VectorType>(Ty); 652 ResultType = llvm::FixedVectorType::get(ConvertType(VT->getElementType()), 653 VT->getNumElements()); 654 break; 655 } 656 case Type::ConstantMatrix: { 657 const ConstantMatrixType *MT = cast<ConstantMatrixType>(Ty); 658 ResultType = 659 llvm::FixedVectorType::get(ConvertType(MT->getElementType()), 660 MT->getNumRows() * MT->getNumColumns()); 661 break; 662 } 663 case Type::FunctionNoProto: 664 case Type::FunctionProto: 665 ResultType = ConvertFunctionTypeInternal(T); 666 break; 667 case Type::ObjCObject: 668 ResultType = ConvertType(cast<ObjCObjectType>(Ty)->getBaseType()); 669 break; 670 671 case Type::ObjCInterface: { 672 // Objective-C interfaces are always opaque (outside of the 673 // runtime, which can do whatever it likes); we never refine 674 // these. 675 llvm::Type *&T = InterfaceTypes[cast<ObjCInterfaceType>(Ty)]; 676 if (!T) 677 T = llvm::StructType::create(getLLVMContext()); 678 ResultType = T; 679 break; 680 } 681 682 case Type::ObjCObjectPointer: { 683 // Protocol qualifications do not influence the LLVM type, we just return a 684 // pointer to the underlying interface type. We don't need to worry about 685 // recursive conversion. 686 llvm::Type *T = 687 ConvertTypeForMem(cast<ObjCObjectPointerType>(Ty)->getPointeeType()); 688 ResultType = T->getPointerTo(); 689 break; 690 } 691 692 case Type::Enum: { 693 const EnumDecl *ED = cast<EnumType>(Ty)->getDecl(); 694 if (ED->isCompleteDefinition() || ED->isFixed()) 695 return ConvertType(ED->getIntegerType()); 696 // Return a placeholder 'i32' type. This can be changed later when the 697 // type is defined (see UpdateCompletedType), but is likely to be the 698 // "right" answer. 699 ResultType = llvm::Type::getInt32Ty(getLLVMContext()); 700 break; 701 } 702 703 case Type::BlockPointer: { 704 const QualType FTy = cast<BlockPointerType>(Ty)->getPointeeType(); 705 llvm::Type *PointeeType = CGM.getLangOpts().OpenCL 706 ? CGM.getGenericBlockLiteralType() 707 : ConvertTypeForMem(FTy); 708 unsigned AS = Context.getTargetAddressSpace(FTy); 709 ResultType = llvm::PointerType::get(PointeeType, AS); 710 break; 711 } 712 713 case Type::MemberPointer: { 714 auto *MPTy = cast<MemberPointerType>(Ty); 715 if (!getCXXABI().isMemberPointerConvertible(MPTy)) { 716 RecordsWithOpaqueMemberPointers.insert(MPTy->getClass()); 717 ResultType = llvm::StructType::create(getLLVMContext()); 718 } else { 719 ResultType = getCXXABI().ConvertMemberPointerType(MPTy); 720 } 721 break; 722 } 723 724 case Type::Atomic: { 725 QualType valueType = cast<AtomicType>(Ty)->getValueType(); 726 ResultType = ConvertTypeForMem(valueType); 727 728 // Pad out to the inflated size if necessary. 729 uint64_t valueSize = Context.getTypeSize(valueType); 730 uint64_t atomicSize = Context.getTypeSize(Ty); 731 if (valueSize != atomicSize) { 732 assert(valueSize < atomicSize); 733 llvm::Type *elts[] = { 734 ResultType, 735 llvm::ArrayType::get(CGM.Int8Ty, (atomicSize - valueSize) / 8) 736 }; 737 ResultType = llvm::StructType::get(getLLVMContext(), 738 llvm::makeArrayRef(elts)); 739 } 740 break; 741 } 742 case Type::Pipe: { 743 ResultType = CGM.getOpenCLRuntime().getPipeType(cast<PipeType>(Ty)); 744 break; 745 } 746 case Type::ExtInt: { 747 const auto &EIT = cast<ExtIntType>(Ty); 748 ResultType = llvm::Type::getIntNTy(getLLVMContext(), EIT->getNumBits()); 749 break; 750 } 751 } 752 753 assert(ResultType && "Didn't convert a type?"); 754 755 TypeCache[Ty] = ResultType; 756 return ResultType; 757 } 758 759 bool CodeGenModule::isPaddedAtomicType(QualType type) { 760 return isPaddedAtomicType(type->castAs<AtomicType>()); 761 } 762 763 bool CodeGenModule::isPaddedAtomicType(const AtomicType *type) { 764 return Context.getTypeSize(type) != Context.getTypeSize(type->getValueType()); 765 } 766 767 /// ConvertRecordDeclType - Lay out a tagged decl type like struct or union. 768 llvm::StructType *CodeGenTypes::ConvertRecordDeclType(const RecordDecl *RD) { 769 // TagDecl's are not necessarily unique, instead use the (clang) 770 // type connected to the decl. 771 const Type *Key = Context.getTagDeclType(RD).getTypePtr(); 772 773 llvm::StructType *&Entry = RecordDeclTypes[Key]; 774 775 // If we don't have a StructType at all yet, create the forward declaration. 776 if (!Entry) { 777 Entry = llvm::StructType::create(getLLVMContext()); 778 addRecordTypeName(RD, Entry, ""); 779 } 780 llvm::StructType *Ty = Entry; 781 782 // If this is still a forward declaration, or the LLVM type is already 783 // complete, there's nothing more to do. 784 RD = RD->getDefinition(); 785 if (!RD || !RD->isCompleteDefinition() || !Ty->isOpaque()) 786 return Ty; 787 788 // If converting this type would cause us to infinitely loop, don't do it! 789 if (!isSafeToConvert(RD, *this)) { 790 DeferredRecords.push_back(RD); 791 return Ty; 792 } 793 794 // Okay, this is a definition of a type. Compile the implementation now. 795 bool InsertResult = RecordsBeingLaidOut.insert(Key).second; 796 (void)InsertResult; 797 assert(InsertResult && "Recursively compiling a struct?"); 798 799 // Force conversion of non-virtual base classes recursively. 800 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 801 for (const auto &I : CRD->bases()) { 802 if (I.isVirtual()) continue; 803 ConvertRecordDeclType(I.getType()->castAs<RecordType>()->getDecl()); 804 } 805 } 806 807 // Layout fields. 808 std::unique_ptr<CGRecordLayout> Layout = ComputeRecordLayout(RD, Ty); 809 CGRecordLayouts[Key] = std::move(Layout); 810 811 // We're done laying out this struct. 812 bool EraseResult = RecordsBeingLaidOut.erase(Key); (void)EraseResult; 813 assert(EraseResult && "struct not in RecordsBeingLaidOut set?"); 814 815 // If this struct blocked a FunctionType conversion, then recompute whatever 816 // was derived from that. 817 // FIXME: This is hugely overconservative. 818 if (SkippedLayout) 819 TypeCache.clear(); 820 821 // If we're done converting the outer-most record, then convert any deferred 822 // structs as well. 823 if (RecordsBeingLaidOut.empty()) 824 while (!DeferredRecords.empty()) 825 ConvertRecordDeclType(DeferredRecords.pop_back_val()); 826 827 return Ty; 828 } 829 830 /// getCGRecordLayout - Return record layout info for the given record decl. 831 const CGRecordLayout & 832 CodeGenTypes::getCGRecordLayout(const RecordDecl *RD) { 833 const Type *Key = Context.getTagDeclType(RD).getTypePtr(); 834 835 auto I = CGRecordLayouts.find(Key); 836 if (I != CGRecordLayouts.end()) 837 return *I->second; 838 // Compute the type information. 839 ConvertRecordDeclType(RD); 840 841 // Now try again. 842 I = CGRecordLayouts.find(Key); 843 844 assert(I != CGRecordLayouts.end() && 845 "Unable to find record layout information for type"); 846 return *I->second; 847 } 848 849 bool CodeGenTypes::isPointerZeroInitializable(QualType T) { 850 assert((T->isAnyPointerType() || T->isBlockPointerType()) && "Invalid type"); 851 return isZeroInitializable(T); 852 } 853 854 bool CodeGenTypes::isZeroInitializable(QualType T) { 855 if (T->getAs<PointerType>()) 856 return Context.getTargetNullPointerValue(T) == 0; 857 858 if (const auto *AT = Context.getAsArrayType(T)) { 859 if (isa<IncompleteArrayType>(AT)) 860 return true; 861 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) 862 if (Context.getConstantArrayElementCount(CAT) == 0) 863 return true; 864 T = Context.getBaseElementType(T); 865 } 866 867 // Records are non-zero-initializable if they contain any 868 // non-zero-initializable subobjects. 869 if (const RecordType *RT = T->getAs<RecordType>()) { 870 const RecordDecl *RD = RT->getDecl(); 871 return isZeroInitializable(RD); 872 } 873 874 // We have to ask the ABI about member pointers. 875 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) 876 return getCXXABI().isZeroInitializable(MPT); 877 878 // Everything else is okay. 879 return true; 880 } 881 882 bool CodeGenTypes::isZeroInitializable(const RecordDecl *RD) { 883 return getCGRecordLayout(RD).isZeroInitializable(); 884 } 885