685 case TargetCXXABI::GenericItanium: 686 return CreateItaniumCXXABI(*this); 687 case TargetCXXABI::Microsoft: 688 return CreateMicrosoftCXXABI(*this); 689 } 690 llvm_unreachable("Invalid CXXABI type!"); 691} 692 693static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 694 const LangOptions &LOpts) { 695 if (LOpts.FakeAddressSpaceMap) { 696 // The fake address space map must have a distinct entry for each 697 // language-specific address space. 698 static const unsigned FakeAddrSpaceMap[] = { 699 1, // opencl_global 700 2, // opencl_local 701 3, // opencl_constant 702 4, // opencl_generic 703 5, // cuda_device 704 6, // cuda_constant 705 7 // cuda_shared 706 }; 707 return &FakeAddrSpaceMap; 708 } else { 709 return &T.getAddressSpaceMap(); 710 } 711} 712 713static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 714 const LangOptions &LangOpts) { 715 switch (LangOpts.getAddressSpaceMapMangling()) { 716 case LangOptions::ASMM_Target: 717 return TI.useAddressSpaceMapMangling(); 718 case LangOptions::ASMM_On: 719 return true; 720 case LangOptions::ASMM_Off: 721 return false; 722 } 723 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 724} 725 726ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 727 IdentifierTable &idents, SelectorTable &sels, 728 Builtin::Context &builtins) 729 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()), 730 DependentTemplateSpecializationTypes(this_()), 731 SubstTemplateTemplateParmPacks(this_()), 732 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr), 733 UInt128Decl(nullptr), Float128StubDecl(nullptr), 734 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), 735 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr), 736 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr), 737 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr), 738 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr), 739 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr), 740 FirstLocalImport(), LastLocalImport(), 741 SourceMgr(SM), LangOpts(LOpts), 742 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, SM)), 743 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts), 744 Idents(idents), Selectors(sels), BuiltinInfo(builtins), 745 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr), 746 Comments(SM), CommentsLoaded(false), 747 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) { 748 TUDecl = TranslationUnitDecl::Create(*this); 749} 750 751ASTContext::~ASTContext() { 752 ReleaseParentMapEntries(); 753 754 // Release the DenseMaps associated with DeclContext objects. 755 // FIXME: Is this the ideal solution? 756 ReleaseDeclContextMaps(); 757 758 // Call all of the deallocation functions on all of their targets. 759 for (DeallocationMap::const_iterator I = Deallocations.begin(), 760 E = Deallocations.end(); I != E; ++I) 761 for (unsigned J = 0, N = I->second.size(); J != N; ++J) 762 (I->first)((I->second)[J]); 763 764 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 765 // because they can contain DenseMaps. 766 for (llvm::DenseMap<const ObjCContainerDecl*, 767 const ASTRecordLayout*>::iterator 768 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 769 // Increment in loop to prevent using deallocated memory. 770 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 771 R->Destroy(*this); 772 773 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 774 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 775 // Increment in loop to prevent using deallocated memory. 776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 777 R->Destroy(*this); 778 } 779 780 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 781 AEnd = DeclAttrs.end(); 782 A != AEnd; ++A) 783 A->second->~AttrVec(); 784 785 llvm::DeleteContainerSeconds(MangleNumberingContexts); 786} 787 788void ASTContext::ReleaseParentMapEntries() { 789 if (!AllParents) return; 790 for (const auto &Entry : *AllParents) { 791 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 792 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 793 } else { 794 assert(Entry.second.is<ParentVector *>()); 795 delete Entry.second.get<ParentVector *>(); 796 } 797 } 798} 799 800void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 801 Deallocations[Callback].push_back(Data); 802} 803 804void 805ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 806 ExternalSource = Source; 807} 808 809void ASTContext::PrintStats() const { 810 llvm::errs() << "\n*** AST Context Stats:\n"; 811 llvm::errs() << " " << Types.size() << " types total.\n"; 812 813 unsigned counts[] = { 814#define TYPE(Name, Parent) 0, 815#define ABSTRACT_TYPE(Name, Parent) 816#include "clang/AST/TypeNodes.def" 817 0 // Extra 818 }; 819 820 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 821 Type *T = Types[i]; 822 counts[(unsigned)T->getTypeClass()]++; 823 } 824 825 unsigned Idx = 0; 826 unsigned TotalBytes = 0; 827#define TYPE(Name, Parent) \ 828 if (counts[Idx]) \ 829 llvm::errs() << " " << counts[Idx] << " " << #Name \ 830 << " types\n"; \ 831 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 832 ++Idx; 833#define ABSTRACT_TYPE(Name, Parent) 834#include "clang/AST/TypeNodes.def" 835 836 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 837 838 // Implicit special member functions. 839 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 840 << NumImplicitDefaultConstructors 841 << " implicit default constructors created\n"; 842 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 843 << NumImplicitCopyConstructors 844 << " implicit copy constructors created\n"; 845 if (getLangOpts().CPlusPlus) 846 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 847 << NumImplicitMoveConstructors 848 << " implicit move constructors created\n"; 849 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 850 << NumImplicitCopyAssignmentOperators 851 << " implicit copy assignment operators created\n"; 852 if (getLangOpts().CPlusPlus) 853 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 854 << NumImplicitMoveAssignmentOperators 855 << " implicit move assignment operators created\n"; 856 llvm::errs() << NumImplicitDestructorsDeclared << "/" 857 << NumImplicitDestructors 858 << " implicit destructors created\n"; 859 860 if (ExternalSource) { 861 llvm::errs() << "\n"; 862 ExternalSource->PrintStats(); 863 } 864 865 BumpAlloc.PrintStats(); 866} 867 868RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 869 RecordDecl::TagKind TK) const { 870 SourceLocation Loc; 871 RecordDecl *NewDecl; 872 if (getLangOpts().CPlusPlus) 873 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 874 Loc, &Idents.get(Name)); 875 else 876 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 877 &Idents.get(Name)); 878 NewDecl->setImplicit(); 879 return NewDecl; 880} 881 882TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 883 StringRef Name) const { 884 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 885 TypedefDecl *NewDecl = TypedefDecl::Create( 886 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 887 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 888 NewDecl->setImplicit(); 889 return NewDecl; 890} 891 892TypedefDecl *ASTContext::getInt128Decl() const { 893 if (!Int128Decl) 894 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 895 return Int128Decl; 896} 897 898TypedefDecl *ASTContext::getUInt128Decl() const { 899 if (!UInt128Decl) 900 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 901 return UInt128Decl; 902} 903 904TypeDecl *ASTContext::getFloat128StubType() const { 905 assert(LangOpts.CPlusPlus && "should only be called for c++"); 906 if (!Float128StubDecl) 907 Float128StubDecl = buildImplicitRecord("__float128"); 908 909 return Float128StubDecl; 910} 911 912void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 913 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 914 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 915 Types.push_back(Ty); 916} 917 918void ASTContext::InitBuiltinTypes(const TargetInfo &Target) { 919 assert((!this->Target || this->Target == &Target) && 920 "Incorrect target reinitialization"); 921 assert(VoidTy.isNull() && "Context reinitialized?"); 922 923 this->Target = &Target; 924 925 ABI.reset(createCXXABI(Target)); 926 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 927 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 928 929 // C99 6.2.5p19. 930 InitBuiltinType(VoidTy, BuiltinType::Void); 931 932 // C99 6.2.5p2. 933 InitBuiltinType(BoolTy, BuiltinType::Bool); 934 // C99 6.2.5p3. 935 if (LangOpts.CharIsSigned) 936 InitBuiltinType(CharTy, BuiltinType::Char_S); 937 else 938 InitBuiltinType(CharTy, BuiltinType::Char_U); 939 // C99 6.2.5p4. 940 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 941 InitBuiltinType(ShortTy, BuiltinType::Short); 942 InitBuiltinType(IntTy, BuiltinType::Int); 943 InitBuiltinType(LongTy, BuiltinType::Long); 944 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 945 946 // C99 6.2.5p6. 947 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 948 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 949 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 950 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 951 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 952 953 // C99 6.2.5p10. 954 InitBuiltinType(FloatTy, BuiltinType::Float); 955 InitBuiltinType(DoubleTy, BuiltinType::Double); 956 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 957 958 // GNU extension, 128-bit integers. 959 InitBuiltinType(Int128Ty, BuiltinType::Int128); 960 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 961 962 // C++ 3.9.1p5 963 if (TargetInfo::isTypeSigned(Target.getWCharType())) 964 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 965 else // -fshort-wchar makes wchar_t be unsigned. 966 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 967 if (LangOpts.CPlusPlus && LangOpts.WChar) 968 WideCharTy = WCharTy; 969 else { 970 // C99 (or C++ using -fno-wchar). 971 WideCharTy = getFromTargetType(Target.getWCharType()); 972 } 973 974 WIntTy = getFromTargetType(Target.getWIntType()); 975 976 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 977 InitBuiltinType(Char16Ty, BuiltinType::Char16); 978 else // C99 979 Char16Ty = getFromTargetType(Target.getChar16Type()); 980 981 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 982 InitBuiltinType(Char32Ty, BuiltinType::Char32); 983 else // C99 984 Char32Ty = getFromTargetType(Target.getChar32Type()); 985 986 // Placeholder type for type-dependent expressions whose type is 987 // completely unknown. No code should ever check a type against 988 // DependentTy and users should never see it; however, it is here to 989 // help diagnose failures to properly check for type-dependent 990 // expressions. 991 InitBuiltinType(DependentTy, BuiltinType::Dependent); 992 993 // Placeholder type for functions. 994 InitBuiltinType(OverloadTy, BuiltinType::Overload); 995 996 // Placeholder type for bound members. 997 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 998 999 // Placeholder type for pseudo-objects. 1000 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1001 1002 // "any" type; useful for debugger-like clients. 1003 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1004 1005 // Placeholder type for unbridged ARC casts. 1006 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1007 1008 // Placeholder type for builtin functions. 1009 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1010 1011 // C99 6.2.5p11. 1012 FloatComplexTy = getComplexType(FloatTy); 1013 DoubleComplexTy = getComplexType(DoubleTy); 1014 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1015 1016 // Builtin types for 'id', 'Class', and 'SEL'. 1017 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1018 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1019 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1020 1021 if (LangOpts.OpenCL) { 1022 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d); 1023 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray); 1024 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer); 1025 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d); 1026 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray); 1027 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d); 1028 1029 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1030 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1031 } 1032 1033 // Builtin type for __objc_yes and __objc_no 1034 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1035 SignedCharTy : BoolTy); 1036 1037 ObjCConstantStringType = QualType(); 1038 1039 ObjCSuperType = QualType(); 1040 1041 // void * type 1042 VoidPtrTy = getPointerType(VoidTy); 1043 1044 // nullptr type (C++0x 2.14.7) 1045 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1046 1047 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1048 InitBuiltinType(HalfTy, BuiltinType::Half); 1049 1050 // Builtin type used to help define __builtin_va_list. 1051 VaListTagTy = QualType(); 1052} 1053 1054DiagnosticsEngine &ASTContext::getDiagnostics() const { 1055 return SourceMgr.getDiagnostics(); 1056} 1057 1058AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1059 AttrVec *&Result = DeclAttrs[D]; 1060 if (!Result) { 1061 void *Mem = Allocate(sizeof(AttrVec)); 1062 Result = new (Mem) AttrVec; 1063 } 1064 1065 return *Result; 1066} 1067 1068/// \brief Erase the attributes corresponding to the given declaration. 1069void ASTContext::eraseDeclAttrs(const Decl *D) { 1070 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1071 if (Pos != DeclAttrs.end()) { 1072 Pos->second->~AttrVec(); 1073 DeclAttrs.erase(Pos); 1074 } 1075} 1076 1077// FIXME: Remove ? 1078MemberSpecializationInfo * 1079ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1080 assert(Var->isStaticDataMember() && "Not a static data member"); 1081 return getTemplateOrSpecializationInfo(Var) 1082 .dyn_cast<MemberSpecializationInfo *>(); 1083} 1084 1085ASTContext::TemplateOrSpecializationInfo 1086ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1087 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1088 TemplateOrInstantiation.find(Var); 1089 if (Pos == TemplateOrInstantiation.end()) 1090 return TemplateOrSpecializationInfo(); 1091 1092 return Pos->second; 1093} 1094 1095void 1096ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1097 TemplateSpecializationKind TSK, 1098 SourceLocation PointOfInstantiation) { 1099 assert(Inst->isStaticDataMember() && "Not a static data member"); 1100 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1101 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1102 Tmpl, TSK, PointOfInstantiation)); 1103} 1104 1105void 1106ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1107 TemplateOrSpecializationInfo TSI) { 1108 assert(!TemplateOrInstantiation[Inst] && 1109 "Already noted what the variable was instantiated from"); 1110 TemplateOrInstantiation[Inst] = TSI; 1111} 1112 1113FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 1114 const FunctionDecl *FD){ 1115 assert(FD && "Specialization is 0"); 1116 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 1117 = ClassScopeSpecializationPattern.find(FD); 1118 if (Pos == ClassScopeSpecializationPattern.end()) 1119 return nullptr; 1120 1121 return Pos->second; 1122} 1123 1124void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 1125 FunctionDecl *Pattern) { 1126 assert(FD && "Specialization is 0"); 1127 assert(Pattern && "Class scope specialization pattern is 0"); 1128 ClassScopeSpecializationPattern[FD] = Pattern; 1129} 1130 1131NamedDecl * 1132ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 1133 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 1134 = InstantiatedFromUsingDecl.find(UUD); 1135 if (Pos == InstantiatedFromUsingDecl.end()) 1136 return nullptr; 1137 1138 return Pos->second; 1139} 1140 1141void 1142ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 1143 assert((isa<UsingDecl>(Pattern) || 1144 isa<UnresolvedUsingValueDecl>(Pattern) || 1145 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1146 "pattern decl is not a using decl"); 1147 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1148 InstantiatedFromUsingDecl[Inst] = Pattern; 1149} 1150 1151UsingShadowDecl * 1152ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1153 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1154 = InstantiatedFromUsingShadowDecl.find(Inst); 1155 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1156 return nullptr; 1157 1158 return Pos->second; 1159} 1160 1161void 1162ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1163 UsingShadowDecl *Pattern) { 1164 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1165 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1166} 1167 1168FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1169 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1170 = InstantiatedFromUnnamedFieldDecl.find(Field); 1171 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1172 return nullptr; 1173 1174 return Pos->second; 1175} 1176 1177void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1178 FieldDecl *Tmpl) { 1179 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1180 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1181 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1182 "Already noted what unnamed field was instantiated from"); 1183 1184 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1185} 1186 1187ASTContext::overridden_cxx_method_iterator 1188ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1189 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1190 = OverriddenMethods.find(Method->getCanonicalDecl()); 1191 if (Pos == OverriddenMethods.end()) 1192 return nullptr; 1193 1194 return Pos->second.begin(); 1195} 1196 1197ASTContext::overridden_cxx_method_iterator 1198ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1199 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1200 = OverriddenMethods.find(Method->getCanonicalDecl()); 1201 if (Pos == OverriddenMethods.end()) 1202 return nullptr; 1203 1204 return Pos->second.end(); 1205} 1206 1207unsigned 1208ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1209 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1210 = OverriddenMethods.find(Method->getCanonicalDecl()); 1211 if (Pos == OverriddenMethods.end()) 1212 return 0; 1213 1214 return Pos->second.size(); 1215} 1216 1217void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1218 const CXXMethodDecl *Overridden) { 1219 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1220 OverriddenMethods[Method].push_back(Overridden); 1221} 1222 1223void ASTContext::getOverriddenMethods( 1224 const NamedDecl *D, 1225 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1226 assert(D); 1227 1228 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1229 Overridden.append(overridden_methods_begin(CXXMethod), 1230 overridden_methods_end(CXXMethod)); 1231 return; 1232 } 1233 1234 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 1235 if (!Method) 1236 return; 1237 1238 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1239 Method->getOverriddenMethods(OverDecls); 1240 Overridden.append(OverDecls.begin(), OverDecls.end()); 1241} 1242 1243void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1244 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 1245 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1246 if (!FirstLocalImport) { 1247 FirstLocalImport = Import; 1248 LastLocalImport = Import; 1249 return; 1250 } 1251 1252 LastLocalImport->NextLocalImport = Import; 1253 LastLocalImport = Import; 1254} 1255 1256//===----------------------------------------------------------------------===// 1257// Type Sizing and Analysis 1258//===----------------------------------------------------------------------===// 1259 1260/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1261/// scalar floating point type. 1262const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1263 const BuiltinType *BT = T->getAs<BuiltinType>(); 1264 assert(BT && "Not a floating point type!"); 1265 switch (BT->getKind()) { 1266 default: llvm_unreachable("Not a floating point type!"); 1267 case BuiltinType::Half: return Target->getHalfFormat(); 1268 case BuiltinType::Float: return Target->getFloatFormat(); 1269 case BuiltinType::Double: return Target->getDoubleFormat(); 1270 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 1271 } 1272} 1273 1274CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1275 unsigned Align = Target->getCharWidth(); 1276 1277 bool UseAlignAttrOnly = false; 1278 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1279 Align = AlignFromAttr; 1280 1281 // __attribute__((aligned)) can increase or decrease alignment 1282 // *except* on a struct or struct member, where it only increases 1283 // alignment unless 'packed' is also specified. 1284 // 1285 // It is an error for alignas to decrease alignment, so we can 1286 // ignore that possibility; Sema should diagnose it. 1287 if (isa<FieldDecl>(D)) { 1288 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1289 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1290 } else { 1291 UseAlignAttrOnly = true; 1292 } 1293 } 1294 else if (isa<FieldDecl>(D)) 1295 UseAlignAttrOnly = 1296 D->hasAttr<PackedAttr>() || 1297 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1298 1299 // If we're using the align attribute only, just ignore everything 1300 // else about the declaration and its type. 1301 if (UseAlignAttrOnly) { 1302 // do nothing 1303 1304 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1305 QualType T = VD->getType(); 1306 if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 1307 if (ForAlignof) 1308 T = RT->getPointeeType(); 1309 else 1310 T = getPointerType(RT->getPointeeType()); 1311 } 1312 QualType BaseT = getBaseElementType(T); 1313 if (!BaseT->isIncompleteType() && !T->isFunctionType()) { 1314 // Adjust alignments of declarations with array type by the 1315 // large-array alignment on the target. 1316 if (const ArrayType *arrayType = getAsArrayType(T)) { 1317 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1318 if (!ForAlignof && MinWidth) { 1319 if (isa<VariableArrayType>(arrayType)) 1320 Align = std::max(Align, Target->getLargeArrayAlign()); 1321 else if (isa<ConstantArrayType>(arrayType) && 1322 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1323 Align = std::max(Align, Target->getLargeArrayAlign()); 1324 } 1325 } 1326 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1327 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1328 if (VD->hasGlobalStorage()) 1329 Align = std::max(Align, getTargetInfo().getMinGlobalAlign()); 1330 } 1331 } 1332 1333 // Fields can be subject to extra alignment constraints, like if 1334 // the field is packed, the struct is packed, or the struct has a 1335 // a max-field-alignment constraint (#pragma pack). So calculate 1336 // the actual alignment of the field within the struct, and then 1337 // (as we're expected to) constrain that by the alignment of the type. 1338 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 1339 const RecordDecl *Parent = Field->getParent(); 1340 // We can only produce a sensible answer if the record is valid. 1341 if (!Parent->isInvalidDecl()) { 1342 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1343 1344 // Start with the record's overall alignment. 1345 unsigned FieldAlign = toBits(Layout.getAlignment()); 1346 1347 // Use the GCD of that and the offset within the record. 1348 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1349 if (Offset > 0) { 1350 // Alignment is always a power of 2, so the GCD will be a power of 2, 1351 // which means we get to do this crazy thing instead of Euclid's. 1352 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1353 if (LowBitOfOffset < FieldAlign) 1354 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1355 } 1356 1357 Align = std::min(Align, FieldAlign); 1358 } 1359 } 1360 } 1361 1362 return toCharUnitsFromBits(Align); 1363} 1364 1365// getTypeInfoDataSizeInChars - Return the size of a type, in 1366// chars. If the type is a record, its data size is returned. This is 1367// the size of the memcpy that's performed when assigning this type 1368// using a trivial copy/move assignment operator. 1369std::pair<CharUnits, CharUnits> 1370ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1371 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); 1372 1373 // In C++, objects can sometimes be allocated into the tail padding 1374 // of a base-class subobject. We decide whether that's possible 1375 // during class layout, so here we can just trust the layout results. 1376 if (getLangOpts().CPlusPlus) { 1377 if (const RecordType *RT = T->getAs<RecordType>()) { 1378 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1379 sizeAndAlign.first = layout.getDataSize(); 1380 } 1381 } 1382 1383 return sizeAndAlign; 1384} 1385 1386/// getConstantArrayInfoInChars - Performing the computation in CharUnits 1387/// instead of in bits prevents overflowing the uint64_t for some large arrays. 1388std::pair<CharUnits, CharUnits> 1389static getConstantArrayInfoInChars(const ASTContext &Context, 1390 const ConstantArrayType *CAT) { 1391 std::pair<CharUnits, CharUnits> EltInfo = 1392 Context.getTypeInfoInChars(CAT->getElementType()); 1393 uint64_t Size = CAT->getSize().getZExtValue(); 1394 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= 1395 (uint64_t)(-1)/Size) && 1396 "Overflow in array type char size evaluation"); 1397 uint64_t Width = EltInfo.first.getQuantity() * Size; 1398 unsigned Align = EltInfo.second.getQuantity(); 1399 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1400 Context.getTargetInfo().getPointerWidth(0) == 64) 1401 Width = llvm::RoundUpToAlignment(Width, Align); 1402 return std::make_pair(CharUnits::fromQuantity(Width), 1403 CharUnits::fromQuantity(Align)); 1404} 1405 1406std::pair<CharUnits, CharUnits> 1407ASTContext::getTypeInfoInChars(const Type *T) const { 1408 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) 1409 return getConstantArrayInfoInChars(*this, CAT); 1410 TypeInfo Info = getTypeInfo(T); 1411 return std::make_pair(toCharUnitsFromBits(Info.Width), 1412 toCharUnitsFromBits(Info.Align)); 1413} 1414 1415std::pair<CharUnits, CharUnits> 1416ASTContext::getTypeInfoInChars(QualType T) const { 1417 return getTypeInfoInChars(T.getTypePtr()); 1418} 1419 1420bool ASTContext::isAlignmentRequired(const Type *T) const { 1421 return getTypeInfo(T).AlignIsRequired; 1422} 1423 1424bool ASTContext::isAlignmentRequired(QualType T) const { 1425 return isAlignmentRequired(T.getTypePtr()); 1426} 1427 1428TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1429 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1430 if (I != MemoizedTypeInfo.end()) 1431 return I->second; 1432 1433 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1434 TypeInfo TI = getTypeInfoImpl(T); 1435 MemoizedTypeInfo[T] = TI; 1436 return TI; 1437} 1438 1439/// getTypeInfoImpl - Return the size of the specified type, in bits. This 1440/// method does not work on incomplete types. 1441/// 1442/// FIXME: Pointers into different addr spaces could have different sizes and 1443/// alignment requirements: getPointerInfo should take an AddrSpace, this 1444/// should take a QualType, &c. 1445TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1446 uint64_t Width = 0; 1447 unsigned Align = 8; 1448 bool AlignIsRequired = false; 1449 switch (T->getTypeClass()) { 1450#define TYPE(Class, Base) 1451#define ABSTRACT_TYPE(Class, Base) 1452#define NON_CANONICAL_TYPE(Class, Base) 1453#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1454#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1455 case Type::Class: \ 1456 assert(!T->isDependentType() && "should not see dependent types here"); \ 1457 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1458#include "clang/AST/TypeNodes.def" 1459 llvm_unreachable("Should not see dependent types"); 1460 1461 case Type::FunctionNoProto: 1462 case Type::FunctionProto: 1463 // GCC extension: alignof(function) = 32 bits 1464 Width = 0; 1465 Align = 32; 1466 break; 1467 1468 case Type::IncompleteArray: 1469 case Type::VariableArray: 1470 Width = 0; 1471 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 1472 break; 1473 1474 case Type::ConstantArray: { 1475 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 1476 1477 TypeInfo EltInfo = getTypeInfo(CAT->getElementType()); 1478 uint64_t Size = CAT->getSize().getZExtValue(); 1479 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1480 "Overflow in array type bit size evaluation"); 1481 Width = EltInfo.Width * Size; 1482 Align = EltInfo.Align; 1483 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1484 getTargetInfo().getPointerWidth(0) == 64) 1485 Width = llvm::RoundUpToAlignment(Width, Align); 1486 break; 1487 } 1488 case Type::ExtVector: 1489 case Type::Vector: { 1490 const VectorType *VT = cast<VectorType>(T); 1491 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1492 Width = EltInfo.Width * VT->getNumElements(); 1493 Align = Width; 1494 // If the alignment is not a power of 2, round up to the next power of 2. 1495 // This happens for non-power-of-2 length vectors. 1496 if (Align & (Align-1)) { 1497 Align = llvm::NextPowerOf2(Align); 1498 Width = llvm::RoundUpToAlignment(Width, Align); 1499 } 1500 // Adjust the alignment based on the target max. 1501 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1502 if (TargetVectorAlign && TargetVectorAlign < Align) 1503 Align = TargetVectorAlign; 1504 break; 1505 } 1506 1507 case Type::Builtin: 1508 switch (cast<BuiltinType>(T)->getKind()) { 1509 default: llvm_unreachable("Unknown builtin type!"); 1510 case BuiltinType::Void: 1511 // GCC extension: alignof(void) = 8 bits. 1512 Width = 0; 1513 Align = 8; 1514 break; 1515 1516 case BuiltinType::Bool: 1517 Width = Target->getBoolWidth(); 1518 Align = Target->getBoolAlign(); 1519 break; 1520 case BuiltinType::Char_S: 1521 case BuiltinType::Char_U: 1522 case BuiltinType::UChar: 1523 case BuiltinType::SChar: 1524 Width = Target->getCharWidth(); 1525 Align = Target->getCharAlign(); 1526 break; 1527 case BuiltinType::WChar_S: 1528 case BuiltinType::WChar_U: 1529 Width = Target->getWCharWidth(); 1530 Align = Target->getWCharAlign(); 1531 break; 1532 case BuiltinType::Char16: 1533 Width = Target->getChar16Width(); 1534 Align = Target->getChar16Align(); 1535 break; 1536 case BuiltinType::Char32: 1537 Width = Target->getChar32Width(); 1538 Align = Target->getChar32Align(); 1539 break; 1540 case BuiltinType::UShort: 1541 case BuiltinType::Short: 1542 Width = Target->getShortWidth(); 1543 Align = Target->getShortAlign(); 1544 break; 1545 case BuiltinType::UInt: 1546 case BuiltinType::Int: 1547 Width = Target->getIntWidth(); 1548 Align = Target->getIntAlign(); 1549 break; 1550 case BuiltinType::ULong: 1551 case BuiltinType::Long: 1552 Width = Target->getLongWidth(); 1553 Align = Target->getLongAlign(); 1554 break; 1555 case BuiltinType::ULongLong: 1556 case BuiltinType::LongLong: 1557 Width = Target->getLongLongWidth(); 1558 Align = Target->getLongLongAlign(); 1559 break; 1560 case BuiltinType::Int128: 1561 case BuiltinType::UInt128: 1562 Width = 128; 1563 Align = 128; // int128_t is 128-bit aligned on all targets. 1564 break; 1565 case BuiltinType::Half: 1566 Width = Target->getHalfWidth(); 1567 Align = Target->getHalfAlign(); 1568 break; 1569 case BuiltinType::Float: 1570 Width = Target->getFloatWidth(); 1571 Align = Target->getFloatAlign(); 1572 break; 1573 case BuiltinType::Double: 1574 Width = Target->getDoubleWidth(); 1575 Align = Target->getDoubleAlign(); 1576 break; 1577 case BuiltinType::LongDouble: 1578 Width = Target->getLongDoubleWidth(); 1579 Align = Target->getLongDoubleAlign(); 1580 break; 1581 case BuiltinType::NullPtr: 1582 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1583 Align = Target->getPointerAlign(0); // == sizeof(void*) 1584 break; 1585 case BuiltinType::ObjCId: 1586 case BuiltinType::ObjCClass: 1587 case BuiltinType::ObjCSel: 1588 Width = Target->getPointerWidth(0); 1589 Align = Target->getPointerAlign(0); 1590 break; 1591 case BuiltinType::OCLSampler: 1592 // Samplers are modeled as integers. 1593 Width = Target->getIntWidth(); 1594 Align = Target->getIntAlign(); 1595 break; 1596 case BuiltinType::OCLEvent: 1597 case BuiltinType::OCLImage1d: 1598 case BuiltinType::OCLImage1dArray: 1599 case BuiltinType::OCLImage1dBuffer: 1600 case BuiltinType::OCLImage2d: 1601 case BuiltinType::OCLImage2dArray: 1602 case BuiltinType::OCLImage3d: 1603 // Currently these types are pointers to opaque types. 1604 Width = Target->getPointerWidth(0); 1605 Align = Target->getPointerAlign(0); 1606 break; 1607 } 1608 break; 1609 case Type::ObjCObjectPointer: 1610 Width = Target->getPointerWidth(0); 1611 Align = Target->getPointerAlign(0); 1612 break; 1613 case Type::BlockPointer: { 1614 unsigned AS = getTargetAddressSpace( 1615 cast<BlockPointerType>(T)->getPointeeType()); 1616 Width = Target->getPointerWidth(AS); 1617 Align = Target->getPointerAlign(AS); 1618 break; 1619 } 1620 case Type::LValueReference: 1621 case Type::RValueReference: { 1622 // alignof and sizeof should never enter this code path here, so we go 1623 // the pointer route. 1624 unsigned AS = getTargetAddressSpace( 1625 cast<ReferenceType>(T)->getPointeeType()); 1626 Width = Target->getPointerWidth(AS); 1627 Align = Target->getPointerAlign(AS); 1628 break; 1629 } 1630 case Type::Pointer: { 1631 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1632 Width = Target->getPointerWidth(AS); 1633 Align = Target->getPointerAlign(AS); 1634 break; 1635 } 1636 case Type::MemberPointer: { 1637 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1638 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT); 1639 break; 1640 } 1641 case Type::Complex: { 1642 // Complex types have the same alignment as their elements, but twice the 1643 // size. 1644 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 1645 Width = EltInfo.Width * 2; 1646 Align = EltInfo.Align; 1647 break; 1648 } 1649 case Type::ObjCObject: 1650 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1651 case Type::Adjusted: 1652 case Type::Decayed: 1653 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 1654 case Type::ObjCInterface: { 1655 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1656 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1657 Width = toBits(Layout.getSize()); 1658 Align = toBits(Layout.getAlignment()); 1659 break; 1660 } 1661 case Type::Record: 1662 case Type::Enum: { 1663 const TagType *TT = cast<TagType>(T); 1664 1665 if (TT->getDecl()->isInvalidDecl()) { 1666 Width = 8; 1667 Align = 8; 1668 break; 1669 } 1670 1671 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 1672 return getTypeInfo(ET->getDecl()->getIntegerType()); 1673 1674 const RecordType *RT = cast<RecordType>(TT); 1675 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 1676 Width = toBits(Layout.getSize()); 1677 Align = toBits(Layout.getAlignment()); 1678 break; 1679 } 1680 1681 case Type::SubstTemplateTypeParm: 1682 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1683 getReplacementType().getTypePtr()); 1684 1685 case Type::Auto: { 1686 const AutoType *A = cast<AutoType>(T); 1687 assert(!A->getDeducedType().isNull() && 1688 "cannot request the size of an undeduced or dependent auto type"); 1689 return getTypeInfo(A->getDeducedType().getTypePtr()); 1690 } 1691 1692 case Type::Paren: 1693 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1694 1695 case Type::Typedef: { 1696 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1697 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1698 // If the typedef has an aligned attribute on it, it overrides any computed 1699 // alignment we have. This violates the GCC documentation (which says that 1700 // attribute(aligned) can only round up) but matches its implementation. 1701 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 1702 Align = AttrAlign; 1703 AlignIsRequired = true; 1704 } else { 1705 Align = Info.Align; 1706 AlignIsRequired = Info.AlignIsRequired; 1707 } 1708 Width = Info.Width; 1709 break; 1710 } 1711 1712 case Type::Elaborated: 1713 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1714 1715 case Type::Attributed: 1716 return getTypeInfo( 1717 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1718 1719 case Type::Atomic: { 1720 // Start with the base type information. 1721 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1722 Width = Info.Width; 1723 Align = Info.Align; 1724 1725 // If the size of the type doesn't exceed the platform's max 1726 // atomic promotion width, make the size and alignment more 1727 // favorable to atomic operations: 1728 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) { 1729 // Round the size up to a power of 2. 1730 if (!llvm::isPowerOf2_64(Width)) 1731 Width = llvm::NextPowerOf2(Width); 1732 1733 // Set the alignment equal to the size. 1734 Align = static_cast<unsigned>(Width); 1735 } 1736 } 1737 1738 } 1739 1740 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1741 return TypeInfo(Width, Align, AlignIsRequired); 1742} 1743 1744/// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1745CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1746 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1747} 1748 1749/// toBits - Convert a size in characters to a size in characters. 1750int64_t ASTContext::toBits(CharUnits CharSize) const { 1751 return CharSize.getQuantity() * getCharWidth(); 1752} 1753 1754/// getTypeSizeInChars - Return the size of the specified type, in characters. 1755/// This method does not work on incomplete types. 1756CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1757 return getTypeInfoInChars(T).first; 1758} 1759CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1760 return getTypeInfoInChars(T).first; 1761} 1762 1763/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1764/// characters. This method does not work on incomplete types. 1765CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1766 return toCharUnitsFromBits(getTypeAlign(T)); 1767} 1768CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1769 return toCharUnitsFromBits(getTypeAlign(T)); 1770} 1771 1772/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1773/// type for the current target in bits. This can be different than the ABI 1774/// alignment in cases where it is beneficial for performance to overalign 1775/// a data type. 1776unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1777 TypeInfo TI = getTypeInfo(T); 1778 unsigned ABIAlign = TI.Align; 1779 1780 if (Target->getTriple().getArch() == llvm::Triple::xcore) 1781 return ABIAlign; // Never overalign on XCore. 1782 1783 // Double and long long should be naturally aligned if possible. 1784 T = T->getBaseElementTypeUnsafe(); 1785 if (const ComplexType *CT = T->getAs<ComplexType>()) 1786 T = CT->getElementType().getTypePtr(); 1787 if (T->isSpecificBuiltinType(BuiltinType::Double) || 1788 T->isSpecificBuiltinType(BuiltinType::LongLong) || 1789 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 1790 // Don't increase the alignment if an alignment attribute was specified on a 1791 // typedef declaration. 1792 if (!TI.AlignIsRequired) 1793 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 1794 1795 return ABIAlign; 1796} 1797 1798/// getAlignOfGlobalVar - Return the alignment in bits that should be given 1799/// to a global variable of the specified type. 1800unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 1801 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign()); 1802} 1803 1804/// getAlignOfGlobalVarInChars - Return the alignment in characters that 1805/// should be given to a global variable of the specified type. 1806CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 1807 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 1808} 1809 1810/// DeepCollectObjCIvars - 1811/// This routine first collects all declared, but not synthesized, ivars in 1812/// super class and then collects all ivars, including those synthesized for 1813/// current class. This routine is used for implementation of current class 1814/// when all ivars, declared and synthesized are known. 1815/// 1816void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 1817 bool leafClass, 1818 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 1819 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 1820 DeepCollectObjCIvars(SuperClass, false, Ivars); 1821 if (!leafClass) { 1822 for (const auto *I : OI->ivars()) 1823 Ivars.push_back(I); 1824 } else { 1825 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 1826 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 1827 Iv= Iv->getNextIvar()) 1828 Ivars.push_back(Iv); 1829 } 1830} 1831 1832/// CollectInheritedProtocols - Collect all protocols in current class and 1833/// those inherited by it. 1834void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 1835 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 1836 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1837 // We can use protocol_iterator here instead of 1838 // all_referenced_protocol_iterator since we are walking all categories. 1839 for (auto *Proto : OI->all_referenced_protocols()) { 1840 Protocols.insert(Proto->getCanonicalDecl()); 1841 for (auto *P : Proto->protocols()) { 1842 Protocols.insert(P->getCanonicalDecl()); 1843 CollectInheritedProtocols(P, Protocols); 1844 } 1845 } 1846 1847 // Categories of this Interface. 1848 for (const auto *Cat : OI->visible_categories()) 1849 CollectInheritedProtocols(Cat, Protocols); 1850 1851 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 1852 while (SD) { 1853 CollectInheritedProtocols(SD, Protocols); 1854 SD = SD->getSuperClass(); 1855 } 1856 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1857 for (auto *Proto : OC->protocols()) { 1858 Protocols.insert(Proto->getCanonicalDecl()); 1859 for (const auto *P : Proto->protocols()) 1860 CollectInheritedProtocols(P, Protocols); 1861 } 1862 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1863 for (auto *Proto : OP->protocols()) { 1864 Protocols.insert(Proto->getCanonicalDecl()); 1865 for (const auto *P : Proto->protocols()) 1866 CollectInheritedProtocols(P, Protocols); 1867 } 1868 } 1869} 1870 1871unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 1872 unsigned count = 0; 1873 // Count ivars declared in class extension. 1874 for (const auto *Ext : OI->known_extensions()) 1875 count += Ext->ivar_size(); 1876 1877 // Count ivar defined in this class's implementation. This 1878 // includes synthesized ivars. 1879 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 1880 count += ImplDecl->ivar_size(); 1881 1882 return count; 1883} 1884 1885bool ASTContext::isSentinelNullExpr(const Expr *E) { 1886 if (!E) 1887 return false; 1888 1889 // nullptr_t is always treated as null. 1890 if (E->getType()->isNullPtrType()) return true; 1891 1892 if (E->getType()->isAnyPointerType() && 1893 E->IgnoreParenCasts()->isNullPointerConstant(*this, 1894 Expr::NPC_ValueDependentIsNull)) 1895 return true; 1896 1897 // Unfortunately, __null has type 'int'. 1898 if (isa<GNUNullExpr>(E)) return true; 1899 1900 return false; 1901} 1902 1903/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 1904ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 1905 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1906 I = ObjCImpls.find(D); 1907 if (I != ObjCImpls.end()) 1908 return cast<ObjCImplementationDecl>(I->second); 1909 return nullptr; 1910} 1911/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 1912ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 1913 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1914 I = ObjCImpls.find(D); 1915 if (I != ObjCImpls.end()) 1916 return cast<ObjCCategoryImplDecl>(I->second); 1917 return nullptr; 1918} 1919 1920/// \brief Set the implementation of ObjCInterfaceDecl. 1921void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1922 ObjCImplementationDecl *ImplD) { 1923 assert(IFaceD && ImplD && "Passed null params"); 1924 ObjCImpls[IFaceD] = ImplD; 1925} 1926/// \brief Set the implementation of ObjCCategoryDecl. 1927void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1928 ObjCCategoryImplDecl *ImplD) { 1929 assert(CatD && ImplD && "Passed null params"); 1930 ObjCImpls[CatD] = ImplD; 1931} 1932 1933const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 1934 const NamedDecl *ND) const { 1935 if (const ObjCInterfaceDecl *ID = 1936 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 1937 return ID; 1938 if (const ObjCCategoryDecl *CD = 1939 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 1940 return CD->getClassInterface(); 1941 if (const ObjCImplDecl *IMD = 1942 dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 1943 return IMD->getClassInterface(); 1944 1945 return nullptr; 1946} 1947 1948/// \brief Get the copy initialization expression of VarDecl,or NULL if 1949/// none exists. 1950Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1951 assert(VD && "Passed null params"); 1952 assert(VD->hasAttr<BlocksAttr>() && 1953 "getBlockVarCopyInits - not __block var"); 1954 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1955 I = BlockVarCopyInits.find(VD); 1956 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr; 1957} 1958 1959/// \brief Set the copy inialization expression of a block var decl. 1960void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1961 assert(VD && Init && "Passed null params"); 1962 assert(VD->hasAttr<BlocksAttr>() && 1963 "setBlockVarCopyInits - not __block var"); 1964 BlockVarCopyInits[VD] = Init; 1965} 1966 1967TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1968 unsigned DataSize) const { 1969 if (!DataSize) 1970 DataSize = TypeLoc::getFullDataSizeForType(T); 1971 else 1972 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1973 "incorrect data size provided to CreateTypeSourceInfo!"); 1974 1975 TypeSourceInfo *TInfo = 1976 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1977 new (TInfo) TypeSourceInfo(T); 1978 return TInfo; 1979} 1980 1981TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1982 SourceLocation L) const { 1983 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1984 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 1985 return DI; 1986} 1987 1988const ASTRecordLayout & 1989ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 1990 return getObjCLayout(D, nullptr); 1991} 1992 1993const ASTRecordLayout & 1994ASTContext::getASTObjCImplementationLayout( 1995 const ObjCImplementationDecl *D) const { 1996 return getObjCLayout(D->getClassInterface(), D); 1997} 1998 1999//===----------------------------------------------------------------------===// 2000// Type creation/memoization methods 2001//===----------------------------------------------------------------------===// 2002 2003QualType 2004ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2005 unsigned fastQuals = quals.getFastQualifiers(); 2006 quals.removeFastQualifiers(); 2007 2008 // Check if we've already instantiated this type. 2009 llvm::FoldingSetNodeID ID; 2010 ExtQuals::Profile(ID, baseType, quals); 2011 void *insertPos = nullptr; 2012 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2013 assert(eq->getQualifiers() == quals); 2014 return QualType(eq, fastQuals); 2015 } 2016 2017 // If the base type is not canonical, make the appropriate canonical type. 2018 QualType canon; 2019 if (!baseType->isCanonicalUnqualified()) { 2020 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2021 canonSplit.Quals.addConsistentQualifiers(quals); 2022 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2023 2024 // Re-find the insert position. 2025 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2026 } 2027 2028 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2029 ExtQualNodes.InsertNode(eq, insertPos); 2030 return QualType(eq, fastQuals); 2031} 2032 2033QualType 2034ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 2035 QualType CanT = getCanonicalType(T); 2036 if (CanT.getAddressSpace() == AddressSpace) 2037 return T; 2038 2039 // If we are composing extended qualifiers together, merge together 2040 // into one ExtQuals node. 2041 QualifierCollector Quals; 2042 const Type *TypeNode = Quals.strip(T); 2043 2044 // If this type already has an address space specified, it cannot get 2045 // another one. 2046 assert(!Quals.hasAddressSpace() && 2047 "Type cannot be in multiple addr spaces!"); 2048 Quals.addAddressSpace(AddressSpace); 2049 2050 return getExtQualType(TypeNode, Quals); 2051} 2052 2053QualType ASTContext::getObjCGCQualType(QualType T, 2054 Qualifiers::GC GCAttr) const { 2055 QualType CanT = getCanonicalType(T); 2056 if (CanT.getObjCGCAttr() == GCAttr) 2057 return T; 2058 2059 if (const PointerType *ptr = T->getAs<PointerType>()) { 2060 QualType Pointee = ptr->getPointeeType(); 2061 if (Pointee->isAnyPointerType()) { 2062 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2063 return getPointerType(ResultType); 2064 } 2065 } 2066 2067 // If we are composing extended qualifiers together, merge together 2068 // into one ExtQuals node. 2069 QualifierCollector Quals; 2070 const Type *TypeNode = Quals.strip(T); 2071 2072 // If this type already has an ObjCGC specified, it cannot get 2073 // another one. 2074 assert(!Quals.hasObjCGCAttr() && 2075 "Type cannot have multiple ObjCGCs!"); 2076 Quals.addObjCGCAttr(GCAttr); 2077 2078 return getExtQualType(TypeNode, Quals); 2079} 2080 2081const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2082 FunctionType::ExtInfo Info) { 2083 if (T->getExtInfo() == Info) 2084 return T; 2085 2086 QualType Result; 2087 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2088 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 2089 } else { 2090 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 2091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2092 EPI.ExtInfo = Info; 2093 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 2094 } 2095 2096 return cast<FunctionType>(Result.getTypePtr()); 2097} 2098 2099void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 2100 QualType ResultType) { 2101 FD = FD->getMostRecentDecl(); 2102 while (true) { 2103 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 2104 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2105 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 2106 if (FunctionDecl *Next = FD->getPreviousDecl()) 2107 FD = Next; 2108 else 2109 break; 2110 } 2111 if (ASTMutationListener *L = getASTMutationListener()) 2112 L->DeducedReturnType(FD, ResultType); 2113} 2114 2115/// Get a function type and produce the equivalent function type with the 2116/// specified exception specification. Type sugar that can be present on a 2117/// declaration of a function with an exception specification is permitted 2118/// and preserved. Other type sugar (for instance, typedefs) is not. 2119static QualType getFunctionTypeWithExceptionSpec( 2120 ASTContext &Context, QualType Orig, 2121 const FunctionProtoType::ExceptionSpecInfo &ESI) { 2122 // Might have some parens. 2123 if (auto *PT = dyn_cast<ParenType>(Orig)) 2124 return Context.getParenType( 2125 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI)); 2126 2127 // Might have a calling-convention attribute. 2128 if (auto *AT = dyn_cast<AttributedType>(Orig)) 2129 return Context.getAttributedType( 2130 AT->getAttrKind(), 2131 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI), 2132 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(), 2133 ESI)); 2134 2135 // Anything else must be a function type. Rebuild it with the new exception 2136 // specification. 2137 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig); 2138 return Context.getFunctionType( 2139 Proto->getReturnType(), Proto->getParamTypes(), 2140 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 2141} 2142 2143void ASTContext::adjustExceptionSpec( 2144 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 2145 bool AsWritten) { 2146 // Update the type. 2147 QualType Updated = 2148 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI); 2149 FD->setType(Updated); 2150 2151 if (!AsWritten) 2152 return; 2153 2154 // Update the type in the type source information too. 2155 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 2156 // If the type and the type-as-written differ, we may need to update 2157 // the type-as-written too. 2158 if (TSInfo->getType() != FD->getType()) 2159 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI); 2160 2161 // FIXME: When we get proper type location information for exceptions, 2162 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 2163 // up the TypeSourceInfo; 2164 assert(TypeLoc::getFullDataSizeForType(Updated) == 2165 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 2166 "TypeLoc size mismatch from updating exception specification"); 2167 TSInfo->overrideType(Updated); 2168 } 2169} 2170 2171/// getComplexType - Return the uniqued reference to the type for a complex 2172/// number with the specified element type. 2173QualType ASTContext::getComplexType(QualType T) const { 2174 // Unique pointers, to guarantee there is only one pointer of a particular 2175 // structure. 2176 llvm::FoldingSetNodeID ID; 2177 ComplexType::Profile(ID, T); 2178 2179 void *InsertPos = nullptr; 2180 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 2181 return QualType(CT, 0); 2182 2183 // If the pointee type isn't canonical, this won't be a canonical type either, 2184 // so fill in the canonical type field. 2185 QualType Canonical; 2186 if (!T.isCanonical()) { 2187 Canonical = getComplexType(getCanonicalType(T)); 2188 2189 // Get the new insert position for the node we care about. 2190 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 2191 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2192 } 2193 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 2194 Types.push_back(New); 2195 ComplexTypes.InsertNode(New, InsertPos); 2196 return QualType(New, 0); 2197} 2198 2199/// getPointerType - Return the uniqued reference to the type for a pointer to 2200/// the specified type. 2201QualType ASTContext::getPointerType(QualType T) const { 2202 // Unique pointers, to guarantee there is only one pointer of a particular 2203 // structure. 2204 llvm::FoldingSetNodeID ID; 2205 PointerType::Profile(ID, T); 2206 2207 void *InsertPos = nullptr; 2208 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2209 return QualType(PT, 0); 2210 2211 // If the pointee type isn't canonical, this won't be a canonical type either, 2212 // so fill in the canonical type field. 2213 QualType Canonical; 2214 if (!T.isCanonical()) { 2215 Canonical = getPointerType(getCanonicalType(T)); 2216 2217 // Get the new insert position for the node we care about. 2218 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2219 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2220 } 2221 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 2222 Types.push_back(New); 2223 PointerTypes.InsertNode(New, InsertPos); 2224 return QualType(New, 0); 2225} 2226 2227QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 2228 llvm::FoldingSetNodeID ID; 2229 AdjustedType::Profile(ID, Orig, New); 2230 void *InsertPos = nullptr; 2231 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2232 if (AT) 2233 return QualType(AT, 0); 2234 2235 QualType Canonical = getCanonicalType(New); 2236 2237 // Get the new insert position for the node we care about. 2238 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2239 assert(!AT && "Shouldn't be in the map!"); 2240 2241 AT = new (*this, TypeAlignment) 2242 AdjustedType(Type::Adjusted, Orig, New, Canonical); 2243 Types.push_back(AT); 2244 AdjustedTypes.InsertNode(AT, InsertPos); 2245 return QualType(AT, 0); 2246} 2247 2248QualType ASTContext::getDecayedType(QualType T) const { 2249 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 2250 2251 QualType Decayed; 2252 2253 // C99 6.7.5.3p7: 2254 // A declaration of a parameter as "array of type" shall be 2255 // adjusted to "qualified pointer to type", where the type 2256 // qualifiers (if any) are those specified within the [ and ] of 2257 // the array type derivation. 2258 if (T->isArrayType()) 2259 Decayed = getArrayDecayedType(T); 2260 2261 // C99 6.7.5.3p8: 2262 // A declaration of a parameter as "function returning type" 2263 // shall be adjusted to "pointer to function returning type", as 2264 // in 6.3.2.1. 2265 if (T->isFunctionType()) 2266 Decayed = getPointerType(T); 2267 2268 llvm::FoldingSetNodeID ID; 2269 AdjustedType::Profile(ID, T, Decayed); 2270 void *InsertPos = nullptr; 2271 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2272 if (AT) 2273 return QualType(AT, 0); 2274 2275 QualType Canonical = getCanonicalType(Decayed); 2276 2277 // Get the new insert position for the node we care about. 2278 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2279 assert(!AT && "Shouldn't be in the map!"); 2280 2281 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 2282 Types.push_back(AT); 2283 AdjustedTypes.InsertNode(AT, InsertPos); 2284 return QualType(AT, 0); 2285} 2286 2287/// getBlockPointerType - Return the uniqued reference to the type for 2288/// a pointer to the specified block. 2289QualType ASTContext::getBlockPointerType(QualType T) const { 2290 assert(T->isFunctionType() && "block of function types only"); 2291 // Unique pointers, to guarantee there is only one block of a particular 2292 // structure. 2293 llvm::FoldingSetNodeID ID; 2294 BlockPointerType::Profile(ID, T); 2295 2296 void *InsertPos = nullptr; 2297 if (BlockPointerType *PT = 2298 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2299 return QualType(PT, 0); 2300 2301 // If the block pointee type isn't canonical, this won't be a canonical 2302 // type either so fill in the canonical type field. 2303 QualType Canonical; 2304 if (!T.isCanonical()) { 2305 Canonical = getBlockPointerType(getCanonicalType(T)); 2306 2307 // Get the new insert position for the node we care about. 2308 BlockPointerType *NewIP = 2309 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2310 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2311 } 2312 BlockPointerType *New 2313 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 2314 Types.push_back(New); 2315 BlockPointerTypes.InsertNode(New, InsertPos); 2316 return QualType(New, 0); 2317} 2318 2319/// getLValueReferenceType - Return the uniqued reference to the type for an 2320/// lvalue reference to the specified type. 2321QualType 2322ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 2323 assert(getCanonicalType(T) != OverloadTy && 2324 "Unresolved overloaded function type"); 2325 2326 // Unique pointers, to guarantee there is only one pointer of a particular 2327 // structure. 2328 llvm::FoldingSetNodeID ID; 2329 ReferenceType::Profile(ID, T, SpelledAsLValue); 2330 2331 void *InsertPos = nullptr; 2332 if (LValueReferenceType *RT = 2333 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2334 return QualType(RT, 0); 2335 2336 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2337 2338 // If the referencee type isn't canonical, this won't be a canonical type 2339 // either, so fill in the canonical type field. 2340 QualType Canonical; 2341 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 2342 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2343 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 2344 2345 // Get the new insert position for the node we care about. 2346 LValueReferenceType *NewIP = 2347 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2348 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2349 } 2350 2351 LValueReferenceType *New 2352 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 2353 SpelledAsLValue); 2354 Types.push_back(New); 2355 LValueReferenceTypes.InsertNode(New, InsertPos); 2356 2357 return QualType(New, 0); 2358} 2359 2360/// getRValueReferenceType - Return the uniqued reference to the type for an 2361/// rvalue reference to the specified type. 2362QualType ASTContext::getRValueReferenceType(QualType T) const { 2363 // Unique pointers, to guarantee there is only one pointer of a particular 2364 // structure. 2365 llvm::FoldingSetNodeID ID; 2366 ReferenceType::Profile(ID, T, false); 2367 2368 void *InsertPos = nullptr; 2369 if (RValueReferenceType *RT = 2370 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2371 return QualType(RT, 0); 2372 2373 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2374 2375 // If the referencee type isn't canonical, this won't be a canonical type 2376 // either, so fill in the canonical type field. 2377 QualType Canonical; 2378 if (InnerRef || !T.isCanonical()) { 2379 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2380 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 2381 2382 // Get the new insert position for the node we care about. 2383 RValueReferenceType *NewIP = 2384 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2385 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2386 } 2387 2388 RValueReferenceType *New 2389 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 2390 Types.push_back(New); 2391 RValueReferenceTypes.InsertNode(New, InsertPos); 2392 return QualType(New, 0); 2393} 2394 2395/// getMemberPointerType - Return the uniqued reference to the type for a 2396/// member pointer to the specified type, in the specified class. 2397QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 2398 // Unique pointers, to guarantee there is only one pointer of a particular 2399 // structure. 2400 llvm::FoldingSetNodeID ID; 2401 MemberPointerType::Profile(ID, T, Cls); 2402 2403 void *InsertPos = nullptr; 2404 if (MemberPointerType *PT = 2405 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2406 return QualType(PT, 0); 2407 2408 // If the pointee or class type isn't canonical, this won't be a canonical 2409 // type either, so fill in the canonical type field. 2410 QualType Canonical; 2411 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 2412 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 2413 2414 // Get the new insert position for the node we care about. 2415 MemberPointerType *NewIP = 2416 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2417 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2418 } 2419 MemberPointerType *New 2420 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 2421 Types.push_back(New); 2422 MemberPointerTypes.InsertNode(New, InsertPos); 2423 return QualType(New, 0); 2424} 2425 2426/// getConstantArrayType - Return the unique reference to the type for an 2427/// array of the specified element type. 2428QualType ASTContext::getConstantArrayType(QualType EltTy, 2429 const llvm::APInt &ArySizeIn, 2430 ArrayType::ArraySizeModifier ASM, 2431 unsigned IndexTypeQuals) const { 2432 assert((EltTy->isDependentType() || 2433 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 2434 "Constant array of VLAs is illegal!"); 2435 2436 // Convert the array size into a canonical width matching the pointer size for 2437 // the target. 2438 llvm::APInt ArySize(ArySizeIn); 2439 ArySize = 2440 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 2441 2442 llvm::FoldingSetNodeID ID; 2443 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 2444 2445 void *InsertPos = nullptr; 2446 if (ConstantArrayType *ATP = 2447 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 2448 return QualType(ATP, 0); 2449 2450 // If the element type isn't canonical or has qualifiers, this won't 2451 // be a canonical type either, so fill in the canonical type field. 2452 QualType Canon; 2453 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2454 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2455 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 2456 ASM, IndexTypeQuals); 2457 Canon = getQualifiedType(Canon, canonSplit.Quals); 2458 2459 // Get the new insert position for the node we care about. 2460 ConstantArrayType *NewIP = 2461 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 2462 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2463 } 2464 2465 ConstantArrayType *New = new(*this,TypeAlignment) 2466 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 2467 ConstantArrayTypes.InsertNode(New, InsertPos); 2468 Types.push_back(New); 2469 return QualType(New, 0); 2470} 2471 2472/// getVariableArrayDecayedType - Turns the given type, which may be 2473/// variably-modified, into the corresponding type with all the known 2474/// sizes replaced with [*]. 2475QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 2476 // Vastly most common case. 2477 if (!type->isVariablyModifiedType()) return type; 2478 2479 QualType result; 2480 2481 SplitQualType split = type.getSplitDesugaredType(); 2482 const Type *ty = split.Ty; 2483 switch (ty->getTypeClass()) { 2484#define TYPE(Class, Base) 2485#define ABSTRACT_TYPE(Class, Base) 2486#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2487#include "clang/AST/TypeNodes.def" 2488 llvm_unreachable("didn't desugar past all non-canonical types?"); 2489 2490 // These types should never be variably-modified. 2491 case Type::Builtin: 2492 case Type::Complex: 2493 case Type::Vector: 2494 case Type::ExtVector: 2495 case Type::DependentSizedExtVector: 2496 case Type::ObjCObject: 2497 case Type::ObjCInterface: 2498 case Type::ObjCObjectPointer: 2499 case Type::Record: 2500 case Type::Enum: 2501 case Type::UnresolvedUsing: 2502 case Type::TypeOfExpr: 2503 case Type::TypeOf: 2504 case Type::Decltype: 2505 case Type::UnaryTransform: 2506 case Type::DependentName: 2507 case Type::InjectedClassName: 2508 case Type::TemplateSpecialization: 2509 case Type::DependentTemplateSpecialization: 2510 case Type::TemplateTypeParm: 2511 case Type::SubstTemplateTypeParmPack: 2512 case Type::Auto: 2513 case Type::PackExpansion: 2514 llvm_unreachable("type should never be variably-modified"); 2515 2516 // These types can be variably-modified but should never need to 2517 // further decay. 2518 case Type::FunctionNoProto: 2519 case Type::FunctionProto: 2520 case Type::BlockPointer: 2521 case Type::MemberPointer: 2522 return type; 2523 2524 // These types can be variably-modified. All these modifications 2525 // preserve structure except as noted by comments. 2526 // TODO: if we ever care about optimizing VLAs, there are no-op 2527 // optimizations available here. 2528 case Type::Pointer: 2529 result = getPointerType(getVariableArrayDecayedType( 2530 cast<PointerType>(ty)->getPointeeType())); 2531 break; 2532 2533 case Type::LValueReference: { 2534 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 2535 result = getLValueReferenceType( 2536 getVariableArrayDecayedType(lv->getPointeeType()), 2537 lv->isSpelledAsLValue()); 2538 break; 2539 } 2540 2541 case Type::RValueReference: { 2542 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 2543 result = getRValueReferenceType( 2544 getVariableArrayDecayedType(lv->getPointeeType())); 2545 break; 2546 } 2547 2548 case Type::Atomic: { 2549 const AtomicType *at = cast<AtomicType>(ty); 2550 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 2551 break; 2552 } 2553 2554 case Type::ConstantArray: { 2555 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 2556 result = getConstantArrayType( 2557 getVariableArrayDecayedType(cat->getElementType()), 2558 cat->getSize(), 2559 cat->getSizeModifier(), 2560 cat->getIndexTypeCVRQualifiers()); 2561 break; 2562 } 2563 2564 case Type::DependentSizedArray: { 2565 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 2566 result = getDependentSizedArrayType( 2567 getVariableArrayDecayedType(dat->getElementType()), 2568 dat->getSizeExpr(), 2569 dat->getSizeModifier(), 2570 dat->getIndexTypeCVRQualifiers(), 2571 dat->getBracketsRange()); 2572 break; 2573 } 2574 2575 // Turn incomplete types into [*] types. 2576 case Type::IncompleteArray: { 2577 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 2578 result = getVariableArrayType( 2579 getVariableArrayDecayedType(iat->getElementType()), 2580 /*size*/ nullptr, 2581 ArrayType::Normal, 2582 iat->getIndexTypeCVRQualifiers(), 2583 SourceRange()); 2584 break; 2585 } 2586 2587 // Turn VLA types into [*] types. 2588 case Type::VariableArray: { 2589 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2590 result = getVariableArrayType( 2591 getVariableArrayDecayedType(vat->getElementType()), 2592 /*size*/ nullptr, 2593 ArrayType::Star, 2594 vat->getIndexTypeCVRQualifiers(), 2595 vat->getBracketsRange()); 2596 break; 2597 } 2598 } 2599 2600 // Apply the top-level qualifiers from the original. 2601 return getQualifiedType(result, split.Quals); 2602} 2603 2604/// getVariableArrayType - Returns a non-unique reference to the type for a 2605/// variable array of the specified element type. 2606QualType ASTContext::getVariableArrayType(QualType EltTy, 2607 Expr *NumElts, 2608 ArrayType::ArraySizeModifier ASM, 2609 unsigned IndexTypeQuals, 2610 SourceRange Brackets) const { 2611 // Since we don't unique expressions, it isn't possible to unique VLA's 2612 // that have an expression provided for their size. 2613 QualType Canon; 2614 2615 // Be sure to pull qualifiers off the element type. 2616 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2617 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2618 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 2619 IndexTypeQuals, Brackets); 2620 Canon = getQualifiedType(Canon, canonSplit.Quals); 2621 } 2622 2623 VariableArrayType *New = new(*this, TypeAlignment) 2624 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 2625 2626 VariableArrayTypes.push_back(New); 2627 Types.push_back(New); 2628 return QualType(New, 0); 2629} 2630 2631/// getDependentSizedArrayType - Returns a non-unique reference to 2632/// the type for a dependently-sized array of the specified element 2633/// type. 2634QualType ASTContext::getDependentSizedArrayType(QualType elementType, 2635 Expr *numElements, 2636 ArrayType::ArraySizeModifier ASM, 2637 unsigned elementTypeQuals, 2638 SourceRange brackets) const { 2639 assert((!numElements || numElements->isTypeDependent() || 2640 numElements->isValueDependent()) && 2641 "Size must be type- or value-dependent!"); 2642 2643 // Dependently-sized array types that do not have a specified number 2644 // of elements will have their sizes deduced from a dependent 2645 // initializer. We do no canonicalization here at all, which is okay 2646 // because they can't be used in most locations. 2647 if (!numElements) { 2648 DependentSizedArrayType *newType 2649 = new (*this, TypeAlignment) 2650 DependentSizedArrayType(*this, elementType, QualType(), 2651 numElements, ASM, elementTypeQuals, 2652 brackets); 2653 Types.push_back(newType); 2654 return QualType(newType, 0); 2655 } 2656 2657 // Otherwise, we actually build a new type every time, but we 2658 // also build a canonical type. 2659 2660 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2661 2662 void *insertPos = nullptr; 2663 llvm::FoldingSetNodeID ID; 2664 DependentSizedArrayType::Profile(ID, *this, 2665 QualType(canonElementType.Ty, 0), 2666 ASM, elementTypeQuals, numElements); 2667 2668 // Look for an existing type with these properties. 2669 DependentSizedArrayType *canonTy = 2670 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2671 2672 // If we don't have one, build one. 2673 if (!canonTy) { 2674 canonTy = new (*this, TypeAlignment) 2675 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2676 QualType(), numElements, ASM, elementTypeQuals, 2677 brackets); 2678 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2679 Types.push_back(canonTy); 2680 } 2681 2682 // Apply qualifiers from the element type to the array. 2683 QualType canon = getQualifiedType(QualType(canonTy,0), 2684 canonElementType.Quals); 2685 2686 // If we didn't need extra canonicalization for the element type, 2687 // then just use that as our result. 2688 if (QualType(canonElementType.Ty, 0) == elementType) 2689 return canon; 2690 2691 // Otherwise, we need to build a type which follows the spelling 2692 // of the element type. 2693 DependentSizedArrayType *sugaredType 2694 = new (*this, TypeAlignment) 2695 DependentSizedArrayType(*this, elementType, canon, numElements, 2696 ASM, elementTypeQuals, brackets); 2697 Types.push_back(sugaredType); 2698 return QualType(sugaredType, 0); 2699} 2700 2701QualType ASTContext::getIncompleteArrayType(QualType elementType, 2702 ArrayType::ArraySizeModifier ASM, 2703 unsigned elementTypeQuals) const { 2704 llvm::FoldingSetNodeID ID; 2705 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2706 2707 void *insertPos = nullptr; 2708 if (IncompleteArrayType *iat = 2709 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2710 return QualType(iat, 0); 2711 2712 // If the element type isn't canonical, this won't be a canonical type 2713 // either, so fill in the canonical type field. We also have to pull 2714 // qualifiers off the element type. 2715 QualType canon; 2716 2717 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2718 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2719 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2720 ASM, elementTypeQuals); 2721 canon = getQualifiedType(canon, canonSplit.Quals); 2722 2723 // Get the new insert position for the node we care about. 2724 IncompleteArrayType *existing = 2725 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2726 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2727 } 2728 2729 IncompleteArrayType *newType = new (*this, TypeAlignment) 2730 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2731 2732 IncompleteArrayTypes.InsertNode(newType, insertPos); 2733 Types.push_back(newType); 2734 return QualType(newType, 0); 2735} 2736 2737/// getVectorType - Return the unique reference to a vector type of 2738/// the specified element type and size. VectorType must be a built-in type. 2739QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2740 VectorType::VectorKind VecKind) const { 2741 assert(vecType->isBuiltinType()); 2742 2743 // Check if we've already instantiated a vector of this type. 2744 llvm::FoldingSetNodeID ID; 2745 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2746 2747 void *InsertPos = nullptr; 2748 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2749 return QualType(VTP, 0); 2750 2751 // If the element type isn't canonical, this won't be a canonical type either, 2752 // so fill in the canonical type field. 2753 QualType Canonical; 2754 if (!vecType.isCanonical()) { 2755 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 2756 2757 // Get the new insert position for the node we care about. 2758 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2759 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2760 } 2761 VectorType *New = new (*this, TypeAlignment) 2762 VectorType(vecType, NumElts, Canonical, VecKind); 2763 VectorTypes.InsertNode(New, InsertPos); 2764 Types.push_back(New); 2765 return QualType(New, 0); 2766} 2767 2768/// getExtVectorType - Return the unique reference to an extended vector type of 2769/// the specified element type and size. VectorType must be a built-in type. 2770QualType 2771ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 2772 assert(vecType->isBuiltinType() || vecType->isDependentType()); 2773 2774 // Check if we've already instantiated a vector of this type. 2775 llvm::FoldingSetNodeID ID; 2776 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 2777 VectorType::GenericVector); 2778 void *InsertPos = nullptr; 2779 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2780 return QualType(VTP, 0); 2781 2782 // If the element type isn't canonical, this won't be a canonical type either, 2783 // so fill in the canonical type field. 2784 QualType Canonical; 2785 if (!vecType.isCanonical()) { 2786 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 2787 2788 // Get the new insert position for the node we care about. 2789 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2790 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2791 } 2792 ExtVectorType *New = new (*this, TypeAlignment) 2793 ExtVectorType(vecType, NumElts, Canonical); 2794 VectorTypes.InsertNode(New, InsertPos); 2795 Types.push_back(New); 2796 return QualType(New, 0); 2797} 2798 2799QualType 2800ASTContext::getDependentSizedExtVectorType(QualType vecType, 2801 Expr *SizeExpr, 2802 SourceLocation AttrLoc) const { 2803 llvm::FoldingSetNodeID ID; 2804 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 2805 SizeExpr); 2806 2807 void *InsertPos = nullptr; 2808 DependentSizedExtVectorType *Canon 2809 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2810 DependentSizedExtVectorType *New; 2811 if (Canon) { 2812 // We already have a canonical version of this array type; use it as 2813 // the canonical type for a newly-built type. 2814 New = new (*this, TypeAlignment) 2815 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 2816 SizeExpr, AttrLoc); 2817 } else { 2818 QualType CanonVecTy = getCanonicalType(vecType); 2819 if (CanonVecTy == vecType) { 2820 New = new (*this, TypeAlignment) 2821 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 2822 AttrLoc); 2823 2824 DependentSizedExtVectorType *CanonCheck 2825 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2826 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 2827 (void)CanonCheck; 2828 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 2829 } else { 2830 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 2831 SourceLocation()); 2832 New = new (*this, TypeAlignment) 2833 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 2834 } 2835 } 2836 2837 Types.push_back(New); 2838 return QualType(New, 0); 2839} 2840 2841/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 2842/// 2843QualType 2844ASTContext::getFunctionNoProtoType(QualType ResultTy, 2845 const FunctionType::ExtInfo &Info) const { 2846 const CallingConv CallConv = Info.getCC(); 2847 2848 // Unique functions, to guarantee there is only one function of a particular 2849 // structure. 2850 llvm::FoldingSetNodeID ID; 2851 FunctionNoProtoType::Profile(ID, ResultTy, Info); 2852 2853 void *InsertPos = nullptr; 2854 if (FunctionNoProtoType *FT = 2855 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2856 return QualType(FT, 0); 2857 2858 QualType Canonical; 2859 if (!ResultTy.isCanonical()) { 2860 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info); 2861 2862 // Get the new insert position for the node we care about. 2863 FunctionNoProtoType *NewIP = 2864 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2865 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2866 } 2867 2868 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv); 2869 FunctionNoProtoType *New = new (*this, TypeAlignment) 2870 FunctionNoProtoType(ResultTy, Canonical, newInfo); 2871 Types.push_back(New); 2872 FunctionNoProtoTypes.InsertNode(New, InsertPos); 2873 return QualType(New, 0); 2874} 2875 2876/// \brief Determine whether \p T is canonical as the result type of a function. 2877static bool isCanonicalResultType(QualType T) { 2878 return T.isCanonical() && 2879 (T.getObjCLifetime() == Qualifiers::OCL_None || 2880 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 2881} 2882 2883QualType 2884ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray, 2885 const FunctionProtoType::ExtProtoInfo &EPI) const { 2886 size_t NumArgs = ArgArray.size(); 2887 2888 // Unique functions, to guarantee there is only one function of a particular 2889 // structure. 2890 llvm::FoldingSetNodeID ID; 2891 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 2892 *this); 2893 2894 void *InsertPos = nullptr; 2895 if (FunctionProtoType *FTP = 2896 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2897 return QualType(FTP, 0); 2898 2899 // Determine whether the type being created is already canonical or not. 2900 bool isCanonical = 2901 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) && 2902 !EPI.HasTrailingReturn; 2903 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 2904 if (!ArgArray[i].isCanonicalAsParam()) 2905 isCanonical = false; 2906 2907 // If this type isn't canonical, get the canonical version of it. 2908 // The exception spec is not part of the canonical type. 2909 QualType Canonical; 2910 if (!isCanonical) { 2911 SmallVector<QualType, 16> CanonicalArgs; 2912 CanonicalArgs.reserve(NumArgs); 2913 for (unsigned i = 0; i != NumArgs; ++i) 2914 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 2915 2916 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 2917 CanonicalEPI.HasTrailingReturn = false; 2918 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 2919 2920 // Result types do not have ARC lifetime qualifiers. 2921 QualType CanResultTy = getCanonicalType(ResultTy); 2922 if (ResultTy.getQualifiers().hasObjCLifetime()) { 2923 Qualifiers Qs = CanResultTy.getQualifiers(); 2924 Qs.removeObjCLifetime(); 2925 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs); 2926 } 2927 2928 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI); 2929 2930 // Get the new insert position for the node we care about. 2931 FunctionProtoType *NewIP = 2932 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2933 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2934 } 2935 2936 // FunctionProtoType objects are allocated with extra bytes after 2937 // them for three variable size arrays at the end: 2938 // - parameter types 2939 // - exception types 2940 // - consumed-arguments flags 2941 // Instead of the exception types, there could be a noexcept 2942 // expression, or information used to resolve the exception 2943 // specification. 2944 size_t Size = sizeof(FunctionProtoType) + 2945 NumArgs * sizeof(QualType); 2946 if (EPI.ExceptionSpec.Type == EST_Dynamic) { 2947 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType); 2948 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) { 2949 Size += sizeof(Expr*); 2950 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) { 2951 Size += 2 * sizeof(FunctionDecl*); 2952 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) { 2953 Size += sizeof(FunctionDecl*); 2954 } 2955 if (EPI.ConsumedParameters) 2956 Size += NumArgs * sizeof(bool); 2957 2958 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 2959 FunctionProtoType::ExtProtoInfo newEPI = EPI; 2960 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 2961 Types.push_back(FTP); 2962 FunctionProtoTypes.InsertNode(FTP, InsertPos); 2963 return QualType(FTP, 0); 2964} 2965 2966#ifndef NDEBUG 2967static bool NeedsInjectedClassNameType(const RecordDecl *D) { 2968 if (!isa<CXXRecordDecl>(D)) return false; 2969 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 2970 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 2971 return true; 2972 if (RD->getDescribedClassTemplate() && 2973 !isa<ClassTemplateSpecializationDecl>(RD)) 2974 return true; 2975 return false; 2976} 2977#endif 2978 2979/// getInjectedClassNameType - Return the unique reference to the 2980/// injected class name type for the specified templated declaration. 2981QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 2982 QualType TST) const { 2983 assert(NeedsInjectedClassNameType(Decl)); 2984 if (Decl->TypeForDecl) { 2985 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2986 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 2987 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 2988 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2989 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2990 } else { 2991 Type *newType = 2992 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 2993 Decl->TypeForDecl = newType; 2994 Types.push_back(newType); 2995 } 2996 return QualType(Decl->TypeForDecl, 0); 2997} 2998 2999/// getTypeDeclType - Return the unique reference to the type for the 3000/// specified type declaration. 3001QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 3002 assert(Decl && "Passed null for Decl param"); 3003 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 3004 3005 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 3006 return getTypedefType(Typedef); 3007 3008 assert(!isa<TemplateTypeParmDecl>(Decl) && 3009 "Template type parameter types are always available."); 3010 3011 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 3012 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 3013 assert(!NeedsInjectedClassNameType(Record)); 3014 return getRecordType(Record); 3015 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 3016 assert(Enum->isFirstDecl() && "enum has previous declaration"); 3017 return getEnumType(Enum); 3018 } else if (const UnresolvedUsingTypenameDecl *Using = 3019 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 3020 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 3021 Decl->TypeForDecl = newType; 3022 Types.push_back(newType); 3023 } else 3024 llvm_unreachable("TypeDecl without a type?"); 3025 3026 return QualType(Decl->TypeForDecl, 0); 3027} 3028 3029/// getTypedefType - Return the unique reference to the type for the 3030/// specified typedef name decl. 3031QualType 3032ASTContext::getTypedefType(const TypedefNameDecl *Decl, 3033 QualType Canonical) const { 3034 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3035 3036 if (Canonical.isNull()) 3037 Canonical = getCanonicalType(Decl->getUnderlyingType()); 3038 TypedefType *newType = new(*this, TypeAlignment) 3039 TypedefType(Type::Typedef, Decl, Canonical); 3040 Decl->TypeForDecl = newType; 3041 Types.push_back(newType); 3042 return QualType(newType, 0); 3043} 3044 3045QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 3046 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3047 3048 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 3049 if (PrevDecl->TypeForDecl) 3050 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3051 3052 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 3053 Decl->TypeForDecl = newType; 3054 Types.push_back(newType); 3055 return QualType(newType, 0); 3056} 3057 3058QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 3059 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3060 3061 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 3062 if (PrevDecl->TypeForDecl) 3063 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3064 3065 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 3066 Decl->TypeForDecl = newType; 3067 Types.push_back(newType); 3068 return QualType(newType, 0); 3069} 3070 3071QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 3072 QualType modifiedType, 3073 QualType equivalentType) { 3074 llvm::FoldingSetNodeID id; 3075 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 3076 3077 void *insertPos = nullptr; 3078 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 3079 if (type) return QualType(type, 0); 3080 3081 QualType canon = getCanonicalType(equivalentType); 3082 type = new (*this, TypeAlignment) 3083 AttributedType(canon, attrKind, modifiedType, equivalentType); 3084 3085 Types.push_back(type); 3086 AttributedTypes.InsertNode(type, insertPos); 3087 3088 return QualType(type, 0); 3089} 3090 3091 3092/// \brief Retrieve a substitution-result type. 3093QualType 3094ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 3095 QualType Replacement) const { 3096 assert(Replacement.isCanonical() 3097 && "replacement types must always be canonical"); 3098 3099 llvm::FoldingSetNodeID ID; 3100 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 3101 void *InsertPos = nullptr; 3102 SubstTemplateTypeParmType *SubstParm 3103 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3104 3105 if (!SubstParm) { 3106 SubstParm = new (*this, TypeAlignment) 3107 SubstTemplateTypeParmType(Parm, Replacement); 3108 Types.push_back(SubstParm); 3109 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3110 } 3111 3112 return QualType(SubstParm, 0); 3113} 3114 3115/// \brief Retrieve a 3116QualType ASTContext::getSubstTemplateTypeParmPackType( 3117 const TemplateTypeParmType *Parm, 3118 const TemplateArgument &ArgPack) { 3119#ifndef NDEBUG 3120 for (const auto &P : ArgPack.pack_elements()) { 3121 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 3122 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 3123 } 3124#endif 3125 3126 llvm::FoldingSetNodeID ID; 3127 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 3128 void *InsertPos = nullptr; 3129 if (SubstTemplateTypeParmPackType *SubstParm 3130 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 3131 return QualType(SubstParm, 0); 3132 3133 QualType Canon; 3134 if (!Parm->isCanonicalUnqualified()) { 3135 Canon = getCanonicalType(QualType(Parm, 0)); 3136 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 3137 ArgPack); 3138 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 3139 } 3140 3141 SubstTemplateTypeParmPackType *SubstParm 3142 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 3143 ArgPack); 3144 Types.push_back(SubstParm); 3145 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3146 return QualType(SubstParm, 0); 3147} 3148 3149/// \brief Retrieve the template type parameter type for a template 3150/// parameter or parameter pack with the given depth, index, and (optionally) 3151/// name. 3152QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 3153 bool ParameterPack, 3154 TemplateTypeParmDecl *TTPDecl) const { 3155 llvm::FoldingSetNodeID ID; 3156 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 3157 void *InsertPos = nullptr; 3158 TemplateTypeParmType *TypeParm 3159 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3160 3161 if (TypeParm) 3162 return QualType(TypeParm, 0); 3163 3164 if (TTPDecl) { 3165 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 3166 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 3167 3168 TemplateTypeParmType *TypeCheck 3169 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3170 assert(!TypeCheck && "Template type parameter canonical type broken"); 3171 (void)TypeCheck; 3172 } else 3173 TypeParm = new (*this, TypeAlignment) 3174 TemplateTypeParmType(Depth, Index, ParameterPack); 3175 3176 Types.push_back(TypeParm); 3177 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 3178 3179 return QualType(TypeParm, 0); 3180} 3181 3182TypeSourceInfo * 3183ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 3184 SourceLocation NameLoc, 3185 const TemplateArgumentListInfo &Args, 3186 QualType Underlying) const { 3187 assert(!Name.getAsDependentTemplateName() && 3188 "No dependent template names here!"); 3189 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 3190 3191 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 3192 TemplateSpecializationTypeLoc TL = 3193 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 3194 TL.setTemplateKeywordLoc(SourceLocation()); 3195 TL.setTemplateNameLoc(NameLoc); 3196 TL.setLAngleLoc(Args.getLAngleLoc()); 3197 TL.setRAngleLoc(Args.getRAngleLoc()); 3198 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 3199 TL.setArgLocInfo(i, Args[i].getLocInfo()); 3200 return DI; 3201} 3202 3203QualType 3204ASTContext::getTemplateSpecializationType(TemplateName Template, 3205 const TemplateArgumentListInfo &Args, 3206 QualType Underlying) const { 3207 assert(!Template.getAsDependentTemplateName() && 3208 "No dependent template names here!"); 3209 3210 unsigned NumArgs = Args.size(); 3211 3212 SmallVector<TemplateArgument, 4> ArgVec; 3213 ArgVec.reserve(NumArgs); 3214 for (unsigned i = 0; i != NumArgs; ++i) 3215 ArgVec.push_back(Args[i].getArgument()); 3216 3217 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 3218 Underlying); 3219} 3220 3221#ifndef NDEBUG 3222static bool hasAnyPackExpansions(const TemplateArgument *Args, 3223 unsigned NumArgs) { 3224 for (unsigned I = 0; I != NumArgs; ++I) 3225 if (Args[I].isPackExpansion()) 3226 return true; 3227 3228 return true; 3229} 3230#endif 3231 3232QualType 3233ASTContext::getTemplateSpecializationType(TemplateName Template, 3234 const TemplateArgument *Args, 3235 unsigned NumArgs, 3236 QualType Underlying) const { 3237 assert(!Template.getAsDependentTemplateName() && 3238 "No dependent template names here!"); 3239 // Look through qualified template names. 3240 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3241 Template = TemplateName(QTN->getTemplateDecl()); 3242 3243 bool IsTypeAlias = 3244 Template.getAsTemplateDecl() && 3245 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 3246 QualType CanonType; 3247 if (!Underlying.isNull()) 3248 CanonType = getCanonicalType(Underlying); 3249 else { 3250 // We can get here with an alias template when the specialization contains 3251 // a pack expansion that does not match up with a parameter pack. 3252 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) && 3253 "Caller must compute aliased type"); 3254 IsTypeAlias = false; 3255 CanonType = getCanonicalTemplateSpecializationType(Template, Args, 3256 NumArgs); 3257 } 3258 3259 // Allocate the (non-canonical) template specialization type, but don't 3260 // try to unique it: these types typically have location information that 3261 // we don't unique and don't want to lose. 3262 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 3263 sizeof(TemplateArgument) * NumArgs + 3264 (IsTypeAlias? sizeof(QualType) : 0), 3265 TypeAlignment); 3266 TemplateSpecializationType *Spec 3267 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType, 3268 IsTypeAlias ? Underlying : QualType()); 3269 3270 Types.push_back(Spec); 3271 return QualType(Spec, 0); 3272} 3273 3274QualType 3275ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 3276 const TemplateArgument *Args, 3277 unsigned NumArgs) const { 3278 assert(!Template.getAsDependentTemplateName() && 3279 "No dependent template names here!"); 3280 3281 // Look through qualified template names. 3282 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3283 Template = TemplateName(QTN->getTemplateDecl()); 3284 3285 // Build the canonical template specialization type. 3286 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 3287 SmallVector<TemplateArgument, 4> CanonArgs; 3288 CanonArgs.reserve(NumArgs); 3289 for (unsigned I = 0; I != NumArgs; ++I) 3290 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 3291 3292 // Determine whether this canonical template specialization type already 3293 // exists. 3294 llvm::FoldingSetNodeID ID; 3295 TemplateSpecializationType::Profile(ID, CanonTemplate, 3296 CanonArgs.data(), NumArgs, *this); 3297 3298 void *InsertPos = nullptr; 3299 TemplateSpecializationType *Spec 3300 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3301 3302 if (!Spec) { 3303 // Allocate a new canonical template specialization type. 3304 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 3305 sizeof(TemplateArgument) * NumArgs), 3306 TypeAlignment); 3307 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 3308 CanonArgs.data(), NumArgs, 3309 QualType(), QualType()); 3310 Types.push_back(Spec); 3311 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 3312 } 3313 3314 assert(Spec->isDependentType() && 3315 "Non-dependent template-id type must have a canonical type"); 3316 return QualType(Spec, 0); 3317} 3318 3319QualType 3320ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 3321 NestedNameSpecifier *NNS, 3322 QualType NamedType) const { 3323 llvm::FoldingSetNodeID ID; 3324 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 3325 3326 void *InsertPos = nullptr; 3327 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3328 if (T) 3329 return QualType(T, 0); 3330 3331 QualType Canon = NamedType; 3332 if (!Canon.isCanonical()) { 3333 Canon = getCanonicalType(NamedType); 3334 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3335 assert(!CheckT && "Elaborated canonical type broken"); 3336 (void)CheckT; 3337 } 3338 3339 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 3340 Types.push_back(T); 3341 ElaboratedTypes.InsertNode(T, InsertPos); 3342 return QualType(T, 0); 3343} 3344 3345QualType 3346ASTContext::getParenType(QualType InnerType) const { 3347 llvm::FoldingSetNodeID ID; 3348 ParenType::Profile(ID, InnerType); 3349 3350 void *InsertPos = nullptr; 3351 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3352 if (T) 3353 return QualType(T, 0); 3354 3355 QualType Canon = InnerType; 3356 if (!Canon.isCanonical()) { 3357 Canon = getCanonicalType(InnerType); 3358 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3359 assert(!CheckT && "Paren canonical type broken"); 3360 (void)CheckT; 3361 } 3362 3363 T = new (*this) ParenType(InnerType, Canon); 3364 Types.push_back(T); 3365 ParenTypes.InsertNode(T, InsertPos); 3366 return QualType(T, 0); 3367} 3368 3369QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 3370 NestedNameSpecifier *NNS, 3371 const IdentifierInfo *Name, 3372 QualType Canon) const { 3373 if (Canon.isNull()) { 3374 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3375 ElaboratedTypeKeyword CanonKeyword = Keyword; 3376 if (Keyword == ETK_None) 3377 CanonKeyword = ETK_Typename; 3378 3379 if (CanonNNS != NNS || CanonKeyword != Keyword) 3380 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 3381 } 3382 3383 llvm::FoldingSetNodeID ID; 3384 DependentNameType::Profile(ID, Keyword, NNS, Name); 3385 3386 void *InsertPos = nullptr; 3387 DependentNameType *T 3388 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 3389 if (T) 3390 return QualType(T, 0); 3391 3392 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 3393 Types.push_back(T); 3394 DependentNameTypes.InsertNode(T, InsertPos); 3395 return QualType(T, 0); 3396} 3397 3398QualType 3399ASTContext::getDependentTemplateSpecializationType( 3400 ElaboratedTypeKeyword Keyword, 3401 NestedNameSpecifier *NNS, 3402 const IdentifierInfo *Name, 3403 const TemplateArgumentListInfo &Args) const { 3404 // TODO: avoid this copy 3405 SmallVector<TemplateArgument, 16> ArgCopy; 3406 for (unsigned I = 0, E = Args.size(); I != E; ++I) 3407 ArgCopy.push_back(Args[I].getArgument()); 3408 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 3409 ArgCopy.size(), 3410 ArgCopy.data()); 3411} 3412 3413QualType 3414ASTContext::getDependentTemplateSpecializationType( 3415 ElaboratedTypeKeyword Keyword, 3416 NestedNameSpecifier *NNS, 3417 const IdentifierInfo *Name, 3418 unsigned NumArgs, 3419 const TemplateArgument *Args) const { 3420 assert((!NNS || NNS->isDependent()) && 3421 "nested-name-specifier must be dependent"); 3422 3423 llvm::FoldingSetNodeID ID; 3424 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 3425 Name, NumArgs, Args); 3426 3427 void *InsertPos = nullptr; 3428 DependentTemplateSpecializationType *T 3429 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3430 if (T) 3431 return QualType(T, 0); 3432 3433 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3434 3435 ElaboratedTypeKeyword CanonKeyword = Keyword; 3436 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 3437 3438 bool AnyNonCanonArgs = false; 3439 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 3440 for (unsigned I = 0; I != NumArgs; ++I) { 3441 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 3442 if (!CanonArgs[I].structurallyEquals(Args[I])) 3443 AnyNonCanonArgs = true; 3444 } 3445 3446 QualType Canon; 3447 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 3448 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 3449 Name, NumArgs, 3450 CanonArgs.data()); 3451 3452 // Find the insert position again. 3453 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3454 } 3455 3456 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 3457 sizeof(TemplateArgument) * NumArgs), 3458 TypeAlignment); 3459 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 3460 Name, NumArgs, Args, Canon); 3461 Types.push_back(T); 3462 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 3463 return QualType(T, 0); 3464} 3465 3466QualType ASTContext::getPackExpansionType(QualType Pattern, 3467 Optional<unsigned> NumExpansions) { 3468 llvm::FoldingSetNodeID ID; 3469 PackExpansionType::Profile(ID, Pattern, NumExpansions); 3470 3471 assert(Pattern->containsUnexpandedParameterPack() && 3472 "Pack expansions must expand one or more parameter packs"); 3473 void *InsertPos = nullptr; 3474 PackExpansionType *T 3475 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3476 if (T) 3477 return QualType(T, 0); 3478 3479 QualType Canon; 3480 if (!Pattern.isCanonical()) { 3481 Canon = getCanonicalType(Pattern); 3482 // The canonical type might not contain an unexpanded parameter pack, if it 3483 // contains an alias template specialization which ignores one of its 3484 // parameters. 3485 if (Canon->containsUnexpandedParameterPack()) { 3486 Canon = getPackExpansionType(Canon, NumExpansions); 3487 3488 // Find the insert position again, in case we inserted an element into 3489 // PackExpansionTypes and invalidated our insert position. 3490 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3491 } 3492 } 3493 3494 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions); 3495 Types.push_back(T); 3496 PackExpansionTypes.InsertNode(T, InsertPos); 3497 return QualType(T, 0); 3498} 3499 3500/// CmpProtocolNames - Comparison predicate for sorting protocols 3501/// alphabetically. 3502static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 3503 const ObjCProtocolDecl *RHS) { 3504 return LHS->getDeclName() < RHS->getDeclName(); 3505} 3506 3507static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 3508 unsigned NumProtocols) { 3509 if (NumProtocols == 0) return true; 3510 3511 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 3512 return false; 3513 3514 for (unsigned i = 1; i != NumProtocols; ++i) 3515 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) || 3516 Protocols[i]->getCanonicalDecl() != Protocols[i]) 3517 return false; 3518 return true; 3519} 3520 3521static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 3522 unsigned &NumProtocols) { 3523 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 3524 3525 // Sort protocols, keyed by name. 3526 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 3527 3528 // Canonicalize. 3529 for (unsigned I = 0, N = NumProtocols; I != N; ++I) 3530 Protocols[I] = Protocols[I]->getCanonicalDecl(); 3531 3532 // Remove duplicates. 3533 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 3534 NumProtocols = ProtocolsEnd-Protocols; 3535} 3536 3537QualType ASTContext::getObjCObjectType(QualType BaseType, 3538 ObjCProtocolDecl * const *Protocols, 3539 unsigned NumProtocols) const { 3540 // If the base type is an interface and there aren't any protocols 3541 // to add, then the interface type will do just fine. 3542 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 3543 return BaseType; 3544 3545 // Look in the folding set for an existing type. 3546 llvm::FoldingSetNodeID ID; 3547 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 3548 void *InsertPos = nullptr; 3549 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 3550 return QualType(QT, 0); 3551 3552 // Build the canonical type, which has the canonical base type and 3553 // a sorted-and-uniqued list of protocols. 3554 QualType Canonical; 3555 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 3556 if (!ProtocolsSorted || !BaseType.isCanonical()) { 3557 if (!ProtocolsSorted) { 3558 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 3559 Protocols + NumProtocols); 3560 unsigned UniqueCount = NumProtocols; 3561 3562 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 3563 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3564 &Sorted[0], UniqueCount); 3565 } else { 3566 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3567 Protocols, NumProtocols); 3568 } 3569 3570 // Regenerate InsertPos. 3571 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 3572 } 3573 3574 unsigned Size = sizeof(ObjCObjectTypeImpl); 3575 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 3576 void *Mem = Allocate(Size, TypeAlignment); 3577 ObjCObjectTypeImpl *T = 3578 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 3579 3580 Types.push_back(T); 3581 ObjCObjectTypes.InsertNode(T, InsertPos); 3582 return QualType(T, 0); 3583} 3584 3585/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 3586/// protocol list adopt all protocols in QT's qualified-id protocol 3587/// list. 3588bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 3589 ObjCInterfaceDecl *IC) { 3590 if (!QT->isObjCQualifiedIdType()) 3591 return false; 3592 3593 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) { 3594 // If both the right and left sides have qualifiers. 3595 for (auto *Proto : OPT->quals()) { 3596 if (!IC->ClassImplementsProtocol(Proto, false)) 3597 return false; 3598 } 3599 return true; 3600 } 3601 return false; 3602} 3603 3604/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 3605/// QT's qualified-id protocol list adopt all protocols in IDecl's list 3606/// of protocols. 3607bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 3608 ObjCInterfaceDecl *IDecl) { 3609 if (!QT->isObjCQualifiedIdType()) 3610 return false; 3611 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>(); 3612 if (!OPT) 3613 return false; 3614 if (!IDecl->hasDefinition()) 3615 return false; 3616 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 3617 CollectInheritedProtocols(IDecl, InheritedProtocols); 3618 if (InheritedProtocols.empty()) 3619 return false; 3620 // Check that if every protocol in list of id<plist> conforms to a protcol 3621 // of IDecl's, then bridge casting is ok. 3622 bool Conforms = false; 3623 for (auto *Proto : OPT->quals()) { 3624 Conforms = false; 3625 for (auto *PI : InheritedProtocols) { 3626 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 3627 Conforms = true; 3628 break; 3629 } 3630 } 3631 if (!Conforms) 3632 break; 3633 } 3634 if (Conforms) 3635 return true; 3636 3637 for (auto *PI : InheritedProtocols) { 3638 // If both the right and left sides have qualifiers. 3639 bool Adopts = false; 3640 for (auto *Proto : OPT->quals()) { 3641 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 3642 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 3643 break; 3644 } 3645 if (!Adopts) 3646 return false; 3647 } 3648 return true; 3649} 3650 3651/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 3652/// the given object type. 3653QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 3654 llvm::FoldingSetNodeID ID; 3655 ObjCObjectPointerType::Profile(ID, ObjectT); 3656 3657 void *InsertPos = nullptr; 3658 if (ObjCObjectPointerType *QT = 3659 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3660 return QualType(QT, 0); 3661 3662 // Find the canonical object type. 3663 QualType Canonical; 3664 if (!ObjectT.isCanonical()) { 3665 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 3666 3667 // Regenerate InsertPos. 3668 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3669 } 3670 3671 // No match. 3672 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 3673 ObjCObjectPointerType *QType = 3674 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 3675 3676 Types.push_back(QType); 3677 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 3678 return QualType(QType, 0); 3679} 3680 3681/// getObjCInterfaceType - Return the unique reference to the type for the 3682/// specified ObjC interface decl. The list of protocols is optional. 3683QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 3684 ObjCInterfaceDecl *PrevDecl) const { 3685 if (Decl->TypeForDecl) 3686 return QualType(Decl->TypeForDecl, 0); 3687 3688 if (PrevDecl) { 3689 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 3690 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3691 return QualType(PrevDecl->TypeForDecl, 0); 3692 } 3693 3694 // Prefer the definition, if there is one. 3695 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 3696 Decl = Def; 3697 3698 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 3699 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 3700 Decl->TypeForDecl = T; 3701 Types.push_back(T); 3702 return QualType(T, 0); 3703} 3704 3705/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 3706/// TypeOfExprType AST's (since expression's are never shared). For example, 3707/// multiple declarations that refer to "typeof(x)" all contain different 3708/// DeclRefExpr's. This doesn't effect the type checker, since it operates 3709/// on canonical type's (which are always unique). 3710QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 3711 TypeOfExprType *toe; 3712 if (tofExpr->isTypeDependent()) { 3713 llvm::FoldingSetNodeID ID; 3714 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 3715 3716 void *InsertPos = nullptr; 3717 DependentTypeOfExprType *Canon 3718 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 3719 if (Canon) { 3720 // We already have a "canonical" version of an identical, dependent 3721 // typeof(expr) type. Use that as our canonical type. 3722 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 3723 QualType((TypeOfExprType*)Canon, 0)); 3724 } else { 3725 // Build a new, canonical typeof(expr) type. 3726 Canon 3727 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 3728 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 3729 toe = Canon; 3730 } 3731 } else { 3732 QualType Canonical = getCanonicalType(tofExpr->getType()); 3733 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 3734 } 3735 Types.push_back(toe); 3736 return QualType(toe, 0); 3737} 3738 3739/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 3740/// TypeOfType nodes. The only motivation to unique these nodes would be 3741/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 3742/// an issue. This doesn't affect the type checker, since it operates 3743/// on canonical types (which are always unique). 3744QualType ASTContext::getTypeOfType(QualType tofType) const { 3745 QualType Canonical = getCanonicalType(tofType); 3746 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 3747 Types.push_back(tot); 3748 return QualType(tot, 0); 3749} 3750 3751 3752/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType 3753/// nodes. This would never be helpful, since each such type has its own 3754/// expression, and would not give a significant memory saving, since there 3755/// is an Expr tree under each such type. 3756QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 3757 DecltypeType *dt; 3758 3759 // C++11 [temp.type]p2: 3760 // If an expression e involves a template parameter, decltype(e) denotes a 3761 // unique dependent type. Two such decltype-specifiers refer to the same 3762 // type only if their expressions are equivalent (14.5.6.1). 3763 if (e->isInstantiationDependent()) { 3764 llvm::FoldingSetNodeID ID; 3765 DependentDecltypeType::Profile(ID, *this, e); 3766 3767 void *InsertPos = nullptr; 3768 DependentDecltypeType *Canon 3769 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 3770 if (!Canon) { 3771 // Build a new, canonical typeof(expr) type. 3772 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 3773 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 3774 } 3775 dt = new (*this, TypeAlignment) 3776 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 3777 } else { 3778 dt = new (*this, TypeAlignment) 3779 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 3780 } 3781 Types.push_back(dt); 3782 return QualType(dt, 0); 3783} 3784 3785/// getUnaryTransformationType - We don't unique these, since the memory 3786/// savings are minimal and these are rare. 3787QualType ASTContext::getUnaryTransformType(QualType BaseType, 3788 QualType UnderlyingType, 3789 UnaryTransformType::UTTKind Kind) 3790 const { 3791 UnaryTransformType *Ty = 3792 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 3793 Kind, 3794 UnderlyingType->isDependentType() ? 3795 QualType() : getCanonicalType(UnderlyingType)); 3796 Types.push_back(Ty); 3797 return QualType(Ty, 0); 3798} 3799 3800/// getAutoType - Return the uniqued reference to the 'auto' type which has been 3801/// deduced to the given type, or to the canonical undeduced 'auto' type, or the 3802/// canonical deduced-but-dependent 'auto' type. 3803QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto, 3804 bool IsDependent) const { 3805 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent) 3806 return getAutoDeductType(); 3807 3808 // Look in the folding set for an existing type. 3809 void *InsertPos = nullptr; 3810 llvm::FoldingSetNodeID ID; 3811 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent); 3812 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3813 return QualType(AT, 0); 3814 3815 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType, 3816 IsDecltypeAuto, 3817 IsDependent); 3818 Types.push_back(AT); 3819 if (InsertPos) 3820 AutoTypes.InsertNode(AT, InsertPos); 3821 return QualType(AT, 0); 3822} 3823 3824/// getAtomicType - Return the uniqued reference to the atomic type for 3825/// the given value type. 3826QualType ASTContext::getAtomicType(QualType T) const { 3827 // Unique pointers, to guarantee there is only one pointer of a particular 3828 // structure. 3829 llvm::FoldingSetNodeID ID; 3830 AtomicType::Profile(ID, T); 3831 3832 void *InsertPos = nullptr; 3833 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 3834 return QualType(AT, 0); 3835 3836 // If the atomic value type isn't canonical, this won't be a canonical type 3837 // either, so fill in the canonical type field. 3838 QualType Canonical; 3839 if (!T.isCanonical()) { 3840 Canonical = getAtomicType(getCanonicalType(T)); 3841 3842 // Get the new insert position for the node we care about. 3843 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3844 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3845 } 3846 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3847 Types.push_back(New); 3848 AtomicTypes.InsertNode(New, InsertPos); 3849 return QualType(New, 0); 3850} 3851 3852/// getAutoDeductType - Get type pattern for deducing against 'auto'. 3853QualType ASTContext::getAutoDeductType() const { 3854 if (AutoDeductTy.isNull()) 3855 AutoDeductTy = QualType( 3856 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false, 3857 /*dependent*/false), 3858 0); 3859 return AutoDeductTy; 3860} 3861 3862/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3863QualType ASTContext::getAutoRRefDeductType() const { 3864 if (AutoRRefDeductTy.isNull()) 3865 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3866 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3867 return AutoRRefDeductTy; 3868} 3869 3870/// getTagDeclType - Return the unique reference to the type for the 3871/// specified TagDecl (struct/union/class/enum) decl. 3872QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3873 assert (Decl); 3874 // FIXME: What is the design on getTagDeclType when it requires casting 3875 // away const? mutable? 3876 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3877} 3878 3879/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3880/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3881/// needs to agree with the definition in <stddef.h>. 3882CanQualType ASTContext::getSizeType() const { 3883 return getFromTargetType(Target->getSizeType()); 3884} 3885 3886/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3887CanQualType ASTContext::getIntMaxType() const { 3888 return getFromTargetType(Target->getIntMaxType()); 3889} 3890 3891/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3892CanQualType ASTContext::getUIntMaxType() const { 3893 return getFromTargetType(Target->getUIntMaxType()); 3894} 3895 3896/// getSignedWCharType - Return the type of "signed wchar_t". 3897/// Used when in C++, as a GCC extension. 3898QualType ASTContext::getSignedWCharType() const { 3899 // FIXME: derive from "Target" ? 3900 return WCharTy; 3901} 3902 3903/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3904/// Used when in C++, as a GCC extension. 3905QualType ASTContext::getUnsignedWCharType() const { 3906 // FIXME: derive from "Target" ? 3907 return UnsignedIntTy; 3908} 3909 3910QualType ASTContext::getIntPtrType() const { 3911 return getFromTargetType(Target->getIntPtrType()); 3912} 3913 3914QualType ASTContext::getUIntPtrType() const { 3915 return getCorrespondingUnsignedType(getIntPtrType()); 3916} 3917 3918/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3919/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3920QualType ASTContext::getPointerDiffType() const { 3921 return getFromTargetType(Target->getPtrDiffType(0)); 3922} 3923 3924/// \brief Return the unique type for "pid_t" defined in 3925/// <sys/types.h>. We need this to compute the correct type for vfork(). 3926QualType ASTContext::getProcessIDType() const { 3927 return getFromTargetType(Target->getProcessIDType()); 3928} 3929 3930//===----------------------------------------------------------------------===// 3931// Type Operators 3932//===----------------------------------------------------------------------===// 3933 3934CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3935 // Push qualifiers into arrays, and then discard any remaining 3936 // qualifiers. 3937 T = getCanonicalType(T); 3938 T = getVariableArrayDecayedType(T); 3939 const Type *Ty = T.getTypePtr(); 3940 QualType Result; 3941 if (isa<ArrayType>(Ty)) { 3942 Result = getArrayDecayedType(QualType(Ty,0)); 3943 } else if (isa<FunctionType>(Ty)) { 3944 Result = getPointerType(QualType(Ty, 0)); 3945 } else { 3946 Result = QualType(Ty, 0); 3947 } 3948 3949 return CanQualType::CreateUnsafe(Result); 3950} 3951 3952QualType ASTContext::getUnqualifiedArrayType(QualType type, 3953 Qualifiers &quals) { 3954 SplitQualType splitType = type.getSplitUnqualifiedType(); 3955 3956 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3957 // the unqualified desugared type and then drops it on the floor. 3958 // We then have to strip that sugar back off with 3959 // getUnqualifiedDesugaredType(), which is silly. 3960 const ArrayType *AT = 3961 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 3962 3963 // If we don't have an array, just use the results in splitType. 3964 if (!AT) { 3965 quals = splitType.Quals; 3966 return QualType(splitType.Ty, 0); 3967 } 3968 3969 // Otherwise, recurse on the array's element type. 3970 QualType elementType = AT->getElementType(); 3971 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3972 3973 // If that didn't change the element type, AT has no qualifiers, so we 3974 // can just use the results in splitType. 3975 if (elementType == unqualElementType) { 3976 assert(quals.empty()); // from the recursive call 3977 quals = splitType.Quals; 3978 return QualType(splitType.Ty, 0); 3979 } 3980 3981 // Otherwise, add in the qualifiers from the outermost type, then 3982 // build the type back up. 3983 quals.addConsistentQualifiers(splitType.Quals); 3984 3985 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3986 return getConstantArrayType(unqualElementType, CAT->getSize(), 3987 CAT->getSizeModifier(), 0); 3988 } 3989 3990 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3991 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3992 } 3993 3994 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3995 return getVariableArrayType(unqualElementType, 3996 VAT->getSizeExpr(), 3997 VAT->getSizeModifier(), 3998 VAT->getIndexTypeCVRQualifiers(), 3999 VAT->getBracketsRange()); 4000 } 4001 4002 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 4003 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 4004 DSAT->getSizeModifier(), 0, 4005 SourceRange()); 4006} 4007 4008/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 4009/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 4010/// they point to and return true. If T1 and T2 aren't pointer types 4011/// or pointer-to-member types, or if they are not similar at this 4012/// level, returns false and leaves T1 and T2 unchanged. Top-level 4013/// qualifiers on T1 and T2 are ignored. This function will typically 4014/// be called in a loop that successively "unwraps" pointer and 4015/// pointer-to-member types to compare them at each level. 4016bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 4017 const PointerType *T1PtrType = T1->getAs<PointerType>(), 4018 *T2PtrType = T2->getAs<PointerType>(); 4019 if (T1PtrType && T2PtrType) { 4020 T1 = T1PtrType->getPointeeType(); 4021 T2 = T2PtrType->getPointeeType(); 4022 return true; 4023 } 4024 4025 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 4026 *T2MPType = T2->getAs<MemberPointerType>(); 4027 if (T1MPType && T2MPType && 4028 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 4029 QualType(T2MPType->getClass(), 0))) { 4030 T1 = T1MPType->getPointeeType(); 4031 T2 = T2MPType->getPointeeType(); 4032 return true; 4033 } 4034 4035 if (getLangOpts().ObjC1) { 4036 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 4037 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 4038 if (T1OPType && T2OPType) { 4039 T1 = T1OPType->getPointeeType(); 4040 T2 = T2OPType->getPointeeType(); 4041 return true; 4042 } 4043 } 4044 4045 // FIXME: Block pointers, too? 4046 4047 return false; 4048} 4049 4050DeclarationNameInfo 4051ASTContext::getNameForTemplate(TemplateName Name, 4052 SourceLocation NameLoc) const { 4053 switch (Name.getKind()) { 4054 case TemplateName::QualifiedTemplate: 4055 case TemplateName::Template: 4056 // DNInfo work in progress: CHECKME: what about DNLoc? 4057 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 4058 NameLoc); 4059 4060 case TemplateName::OverloadedTemplate: { 4061 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 4062 // DNInfo work in progress: CHECKME: what about DNLoc? 4063 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 4064 } 4065 4066 case TemplateName::DependentTemplate: { 4067 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4068 DeclarationName DName; 4069 if (DTN->isIdentifier()) { 4070 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 4071 return DeclarationNameInfo(DName, NameLoc); 4072 } else { 4073 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 4074 // DNInfo work in progress: FIXME: source locations? 4075 DeclarationNameLoc DNLoc; 4076 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 4077 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 4078 return DeclarationNameInfo(DName, NameLoc, DNLoc); 4079 } 4080 } 4081 4082 case TemplateName::SubstTemplateTemplateParm: { 4083 SubstTemplateTemplateParmStorage *subst 4084 = Name.getAsSubstTemplateTemplateParm(); 4085 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 4086 NameLoc); 4087 } 4088 4089 case TemplateName::SubstTemplateTemplateParmPack: { 4090 SubstTemplateTemplateParmPackStorage *subst 4091 = Name.getAsSubstTemplateTemplateParmPack(); 4092 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 4093 NameLoc); 4094 } 4095 } 4096 4097 llvm_unreachable("bad template name kind!"); 4098} 4099 4100TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 4101 switch (Name.getKind()) { 4102 case TemplateName::QualifiedTemplate: 4103 case TemplateName::Template: { 4104 TemplateDecl *Template = Name.getAsTemplateDecl(); 4105 if (TemplateTemplateParmDecl *TTP 4106 = dyn_cast<TemplateTemplateParmDecl>(Template)) 4107 Template = getCanonicalTemplateTemplateParmDecl(TTP); 4108 4109 // The canonical template name is the canonical template declaration. 4110 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 4111 } 4112 4113 case TemplateName::OverloadedTemplate: 4114 llvm_unreachable("cannot canonicalize overloaded template"); 4115 4116 case TemplateName::DependentTemplate: { 4117 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4118 assert(DTN && "Non-dependent template names must refer to template decls."); 4119 return DTN->CanonicalTemplateName; 4120 } 4121 4122 case TemplateName::SubstTemplateTemplateParm: { 4123 SubstTemplateTemplateParmStorage *subst 4124 = Name.getAsSubstTemplateTemplateParm(); 4125 return getCanonicalTemplateName(subst->getReplacement()); 4126 } 4127 4128 case TemplateName::SubstTemplateTemplateParmPack: { 4129 SubstTemplateTemplateParmPackStorage *subst 4130 = Name.getAsSubstTemplateTemplateParmPack(); 4131 TemplateTemplateParmDecl *canonParameter 4132 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 4133 TemplateArgument canonArgPack 4134 = getCanonicalTemplateArgument(subst->getArgumentPack()); 4135 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 4136 } 4137 } 4138 4139 llvm_unreachable("bad template name!"); 4140} 4141 4142bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 4143 X = getCanonicalTemplateName(X); 4144 Y = getCanonicalTemplateName(Y); 4145 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 4146} 4147 4148TemplateArgument 4149ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 4150 switch (Arg.getKind()) { 4151 case TemplateArgument::Null: 4152 return Arg; 4153 4154 case TemplateArgument::Expression: 4155 return Arg; 4156 4157 case TemplateArgument::Declaration: { 4158 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 4159 return TemplateArgument(D, Arg.getParamTypeForDecl()); 4160 } 4161 4162 case TemplateArgument::NullPtr: 4163 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 4164 /*isNullPtr*/true); 4165 4166 case TemplateArgument::Template: 4167 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 4168 4169 case TemplateArgument::TemplateExpansion: 4170 return TemplateArgument(getCanonicalTemplateName( 4171 Arg.getAsTemplateOrTemplatePattern()), 4172 Arg.getNumTemplateExpansions()); 4173 4174 case TemplateArgument::Integral: 4175 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 4176 4177 case TemplateArgument::Type: 4178 return TemplateArgument(getCanonicalType(Arg.getAsType())); 4179 4180 case TemplateArgument::Pack: { 4181 if (Arg.pack_size() == 0) 4182 return Arg; 4183 4184 TemplateArgument *CanonArgs 4185 = new (*this) TemplateArgument[Arg.pack_size()]; 4186 unsigned Idx = 0; 4187 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 4188 AEnd = Arg.pack_end(); 4189 A != AEnd; (void)++A, ++Idx) 4190 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 4191 4192 return TemplateArgument(CanonArgs, Arg.pack_size()); 4193 } 4194 } 4195 4196 // Silence GCC warning 4197 llvm_unreachable("Unhandled template argument kind"); 4198} 4199 4200NestedNameSpecifier * 4201ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 4202 if (!NNS) 4203 return nullptr; 4204 4205 switch (NNS->getKind()) { 4206 case NestedNameSpecifier::Identifier: 4207 // Canonicalize the prefix but keep the identifier the same. 4208 return NestedNameSpecifier::Create(*this, 4209 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 4210 NNS->getAsIdentifier()); 4211 4212 case NestedNameSpecifier::Namespace: 4213 // A namespace is canonical; build a nested-name-specifier with 4214 // this namespace and no prefix. 4215 return NestedNameSpecifier::Create(*this, nullptr, 4216 NNS->getAsNamespace()->getOriginalNamespace()); 4217 4218 case NestedNameSpecifier::NamespaceAlias: 4219 // A namespace is canonical; build a nested-name-specifier with 4220 // this namespace and no prefix. 4221 return NestedNameSpecifier::Create(*this, nullptr, 4222 NNS->getAsNamespaceAlias()->getNamespace() 4223 ->getOriginalNamespace()); 4224 4225 case NestedNameSpecifier::TypeSpec: 4226 case NestedNameSpecifier::TypeSpecWithTemplate: { 4227 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 4228 4229 // If we have some kind of dependent-named type (e.g., "typename T::type"), 4230 // break it apart into its prefix and identifier, then reconsititute those 4231 // as the canonical nested-name-specifier. This is required to canonicalize 4232 // a dependent nested-name-specifier involving typedefs of dependent-name 4233 // types, e.g., 4234 // typedef typename T::type T1; 4235 // typedef typename T1::type T2; 4236 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 4237 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 4238 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 4239 4240 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 4241 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 4242 // first place? 4243 return NestedNameSpecifier::Create(*this, nullptr, false, 4244 const_cast<Type *>(T.getTypePtr())); 4245 } 4246 4247 case NestedNameSpecifier::Global: 4248 case NestedNameSpecifier::Super: 4249 // The global specifier and __super specifer are canonical and unique. 4250 return NNS; 4251 } 4252 4253 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 4254} 4255 4256 4257const ArrayType *ASTContext::getAsArrayType(QualType T) const { 4258 // Handle the non-qualified case efficiently. 4259 if (!T.hasLocalQualifiers()) { 4260 // Handle the common positive case fast. 4261 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 4262 return AT; 4263 } 4264 4265 // Handle the common negative case fast. 4266 if (!isa<ArrayType>(T.getCanonicalType())) 4267 return nullptr; 4268 4269 // Apply any qualifiers from the array type to the element type. This 4270 // implements C99 6.7.3p8: "If the specification of an array type includes 4271 // any type qualifiers, the element type is so qualified, not the array type." 4272 4273 // If we get here, we either have type qualifiers on the type, or we have 4274 // sugar such as a typedef in the way. If we have type qualifiers on the type 4275 // we must propagate them down into the element type. 4276 4277 SplitQualType split = T.getSplitDesugaredType(); 4278 Qualifiers qs = split.Quals; 4279 4280 // If we have a simple case, just return now. 4281 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 4282 if (!ATy || qs.empty()) 4283 return ATy; 4284 4285 // Otherwise, we have an array and we have qualifiers on it. Push the 4286 // qualifiers into the array element type and return a new array type. 4287 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 4288 4289 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 4290 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 4291 CAT->getSizeModifier(), 4292 CAT->getIndexTypeCVRQualifiers())); 4293 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 4294 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 4295 IAT->getSizeModifier(), 4296 IAT->getIndexTypeCVRQualifiers())); 4297 4298 if (const DependentSizedArrayType *DSAT 4299 = dyn_cast<DependentSizedArrayType>(ATy)) 4300 return cast<ArrayType>( 4301 getDependentSizedArrayType(NewEltTy, 4302 DSAT->getSizeExpr(), 4303 DSAT->getSizeModifier(), 4304 DSAT->getIndexTypeCVRQualifiers(), 4305 DSAT->getBracketsRange())); 4306 4307 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 4308 return cast<ArrayType>(getVariableArrayType(NewEltTy, 4309 VAT->getSizeExpr(), 4310 VAT->getSizeModifier(), 4311 VAT->getIndexTypeCVRQualifiers(), 4312 VAT->getBracketsRange())); 4313} 4314 4315QualType ASTContext::getAdjustedParameterType(QualType T) const { 4316 if (T->isArrayType() || T->isFunctionType()) 4317 return getDecayedType(T); 4318 return T; 4319} 4320 4321QualType ASTContext::getSignatureParameterType(QualType T) const { 4322 T = getVariableArrayDecayedType(T); 4323 T = getAdjustedParameterType(T); 4324 return T.getUnqualifiedType(); 4325} 4326 4327/// getArrayDecayedType - Return the properly qualified result of decaying the 4328/// specified array type to a pointer. This operation is non-trivial when 4329/// handling typedefs etc. The canonical type of "T" must be an array type, 4330/// this returns a pointer to a properly qualified element of the array. 4331/// 4332/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 4333QualType ASTContext::getArrayDecayedType(QualType Ty) const { 4334 // Get the element type with 'getAsArrayType' so that we don't lose any 4335 // typedefs in the element type of the array. This also handles propagation 4336 // of type qualifiers from the array type into the element type if present 4337 // (C99 6.7.3p8). 4338 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 4339 assert(PrettyArrayType && "Not an array type!"); 4340 4341 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 4342 4343 // int x[restrict 4] -> int *restrict 4344 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 4345} 4346 4347QualType ASTContext::getBaseElementType(const ArrayType *array) const { 4348 return getBaseElementType(array->getElementType()); 4349} 4350 4351QualType ASTContext::getBaseElementType(QualType type) const { 4352 Qualifiers qs; 4353 while (true) { 4354 SplitQualType split = type.getSplitDesugaredType(); 4355 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 4356 if (!array) break; 4357 4358 type = array->getElementType(); 4359 qs.addConsistentQualifiers(split.Quals); 4360 } 4361 4362 return getQualifiedType(type, qs); 4363} 4364 4365/// getConstantArrayElementCount - Returns number of constant array elements. 4366uint64_t 4367ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 4368 uint64_t ElementCount = 1; 4369 do { 4370 ElementCount *= CA->getSize().getZExtValue(); 4371 CA = dyn_cast_or_null<ConstantArrayType>( 4372 CA->getElementType()->getAsArrayTypeUnsafe()); 4373 } while (CA); 4374 return ElementCount; 4375} 4376 4377/// getFloatingRank - Return a relative rank for floating point types. 4378/// This routine will assert if passed a built-in type that isn't a float. 4379static FloatingRank getFloatingRank(QualType T) { 4380 if (const ComplexType *CT = T->getAs<ComplexType>()) 4381 return getFloatingRank(CT->getElementType()); 4382 4383 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 4384 switch (T->getAs<BuiltinType>()->getKind()) { 4385 default: llvm_unreachable("getFloatingRank(): not a floating type"); 4386 case BuiltinType::Half: return HalfRank; 4387 case BuiltinType::Float: return FloatRank; 4388 case BuiltinType::Double: return DoubleRank; 4389 case BuiltinType::LongDouble: return LongDoubleRank; 4390 } 4391} 4392 4393/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 4394/// point or a complex type (based on typeDomain/typeSize). 4395/// 'typeDomain' is a real floating point or complex type. 4396/// 'typeSize' is a real floating point or complex type. 4397QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 4398 QualType Domain) const { 4399 FloatingRank EltRank = getFloatingRank(Size); 4400 if (Domain->isComplexType()) { 4401 switch (EltRank) { 4402 case HalfRank: llvm_unreachable("Complex half is not supported"); 4403 case FloatRank: return FloatComplexTy; 4404 case DoubleRank: return DoubleComplexTy; 4405 case LongDoubleRank: return LongDoubleComplexTy; 4406 } 4407 } 4408 4409 assert(Domain->isRealFloatingType() && "Unknown domain!"); 4410 switch (EltRank) { 4411 case HalfRank: return HalfTy; 4412 case FloatRank: return FloatTy; 4413 case DoubleRank: return DoubleTy; 4414 case LongDoubleRank: return LongDoubleTy; 4415 } 4416 llvm_unreachable("getFloatingRank(): illegal value for rank"); 4417} 4418 4419/// getFloatingTypeOrder - Compare the rank of the two specified floating 4420/// point types, ignoring the domain of the type (i.e. 'double' == 4421/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 4422/// LHS < RHS, return -1. 4423int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 4424 FloatingRank LHSR = getFloatingRank(LHS); 4425 FloatingRank RHSR = getFloatingRank(RHS); 4426 4427 if (LHSR == RHSR) 4428 return 0; 4429 if (LHSR > RHSR) 4430 return 1; 4431 return -1; 4432} 4433 4434/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 4435/// routine will assert if passed a built-in type that isn't an integer or enum, 4436/// or if it is not canonicalized. 4437unsigned ASTContext::getIntegerRank(const Type *T) const { 4438 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 4439 4440 switch (cast<BuiltinType>(T)->getKind()) { 4441 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 4442 case BuiltinType::Bool: 4443 return 1 + (getIntWidth(BoolTy) << 3); 4444 case BuiltinType::Char_S: 4445 case BuiltinType::Char_U: 4446 case BuiltinType::SChar: 4447 case BuiltinType::UChar: 4448 return 2 + (getIntWidth(CharTy) << 3); 4449 case BuiltinType::Short: 4450 case BuiltinType::UShort: 4451 return 3 + (getIntWidth(ShortTy) << 3); 4452 case BuiltinType::Int: 4453 case BuiltinType::UInt: 4454 return 4 + (getIntWidth(IntTy) << 3); 4455 case BuiltinType::Long: 4456 case BuiltinType::ULong: 4457 return 5 + (getIntWidth(LongTy) << 3); 4458 case BuiltinType::LongLong: 4459 case BuiltinType::ULongLong: 4460 return 6 + (getIntWidth(LongLongTy) << 3); 4461 case BuiltinType::Int128: 4462 case BuiltinType::UInt128: 4463 return 7 + (getIntWidth(Int128Ty) << 3); 4464 } 4465} 4466 4467/// \brief Whether this is a promotable bitfield reference according 4468/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 4469/// 4470/// \returns the type this bit-field will promote to, or NULL if no 4471/// promotion occurs. 4472QualType ASTContext::isPromotableBitField(Expr *E) const { 4473 if (E->isTypeDependent() || E->isValueDependent()) 4474 return QualType(); 4475 4476 // FIXME: We should not do this unless E->refersToBitField() is true. This 4477 // matters in C where getSourceBitField() will find bit-fields for various 4478 // cases where the source expression is not a bit-field designator. 4479 4480 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 4481 if (!Field) 4482 return QualType(); 4483 4484 QualType FT = Field->getType(); 4485 4486 uint64_t BitWidth = Field->getBitWidthValue(*this); 4487 uint64_t IntSize = getTypeSize(IntTy); 4488 // C++ [conv.prom]p5: 4489 // A prvalue for an integral bit-field can be converted to a prvalue of type 4490 // int if int can represent all the values of the bit-field; otherwise, it 4491 // can be converted to unsigned int if unsigned int can represent all the 4492 // values of the bit-field. If the bit-field is larger yet, no integral 4493 // promotion applies to it. 4494 // C11 6.3.1.1/2: 4495 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 4496 // If an int can represent all values of the original type (as restricted by 4497 // the width, for a bit-field), the value is converted to an int; otherwise, 4498 // it is converted to an unsigned int. 4499 // 4500 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 4501 // We perform that promotion here to match GCC and C++. 4502 if (BitWidth < IntSize) 4503 return IntTy; 4504 4505 if (BitWidth == IntSize) 4506 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 4507 4508 // Types bigger than int are not subject to promotions, and therefore act 4509 // like the base type. GCC has some weird bugs in this area that we 4510 // deliberately do not follow (GCC follows a pre-standard resolution to 4511 // C's DR315 which treats bit-width as being part of the type, and this leaks 4512 // into their semantics in some cases). 4513 return QualType(); 4514} 4515 4516/// getPromotedIntegerType - Returns the type that Promotable will 4517/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 4518/// integer type. 4519QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 4520 assert(!Promotable.isNull()); 4521 assert(Promotable->isPromotableIntegerType()); 4522 if (const EnumType *ET = Promotable->getAs<EnumType>()) 4523 return ET->getDecl()->getPromotionType(); 4524 4525 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 4526 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 4527 // (3.9.1) can be converted to a prvalue of the first of the following 4528 // types that can represent all the values of its underlying type: 4529 // int, unsigned int, long int, unsigned long int, long long int, or 4530 // unsigned long long int [...] 4531 // FIXME: Is there some better way to compute this? 4532 if (BT->getKind() == BuiltinType::WChar_S || 4533 BT->getKind() == BuiltinType::WChar_U || 4534 BT->getKind() == BuiltinType::Char16 || 4535 BT->getKind() == BuiltinType::Char32) { 4536 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 4537 uint64_t FromSize = getTypeSize(BT); 4538 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 4539 LongLongTy, UnsignedLongLongTy }; 4540 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 4541 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 4542 if (FromSize < ToSize || 4543 (FromSize == ToSize && 4544 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 4545 return PromoteTypes[Idx]; 4546 } 4547 llvm_unreachable("char type should fit into long long"); 4548 } 4549 } 4550 4551 // At this point, we should have a signed or unsigned integer type. 4552 if (Promotable->isSignedIntegerType()) 4553 return IntTy; 4554 uint64_t PromotableSize = getIntWidth(Promotable); 4555 uint64_t IntSize = getIntWidth(IntTy); 4556 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 4557 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 4558} 4559 4560/// \brief Recurses in pointer/array types until it finds an objc retainable 4561/// type and returns its ownership. 4562Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 4563 while (!T.isNull()) { 4564 if (T.getObjCLifetime() != Qualifiers::OCL_None) 4565 return T.getObjCLifetime(); 4566 if (T->isArrayType()) 4567 T = getBaseElementType(T); 4568 else if (const PointerType *PT = T->getAs<PointerType>()) 4569 T = PT->getPointeeType(); 4570 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4571 T = RT->getPointeeType(); 4572 else 4573 break; 4574 } 4575 4576 return Qualifiers::OCL_None; 4577} 4578 4579static const Type *getIntegerTypeForEnum(const EnumType *ET) { 4580 // Incomplete enum types are not treated as integer types. 4581 // FIXME: In C++, enum types are never integer types. 4582 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 4583 return ET->getDecl()->getIntegerType().getTypePtr(); 4584 return nullptr; 4585} 4586 4587/// getIntegerTypeOrder - Returns the highest ranked integer type: 4588/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 4589/// LHS < RHS, return -1. 4590int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 4591 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 4592 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 4593 4594 // Unwrap enums to their underlying type. 4595 if (const EnumType *ET = dyn_cast<EnumType>(LHSC)) 4596 LHSC = getIntegerTypeForEnum(ET); 4597 if (const EnumType *ET = dyn_cast<EnumType>(RHSC)) 4598 RHSC = getIntegerTypeForEnum(ET); 4599 4600 if (LHSC == RHSC) return 0; 4601 4602 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 4603 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 4604 4605 unsigned LHSRank = getIntegerRank(LHSC); 4606 unsigned RHSRank = getIntegerRank(RHSC); 4607 4608 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 4609 if (LHSRank == RHSRank) return 0; 4610 return LHSRank > RHSRank ? 1 : -1; 4611 } 4612 4613 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 4614 if (LHSUnsigned) { 4615 // If the unsigned [LHS] type is larger, return it. 4616 if (LHSRank >= RHSRank) 4617 return 1; 4618 4619 // If the signed type can represent all values of the unsigned type, it 4620 // wins. Because we are dealing with 2's complement and types that are 4621 // powers of two larger than each other, this is always safe. 4622 return -1; 4623 } 4624 4625 // If the unsigned [RHS] type is larger, return it. 4626 if (RHSRank >= LHSRank) 4627 return -1; 4628 4629 // If the signed type can represent all values of the unsigned type, it 4630 // wins. Because we are dealing with 2's complement and types that are 4631 // powers of two larger than each other, this is always safe. 4632 return 1; 4633} 4634 4635// getCFConstantStringType - Return the type used for constant CFStrings. 4636QualType ASTContext::getCFConstantStringType() const { 4637 if (!CFConstantStringTypeDecl) { 4638 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString"); 4639 CFConstantStringTypeDecl->startDefinition(); 4640 4641 QualType FieldTypes[4]; 4642 4643 // const int *isa; 4644 FieldTypes[0] = getPointerType(IntTy.withConst()); 4645 // int flags; 4646 FieldTypes[1] = IntTy; 4647 // const char *str; 4648 FieldTypes[2] = getPointerType(CharTy.withConst()); 4649 // long length; 4650 FieldTypes[3] = LongTy; 4651 4652 // Create fields 4653 for (unsigned i = 0; i < 4; ++i) { 4654 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 4655 SourceLocation(), 4656 SourceLocation(), nullptr, 4657 FieldTypes[i], /*TInfo=*/nullptr, 4658 /*BitWidth=*/nullptr, 4659 /*Mutable=*/false, 4660 ICIS_NoInit); 4661 Field->setAccess(AS_public); 4662 CFConstantStringTypeDecl->addDecl(Field); 4663 } 4664 4665 CFConstantStringTypeDecl->completeDefinition(); 4666 } 4667 4668 return getTagDeclType(CFConstantStringTypeDecl); 4669} 4670 4671QualType ASTContext::getObjCSuperType() const { 4672 if (ObjCSuperType.isNull()) { 4673 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 4674 TUDecl->addDecl(ObjCSuperTypeDecl); 4675 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 4676 } 4677 return ObjCSuperType; 4678} 4679 4680void ASTContext::setCFConstantStringType(QualType T) { 4681 const RecordType *Rec = T->getAs<RecordType>(); 4682 assert(Rec && "Invalid CFConstantStringType"); 4683 CFConstantStringTypeDecl = Rec->getDecl(); 4684} 4685 4686QualType ASTContext::getBlockDescriptorType() const { 4687 if (BlockDescriptorType) 4688 return getTagDeclType(BlockDescriptorType); 4689 4690 RecordDecl *RD; 4691 // FIXME: Needs the FlagAppleBlock bit. 4692 RD = buildImplicitRecord("__block_descriptor"); 4693 RD->startDefinition(); 4694 4695 QualType FieldTypes[] = { 4696 UnsignedLongTy, 4697 UnsignedLongTy, 4698 }; 4699 4700 static const char *const FieldNames[] = { 4701 "reserved", 4702 "Size" 4703 }; 4704 4705 for (size_t i = 0; i < 2; ++i) { 4706 FieldDecl *Field = FieldDecl::Create( 4707 *this, RD, SourceLocation(), SourceLocation(), 4708 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 4709 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 4710 Field->setAccess(AS_public); 4711 RD->addDecl(Field); 4712 } 4713 4714 RD->completeDefinition(); 4715 4716 BlockDescriptorType = RD; 4717 4718 return getTagDeclType(BlockDescriptorType); 4719} 4720 4721QualType ASTContext::getBlockDescriptorExtendedType() const { 4722 if (BlockDescriptorExtendedType) 4723 return getTagDeclType(BlockDescriptorExtendedType); 4724 4725 RecordDecl *RD; 4726 // FIXME: Needs the FlagAppleBlock bit. 4727 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 4728 RD->startDefinition(); 4729 4730 QualType FieldTypes[] = { 4731 UnsignedLongTy, 4732 UnsignedLongTy, 4733 getPointerType(VoidPtrTy), 4734 getPointerType(VoidPtrTy) 4735 }; 4736 4737 static const char *const FieldNames[] = { 4738 "reserved", 4739 "Size", 4740 "CopyFuncPtr", 4741 "DestroyFuncPtr" 4742 }; 4743 4744 for (size_t i = 0; i < 4; ++i) { 4745 FieldDecl *Field = FieldDecl::Create( 4746 *this, RD, SourceLocation(), SourceLocation(), 4747 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 4748 /*BitWidth=*/nullptr, 4749 /*Mutable=*/false, ICIS_NoInit); 4750 Field->setAccess(AS_public); 4751 RD->addDecl(Field); 4752 } 4753 4754 RD->completeDefinition(); 4755 4756 BlockDescriptorExtendedType = RD; 4757 return getTagDeclType(BlockDescriptorExtendedType); 4758} 4759 4760/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 4761/// requires copy/dispose. Note that this must match the logic 4762/// in buildByrefHelpers. 4763bool ASTContext::BlockRequiresCopying(QualType Ty, 4764 const VarDecl *D) { 4765 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 4766 const Expr *copyExpr = getBlockVarCopyInits(D); 4767 if (!copyExpr && record->hasTrivialDestructor()) return false; 4768 4769 return true; 4770 } 4771 4772 if (!Ty->isObjCRetainableType()) return false; 4773 4774 Qualifiers qs = Ty.getQualifiers(); 4775 4776 // If we have lifetime, that dominates. 4777 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 4778 assert(getLangOpts().ObjCAutoRefCount); 4779 4780 switch (lifetime) { 4781 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 4782 4783 // These are just bits as far as the runtime is concerned. 4784 case Qualifiers::OCL_ExplicitNone: 4785 case Qualifiers::OCL_Autoreleasing: 4786 return false; 4787 4788 // Tell the runtime that this is ARC __weak, called by the 4789 // byref routines. 4790 case Qualifiers::OCL_Weak: 4791 // ARC __strong __block variables need to be retained. 4792 case Qualifiers::OCL_Strong: 4793 return true; 4794 } 4795 llvm_unreachable("fell out of lifetime switch!"); 4796 } 4797 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 4798 Ty->isObjCObjectPointerType()); 4799} 4800 4801bool ASTContext::getByrefLifetime(QualType Ty, 4802 Qualifiers::ObjCLifetime &LifeTime, 4803 bool &HasByrefExtendedLayout) const { 4804 4805 if (!getLangOpts().ObjC1 || 4806 getLangOpts().getGC() != LangOptions::NonGC) 4807 return false; 4808 4809 HasByrefExtendedLayout = false; 4810 if (Ty->isRecordType()) { 4811 HasByrefExtendedLayout = true; 4812 LifeTime = Qualifiers::OCL_None; 4813 } 4814 else if (getLangOpts().ObjCAutoRefCount) 4815 LifeTime = Ty.getObjCLifetime(); 4816 // MRR. 4817 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 4818 LifeTime = Qualifiers::OCL_ExplicitNone; 4819 else 4820 LifeTime = Qualifiers::OCL_None; 4821 return true; 4822} 4823 4824TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 4825 if (!ObjCInstanceTypeDecl) 4826 ObjCInstanceTypeDecl = 4827 buildImplicitTypedef(getObjCIdType(), "instancetype"); 4828 return ObjCInstanceTypeDecl; 4829} 4830 4831// This returns true if a type has been typedefed to BOOL: 4832// typedef <type> BOOL; 4833static bool isTypeTypedefedAsBOOL(QualType T) { 4834 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 4835 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 4836 return II->isStr("BOOL"); 4837 4838 return false; 4839} 4840 4841/// getObjCEncodingTypeSize returns size of type for objective-c encoding 4842/// purpose. 4843CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 4844 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4845 return CharUnits::Zero(); 4846 4847 CharUnits sz = getTypeSizeInChars(type); 4848 4849 // Make all integer and enum types at least as large as an int 4850 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4851 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4852 // Treat arrays as pointers, since that's how they're passed in. 4853 else if (type->isArrayType()) 4854 sz = getTypeSizeInChars(VoidPtrTy); 4855 return sz; 4856} 4857 4858bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 4859 return getLangOpts().MSVCCompat && VD->isStaticDataMember() && 4860 VD->getType()->isIntegralOrEnumerationType() && 4861 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 4862} 4863 4864static inline 4865std::string charUnitsToString(const CharUnits &CU) { 4866 return llvm::itostr(CU.getQuantity()); 4867} 4868 4869/// getObjCEncodingForBlock - Return the encoded type for this block 4870/// declaration. 4871std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4872 std::string S; 4873 4874 const BlockDecl *Decl = Expr->getBlockDecl(); 4875 QualType BlockTy = 4876 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4877 // Encode result type. 4878 if (getLangOpts().EncodeExtendedBlockSig) 4879 getObjCEncodingForMethodParameter( 4880 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S, 4881 true /*Extended*/); 4882 else 4883 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S); 4884 // Compute size of all parameters. 4885 // Start with computing size of a pointer in number of bytes. 4886 // FIXME: There might(should) be a better way of doing this computation! 4887 SourceLocation Loc; 4888 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4889 CharUnits ParmOffset = PtrSize; 4890 for (auto PI : Decl->params()) { 4891 QualType PType = PI->getType(); 4892 CharUnits sz = getObjCEncodingTypeSize(PType); 4893 if (sz.isZero()) 4894 continue; 4895 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4896 ParmOffset += sz; 4897 } 4898 // Size of the argument frame 4899 S += charUnitsToString(ParmOffset); 4900 // Block pointer and offset. 4901 S += "@?0"; 4902 4903 // Argument types. 4904 ParmOffset = PtrSize; 4905 for (auto PVDecl : Decl->params()) { 4906 QualType PType = PVDecl->getOriginalType(); 4907 if (const ArrayType *AT = 4908 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4909 // Use array's original type only if it has known number of 4910 // elements. 4911 if (!isa<ConstantArrayType>(AT)) 4912 PType = PVDecl->getType(); 4913 } else if (PType->isFunctionType()) 4914 PType = PVDecl->getType(); 4915 if (getLangOpts().EncodeExtendedBlockSig) 4916 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 4917 S, true /*Extended*/); 4918 else 4919 getObjCEncodingForType(PType, S); 4920 S += charUnitsToString(ParmOffset); 4921 ParmOffset += getObjCEncodingTypeSize(PType); 4922 } 4923 4924 return S; 4925} 4926 4927bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4928 std::string& S) { 4929 // Encode result type. 4930 getObjCEncodingForType(Decl->getReturnType(), S); 4931 CharUnits ParmOffset; 4932 // Compute size of all parameters. 4933 for (auto PI : Decl->params()) { 4934 QualType PType = PI->getType(); 4935 CharUnits sz = getObjCEncodingTypeSize(PType); 4936 if (sz.isZero()) 4937 continue; 4938 4939 assert (sz.isPositive() && 4940 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4941 ParmOffset += sz; 4942 } 4943 S += charUnitsToString(ParmOffset); 4944 ParmOffset = CharUnits::Zero(); 4945 4946 // Argument types. 4947 for (auto PVDecl : Decl->params()) { 4948 QualType PType = PVDecl->getOriginalType(); 4949 if (const ArrayType *AT = 4950 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4951 // Use array's original type only if it has known number of 4952 // elements. 4953 if (!isa<ConstantArrayType>(AT)) 4954 PType = PVDecl->getType(); 4955 } else if (PType->isFunctionType()) 4956 PType = PVDecl->getType(); 4957 getObjCEncodingForType(PType, S); 4958 S += charUnitsToString(ParmOffset); 4959 ParmOffset += getObjCEncodingTypeSize(PType); 4960 } 4961 4962 return false; 4963} 4964 4965/// getObjCEncodingForMethodParameter - Return the encoded type for a single 4966/// method parameter or return type. If Extended, include class names and 4967/// block object types. 4968void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4969 QualType T, std::string& S, 4970 bool Extended) const { 4971 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4972 getObjCEncodingForTypeQualifier(QT, S); 4973 // Encode parameter type. 4974 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 4975 true /*OutermostType*/, 4976 false /*EncodingProperty*/, 4977 false /*StructField*/, 4978 Extended /*EncodeBlockParameters*/, 4979 Extended /*EncodeClassNames*/); 4980} 4981 4982/// getObjCEncodingForMethodDecl - Return the encoded type for this method 4983/// declaration. 4984bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4985 std::string& S, 4986 bool Extended) const { 4987 // FIXME: This is not very efficient. 4988 // Encode return type. 4989 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4990 Decl->getReturnType(), S, Extended); 4991 // Compute size of all parameters. 4992 // Start with computing size of a pointer in number of bytes. 4993 // FIXME: There might(should) be a better way of doing this computation! 4994 SourceLocation Loc; 4995 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4996 // The first two arguments (self and _cmd) are pointers; account for 4997 // their size. 4998 CharUnits ParmOffset = 2 * PtrSize; 4999 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 5000 E = Decl->sel_param_end(); PI != E; ++PI) { 5001 QualType PType = (*PI)->getType(); 5002 CharUnits sz = getObjCEncodingTypeSize(PType); 5003 if (sz.isZero()) 5004 continue; 5005 5006 assert (sz.isPositive() && 5007 "getObjCEncodingForMethodDecl - Incomplete param type"); 5008 ParmOffset += sz; 5009 } 5010 S += charUnitsToString(ParmOffset); 5011 S += "@0:"; 5012 S += charUnitsToString(PtrSize); 5013 5014 // Argument types. 5015 ParmOffset = 2 * PtrSize; 5016 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 5017 E = Decl->sel_param_end(); PI != E; ++PI) { 5018 const ParmVarDecl *PVDecl = *PI; 5019 QualType PType = PVDecl->getOriginalType(); 5020 if (const ArrayType *AT = 5021 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 5022 // Use array's original type only if it has known number of 5023 // elements. 5024 if (!isa<ConstantArrayType>(AT)) 5025 PType = PVDecl->getType(); 5026 } else if (PType->isFunctionType()) 5027 PType = PVDecl->getType(); 5028 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 5029 PType, S, Extended); 5030 S += charUnitsToString(ParmOffset); 5031 ParmOffset += getObjCEncodingTypeSize(PType); 5032 } 5033 5034 return false; 5035} 5036 5037ObjCPropertyImplDecl * 5038ASTContext::getObjCPropertyImplDeclForPropertyDecl( 5039 const ObjCPropertyDecl *PD, 5040 const Decl *Container) const { 5041 if (!Container) 5042 return nullptr; 5043 if (const ObjCCategoryImplDecl *CID = 5044 dyn_cast<ObjCCategoryImplDecl>(Container)) { 5045 for (auto *PID : CID->property_impls()) 5046 if (PID->getPropertyDecl() == PD) 5047 return PID; 5048 } else { 5049 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 5050 for (auto *PID : OID->property_impls()) 5051 if (PID->getPropertyDecl() == PD) 5052 return PID; 5053 } 5054 return nullptr; 5055} 5056 5057/// getObjCEncodingForPropertyDecl - Return the encoded type for this 5058/// property declaration. If non-NULL, Container must be either an 5059/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 5060/// NULL when getting encodings for protocol properties. 5061/// Property attributes are stored as a comma-delimited C string. The simple 5062/// attributes readonly and bycopy are encoded as single characters. The 5063/// parametrized attributes, getter=name, setter=name, and ivar=name, are 5064/// encoded as single characters, followed by an identifier. Property types 5065/// are also encoded as a parametrized attribute. The characters used to encode 5066/// these attributes are defined by the following enumeration: 5067/// @code 5068/// enum PropertyAttributes { 5069/// kPropertyReadOnly = 'R', // property is read-only. 5070/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 5071/// kPropertyByref = '&', // property is a reference to the value last assigned 5072/// kPropertyDynamic = 'D', // property is dynamic 5073/// kPropertyGetter = 'G', // followed by getter selector name 5074/// kPropertySetter = 'S', // followed by setter selector name 5075/// kPropertyInstanceVariable = 'V' // followed by instance variable name 5076/// kPropertyType = 'T' // followed by old-style type encoding. 5077/// kPropertyWeak = 'W' // 'weak' property 5078/// kPropertyStrong = 'P' // property GC'able 5079/// kPropertyNonAtomic = 'N' // property non-atomic 5080/// }; 5081/// @endcode 5082void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 5083 const Decl *Container, 5084 std::string& S) const { 5085 // Collect information from the property implementation decl(s). 5086 bool Dynamic = false; 5087 ObjCPropertyImplDecl *SynthesizePID = nullptr; 5088 5089 if (ObjCPropertyImplDecl *PropertyImpDecl = 5090 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 5091 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 5092 Dynamic = true; 5093 else 5094 SynthesizePID = PropertyImpDecl; 5095 } 5096 5097 // FIXME: This is not very efficient. 5098 S = "T"; 5099 5100 // Encode result type. 5101 // GCC has some special rules regarding encoding of properties which 5102 // closely resembles encoding of ivars. 5103 getObjCEncodingForPropertyType(PD->getType(), S); 5104 5105 if (PD->isReadOnly()) { 5106 S += ",R"; 5107 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) 5108 S += ",C"; 5109 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) 5110 S += ",&"; 5111 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 5112 S += ",W"; 5113 } else { 5114 switch (PD->getSetterKind()) { 5115 case ObjCPropertyDecl::Assign: break; 5116 case ObjCPropertyDecl::Copy: S += ",C"; break; 5117 case ObjCPropertyDecl::Retain: S += ",&"; break; 5118 case ObjCPropertyDecl::Weak: S += ",W"; break; 5119 } 5120 } 5121 5122 // It really isn't clear at all what this means, since properties 5123 // are "dynamic by default". 5124 if (Dynamic) 5125 S += ",D"; 5126 5127 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 5128 S += ",N"; 5129 5130 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 5131 S += ",G"; 5132 S += PD->getGetterName().getAsString(); 5133 } 5134 5135 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 5136 S += ",S"; 5137 S += PD->getSetterName().getAsString(); 5138 } 5139 5140 if (SynthesizePID) { 5141 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 5142 S += ",V"; 5143 S += OID->getNameAsString(); 5144 } 5145 5146 // FIXME: OBJCGC: weak & strong 5147} 5148 5149/// getLegacyIntegralTypeEncoding - 5150/// Another legacy compatibility encoding: 32-bit longs are encoded as 5151/// 'l' or 'L' , but not always. For typedefs, we need to use 5152/// 'i' or 'I' instead if encoding a struct field, or a pointer! 5153/// 5154void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 5155 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 5156 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 5157 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 5158 PointeeTy = UnsignedIntTy; 5159 else 5160 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 5161 PointeeTy = IntTy; 5162 } 5163 } 5164} 5165 5166void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 5167 const FieldDecl *Field, 5168 QualType *NotEncodedT) const { 5169 // We follow the behavior of gcc, expanding structures which are 5170 // directly pointed to, and expanding embedded structures. Note that 5171 // these rules are sufficient to prevent recursive encoding of the 5172 // same type. 5173 getObjCEncodingForTypeImpl(T, S, true, true, Field, 5174 true /* outermost type */, false, false, 5175 false, false, false, NotEncodedT); 5176} 5177 5178void ASTContext::getObjCEncodingForPropertyType(QualType T, 5179 std::string& S) const { 5180 // Encode result type. 5181 // GCC has some special rules regarding encoding of properties which 5182 // closely resembles encoding of ivars. 5183 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 5184 true /* outermost type */, 5185 true /* encoding property */); 5186} 5187 5188static char getObjCEncodingForPrimitiveKind(const ASTContext *C, 5189 BuiltinType::Kind kind) { 5190 switch (kind) { 5191 case BuiltinType::Void: return 'v'; 5192 case BuiltinType::Bool: return 'B'; 5193 case BuiltinType::Char_U: 5194 case BuiltinType::UChar: return 'C'; 5195 case BuiltinType::Char16: 5196 case BuiltinType::UShort: return 'S'; 5197 case BuiltinType::Char32: 5198 case BuiltinType::UInt: return 'I'; 5199 case BuiltinType::ULong: 5200 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 5201 case BuiltinType::UInt128: return 'T'; 5202 case BuiltinType::ULongLong: return 'Q'; 5203 case BuiltinType::Char_S: 5204 case BuiltinType::SChar: return 'c'; 5205 case BuiltinType::Short: return 's'; 5206 case BuiltinType::WChar_S: 5207 case BuiltinType::WChar_U: 5208 case BuiltinType::Int: return 'i'; 5209 case BuiltinType::Long: 5210 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 5211 case BuiltinType::LongLong: return 'q'; 5212 case BuiltinType::Int128: return 't'; 5213 case BuiltinType::Float: return 'f'; 5214 case BuiltinType::Double: return 'd'; 5215 case BuiltinType::LongDouble: return 'D'; 5216 case BuiltinType::NullPtr: return '*'; // like char* 5217 5218 case BuiltinType::Half: 5219 // FIXME: potentially need @encodes for these! 5220 return ' '; 5221 5222 case BuiltinType::ObjCId: 5223 case BuiltinType::ObjCClass: 5224 case BuiltinType::ObjCSel: 5225 llvm_unreachable("@encoding ObjC primitive type"); 5226 5227 // OpenCL and placeholder types don't need @encodings. 5228 case BuiltinType::OCLImage1d: 5229 case BuiltinType::OCLImage1dArray: 5230 case BuiltinType::OCLImage1dBuffer: 5231 case BuiltinType::OCLImage2d: 5232 case BuiltinType::OCLImage2dArray: 5233 case BuiltinType::OCLImage3d: 5234 case BuiltinType::OCLEvent: 5235 case BuiltinType::OCLSampler: 5236 case BuiltinType::Dependent: 5237#define BUILTIN_TYPE(KIND, ID) 5238#define PLACEHOLDER_TYPE(KIND, ID) \ 5239 case BuiltinType::KIND: 5240#include "clang/AST/BuiltinTypes.def" 5241 llvm_unreachable("invalid builtin type for @encode"); 5242 } 5243 llvm_unreachable("invalid BuiltinType::Kind value"); 5244} 5245 5246static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 5247 EnumDecl *Enum = ET->getDecl(); 5248 5249 // The encoding of an non-fixed enum type is always 'i', regardless of size. 5250 if (!Enum->isFixed()) 5251 return 'i'; 5252 5253 // The encoding of a fixed enum type matches its fixed underlying type. 5254 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 5255 return getObjCEncodingForPrimitiveKind(C, BT->getKind()); 5256} 5257 5258static void EncodeBitField(const ASTContext *Ctx, std::string& S, 5259 QualType T, const FieldDecl *FD) { 5260 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 5261 S += 'b'; 5262 // The NeXT runtime encodes bit fields as b followed by the number of bits. 5263 // The GNU runtime requires more information; bitfields are encoded as b, 5264 // then the offset (in bits) of the first element, then the type of the 5265 // bitfield, then the size in bits. For example, in this structure: 5266 // 5267 // struct 5268 // { 5269 // int integer; 5270 // int flags:2; 5271 // }; 5272 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 5273 // runtime, but b32i2 for the GNU runtime. The reason for this extra 5274 // information is not especially sensible, but we're stuck with it for 5275 // compatibility with GCC, although providing it breaks anything that 5276 // actually uses runtime introspection and wants to work on both runtimes... 5277 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 5278 const RecordDecl *RD = FD->getParent(); 5279 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 5280 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 5281 if (const EnumType *ET = T->getAs<EnumType>()) 5282 S += ObjCEncodingForEnumType(Ctx, ET); 5283 else { 5284 const BuiltinType *BT = T->castAs<BuiltinType>(); 5285 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind()); 5286 } 5287 } 5288 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 5289} 5290 5291// FIXME: Use SmallString for accumulating string. 5292void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 5293 bool ExpandPointedToStructures, 5294 bool ExpandStructures, 5295 const FieldDecl *FD, 5296 bool OutermostType, 5297 bool EncodingProperty, 5298 bool StructField, 5299 bool EncodeBlockParameters, 5300 bool EncodeClassNames, 5301 bool EncodePointerToObjCTypedef, 5302 QualType *NotEncodedT) const { 5303 CanQualType CT = getCanonicalType(T); 5304 switch (CT->getTypeClass()) { 5305 case Type::Builtin: 5306 case Type::Enum: 5307 if (FD && FD->isBitField()) 5308 return EncodeBitField(this, S, T, FD); 5309 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT)) 5310 S += getObjCEncodingForPrimitiveKind(this, BT->getKind()); 5311 else 5312 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 5313 return; 5314 5315 case Type::Complex: { 5316 const ComplexType *CT = T->castAs<ComplexType>(); 5317 S += 'j'; 5318 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr); 5319 return; 5320 } 5321 5322 case Type::Atomic: { 5323 const AtomicType *AT = T->castAs<AtomicType>(); 5324 S += 'A'; 5325 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr); 5326 return; 5327 } 5328 5329 // encoding for pointer or reference types. 5330 case Type::Pointer: 5331 case Type::LValueReference: 5332 case Type::RValueReference: { 5333 QualType PointeeTy; 5334 if (isa<PointerType>(CT)) { 5335 const PointerType *PT = T->castAs<PointerType>(); 5336 if (PT->isObjCSelType()) { 5337 S += ':'; 5338 return; 5339 } 5340 PointeeTy = PT->getPointeeType(); 5341 } else { 5342 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 5343 } 5344 5345 bool isReadOnly = false; 5346 // For historical/compatibility reasons, the read-only qualifier of the 5347 // pointee gets emitted _before_ the '^'. The read-only qualifier of 5348 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 5349 // Also, do not emit the 'r' for anything but the outermost type! 5350 if (isa<TypedefType>(T.getTypePtr())) { 5351 if (OutermostType && T.isConstQualified()) { 5352 isReadOnly = true; 5353 S += 'r'; 5354 } 5355 } else if (OutermostType) { 5356 QualType P = PointeeTy; 5357 while (P->getAs<PointerType>()) 5358 P = P->getAs<PointerType>()->getPointeeType(); 5359 if (P.isConstQualified()) { 5360 isReadOnly = true; 5361 S += 'r'; 5362 } 5363 } 5364 if (isReadOnly) { 5365 // Another legacy compatibility encoding. Some ObjC qualifier and type 5366 // combinations need to be rearranged. 5367 // Rewrite "in const" from "nr" to "rn" 5368 if (StringRef(S).endswith("nr")) 5369 S.replace(S.end()-2, S.end(), "rn"); 5370 } 5371 5372 if (PointeeTy->isCharType()) { 5373 // char pointer types should be encoded as '*' unless it is a 5374 // type that has been typedef'd to 'BOOL'. 5375 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 5376 S += '*'; 5377 return; 5378 } 5379 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 5380 // GCC binary compat: Need to convert "struct objc_class *" to "#". 5381 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 5382 S += '#'; 5383 return; 5384 } 5385 // GCC binary compat: Need to convert "struct objc_object *" to "@". 5386 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 5387 S += '@'; 5388 return; 5389 } 5390 // fall through... 5391 } 5392 S += '^'; 5393 getLegacyIntegralTypeEncoding(PointeeTy); 5394 5395 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 5396 nullptr, false, false, false, false, false, false, 5397 NotEncodedT); 5398 return; 5399 } 5400 5401 case Type::ConstantArray: 5402 case Type::IncompleteArray: 5403 case Type::VariableArray: { 5404 const ArrayType *AT = cast<ArrayType>(CT); 5405 5406 if (isa<IncompleteArrayType>(AT) && !StructField) { 5407 // Incomplete arrays are encoded as a pointer to the array element. 5408 S += '^'; 5409 5410 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5411 false, ExpandStructures, FD); 5412 } else { 5413 S += '['; 5414 5415 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 5416 S += llvm::utostr(CAT->getSize().getZExtValue()); 5417 else { 5418 //Variable length arrays are encoded as a regular array with 0 elements. 5419 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 5420 "Unknown array type!"); 5421 S += '0'; 5422 } 5423 5424 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5425 false, ExpandStructures, FD, 5426 false, false, false, false, false, false, 5427 NotEncodedT); 5428 S += ']'; 5429 } 5430 return; 5431 } 5432 5433 case Type::FunctionNoProto: 5434 case Type::FunctionProto: 5435 S += '?'; 5436 return; 5437 5438 case Type::Record: { 5439 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 5440 S += RDecl->isUnion() ? '(' : '{'; 5441 // Anonymous structures print as '?' 5442 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 5443 S += II->getName(); 5444 if (ClassTemplateSpecializationDecl *Spec 5445 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 5446 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 5447 llvm::raw_string_ostream OS(S); 5448 TemplateSpecializationType::PrintTemplateArgumentList(OS, 5449 TemplateArgs.data(), 5450 TemplateArgs.size(), 5451 (*this).getPrintingPolicy()); 5452 } 5453 } else { 5454 S += '?'; 5455 } 5456 if (ExpandStructures) { 5457 S += '='; 5458 if (!RDecl->isUnion()) { 5459 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 5460 } else { 5461 for (const auto *Field : RDecl->fields()) { 5462 if (FD) { 5463 S += '"'; 5464 S += Field->getNameAsString(); 5465 S += '"'; 5466 } 5467 5468 // Special case bit-fields. 5469 if (Field->isBitField()) { 5470 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 5471 Field); 5472 } else { 5473 QualType qt = Field->getType(); 5474 getLegacyIntegralTypeEncoding(qt); 5475 getObjCEncodingForTypeImpl(qt, S, false, true, 5476 FD, /*OutermostType*/false, 5477 /*EncodingProperty*/false, 5478 /*StructField*/true, 5479 false, false, false, NotEncodedT); 5480 } 5481 } 5482 } 5483 } 5484 S += RDecl->isUnion() ? ')' : '}'; 5485 return; 5486 } 5487 5488 case Type::BlockPointer: { 5489 const BlockPointerType *BT = T->castAs<BlockPointerType>(); 5490 S += "@?"; // Unlike a pointer-to-function, which is "^?". 5491 if (EncodeBlockParameters) { 5492 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>(); 5493 5494 S += '<'; 5495 // Block return type 5496 getObjCEncodingForTypeImpl( 5497 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures, 5498 FD, false /* OutermostType */, EncodingProperty, 5499 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false, 5500 NotEncodedT); 5501 // Block self 5502 S += "@?"; 5503 // Block parameters 5504 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 5505 for (const auto &I : FPT->param_types()) 5506 getObjCEncodingForTypeImpl( 5507 I, S, ExpandPointedToStructures, ExpandStructures, FD, 5508 false /* OutermostType */, EncodingProperty, 5509 false /* StructField */, EncodeBlockParameters, EncodeClassNames, 5510 false, NotEncodedT); 5511 } 5512 S += '>'; 5513 } 5514 return; 5515 } 5516 5517 case Type::ObjCObject: { 5518 // hack to match legacy encoding of *id and *Class 5519 QualType Ty = getObjCObjectPointerType(CT); 5520 if (Ty->isObjCIdType()) { 5521 S += "{objc_object=}"; 5522 return; 5523 } 5524 else if (Ty->isObjCClassType()) { 5525 S += "{objc_class=}"; 5526 return; 5527 } 5528 } 5529 5530 case Type::ObjCInterface: { 5531 // Ignore protocol qualifiers when mangling at this level. 5532 T = T->castAs<ObjCObjectType>()->getBaseType(); 5533 5534 // The assumption seems to be that this assert will succeed 5535 // because nested levels will have filtered out 'id' and 'Class'. 5536 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>(); 5537 // @encode(class_name) 5538 ObjCInterfaceDecl *OI = OIT->getDecl(); 5539 S += '{'; 5540 const IdentifierInfo *II = OI->getIdentifier(); 5541 S += II->getName(); 5542 S += '='; 5543 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5544 DeepCollectObjCIvars(OI, true, Ivars); 5545 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 5546 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 5547 if (Field->isBitField()) 5548 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 5549 else 5550 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD, 5551 false, false, false, false, false, 5552 EncodePointerToObjCTypedef, 5553 NotEncodedT); 5554 } 5555 S += '}'; 5556 return; 5557 } 5558 5559 case Type::ObjCObjectPointer: { 5560 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>(); 5561 if (OPT->isObjCIdType()) { 5562 S += '@'; 5563 return; 5564 } 5565 5566 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 5567 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 5568 // Since this is a binary compatibility issue, need to consult with runtime 5569 // folks. Fortunately, this is a *very* obsure construct. 5570 S += '#'; 5571 return; 5572 } 5573 5574 if (OPT->isObjCQualifiedIdType()) { 5575 getObjCEncodingForTypeImpl(getObjCIdType(), S, 5576 ExpandPointedToStructures, 5577 ExpandStructures, FD); 5578 if (FD || EncodingProperty || EncodeClassNames) { 5579 // Note that we do extended encoding of protocol qualifer list 5580 // Only when doing ivar or property encoding. 5581 S += '"'; 5582 for (const auto *I : OPT->quals()) { 5583 S += '<'; 5584 S += I->getNameAsString(); 5585 S += '>'; 5586 } 5587 S += '"'; 5588 } 5589 return; 5590 } 5591 5592 QualType PointeeTy = OPT->getPointeeType(); 5593 if (!EncodingProperty && 5594 isa<TypedefType>(PointeeTy.getTypePtr()) && 5595 !EncodePointerToObjCTypedef) { 5596 // Another historical/compatibility reason. 5597 // We encode the underlying type which comes out as 5598 // {...}; 5599 S += '^'; 5600 if (FD && OPT->getInterfaceDecl()) { 5601 // Prevent recursive encoding of fields in some rare cases. 5602 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl(); 5603 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5604 DeepCollectObjCIvars(OI, true, Ivars); 5605 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 5606 if (cast<FieldDecl>(Ivars[i]) == FD) { 5607 S += '{'; 5608 S += OI->getIdentifier()->getName(); 5609 S += '}'; 5610 return; 5611 } 5612 } 5613 } 5614 getObjCEncodingForTypeImpl(PointeeTy, S, 5615 false, ExpandPointedToStructures, 5616 nullptr, 5617 false, false, false, false, false, 5618 /*EncodePointerToObjCTypedef*/true); 5619 return; 5620 } 5621 5622 S += '@'; 5623 if (OPT->getInterfaceDecl() && 5624 (FD || EncodingProperty || EncodeClassNames)) { 5625 S += '"'; 5626 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 5627 for (const auto *I : OPT->quals()) { 5628 S += '<'; 5629 S += I->getNameAsString(); 5630 S += '>'; 5631 } 5632 S += '"'; 5633 } 5634 return; 5635 } 5636 5637 // gcc just blithely ignores member pointers. 5638 // FIXME: we shoul do better than that. 'M' is available. 5639 case Type::MemberPointer: 5640 // This matches gcc's encoding, even though technically it is insufficient. 5641 //FIXME. We should do a better job than gcc. 5642 case Type::Vector: 5643 case Type::ExtVector: 5644 // Until we have a coherent encoding of these three types, issue warning. 5645 { if (NotEncodedT) 5646 *NotEncodedT = T; 5647 return; 5648 } 5649 5650 // We could see an undeduced auto type here during error recovery. 5651 // Just ignore it. 5652 case Type::Auto: 5653 return; 5654 5655 5656#define ABSTRACT_TYPE(KIND, BASE) 5657#define TYPE(KIND, BASE) 5658#define DEPENDENT_TYPE(KIND, BASE) \ 5659 case Type::KIND: 5660#define NON_CANONICAL_TYPE(KIND, BASE) \ 5661 case Type::KIND: 5662#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 5663 case Type::KIND: 5664#include "clang/AST/TypeNodes.def" 5665 llvm_unreachable("@encode for dependent type!"); 5666 } 5667 llvm_unreachable("bad type kind!"); 5668} 5669 5670void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 5671 std::string &S, 5672 const FieldDecl *FD, 5673 bool includeVBases, 5674 QualType *NotEncodedT) const { 5675 assert(RDecl && "Expected non-null RecordDecl"); 5676 assert(!RDecl->isUnion() && "Should not be called for unions"); 5677 if (!RDecl->getDefinition()) 5678 return; 5679 5680 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 5681 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 5682 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 5683 5684 if (CXXRec) { 5685 for (const auto &BI : CXXRec->bases()) { 5686 if (!BI.isVirtual()) { 5687 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 5688 if (base->isEmpty()) 5689 continue; 5690 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 5691 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5692 std::make_pair(offs, base)); 5693 } 5694 } 5695 } 5696 5697 unsigned i = 0; 5698 for (auto *Field : RDecl->fields()) { 5699 uint64_t offs = layout.getFieldOffset(i); 5700 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5701 std::make_pair(offs, Field)); 5702 ++i; 5703 } 5704 5705 if (CXXRec && includeVBases) { 5706 for (const auto &BI : CXXRec->vbases()) { 5707 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 5708 if (base->isEmpty()) 5709 continue; 5710 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 5711 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 5712 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 5713 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 5714 std::make_pair(offs, base)); 5715 } 5716 } 5717 5718 CharUnits size; 5719 if (CXXRec) { 5720 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 5721 } else { 5722 size = layout.getSize(); 5723 } 5724 5725#ifndef NDEBUG 5726 uint64_t CurOffs = 0; 5727#endif 5728 std::multimap<uint64_t, NamedDecl *>::iterator 5729 CurLayObj = FieldOrBaseOffsets.begin(); 5730 5731 if (CXXRec && CXXRec->isDynamicClass() && 5732 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 5733 if (FD) { 5734 S += "\"_vptr$"; 5735 std::string recname = CXXRec->getNameAsString(); 5736 if (recname.empty()) recname = "?"; 5737 S += recname; 5738 S += '"'; 5739 } 5740 S += "^^?"; 5741#ifndef NDEBUG 5742 CurOffs += getTypeSize(VoidPtrTy); 5743#endif 5744 } 5745 5746 if (!RDecl->hasFlexibleArrayMember()) { 5747 // Mark the end of the structure. 5748 uint64_t offs = toBits(size); 5749 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5750 std::make_pair(offs, nullptr)); 5751 } 5752 5753 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 5754#ifndef NDEBUG 5755 assert(CurOffs <= CurLayObj->first); 5756 if (CurOffs < CurLayObj->first) { 5757 uint64_t padding = CurLayObj->first - CurOffs; 5758 // FIXME: There doesn't seem to be a way to indicate in the encoding that 5759 // packing/alignment of members is different that normal, in which case 5760 // the encoding will be out-of-sync with the real layout. 5761 // If the runtime switches to just consider the size of types without 5762 // taking into account alignment, we could make padding explicit in the 5763 // encoding (e.g. using arrays of chars). The encoding strings would be 5764 // longer then though. 5765 CurOffs += padding; 5766 } 5767#endif 5768 5769 NamedDecl *dcl = CurLayObj->second; 5770 if (!dcl) 5771 break; // reached end of structure. 5772 5773 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 5774 // We expand the bases without their virtual bases since those are going 5775 // in the initial structure. Note that this differs from gcc which 5776 // expands virtual bases each time one is encountered in the hierarchy, 5777 // making the encoding type bigger than it really is. 5778 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 5779 NotEncodedT); 5780 assert(!base->isEmpty()); 5781#ifndef NDEBUG 5782 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 5783#endif 5784 } else { 5785 FieldDecl *field = cast<FieldDecl>(dcl); 5786 if (FD) { 5787 S += '"'; 5788 S += field->getNameAsString(); 5789 S += '"'; 5790 } 5791 5792 if (field->isBitField()) { 5793 EncodeBitField(this, S, field->getType(), field); 5794#ifndef NDEBUG 5795 CurOffs += field->getBitWidthValue(*this); 5796#endif 5797 } else { 5798 QualType qt = field->getType(); 5799 getLegacyIntegralTypeEncoding(qt); 5800 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 5801 /*OutermostType*/false, 5802 /*EncodingProperty*/false, 5803 /*StructField*/true, 5804 false, false, false, NotEncodedT); 5805#ifndef NDEBUG 5806 CurOffs += getTypeSize(field->getType()); 5807#endif 5808 } 5809 } 5810 } 5811} 5812 5813void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 5814 std::string& S) const { 5815 if (QT & Decl::OBJC_TQ_In) 5816 S += 'n'; 5817 if (QT & Decl::OBJC_TQ_Inout) 5818 S += 'N'; 5819 if (QT & Decl::OBJC_TQ_Out) 5820 S += 'o'; 5821 if (QT & Decl::OBJC_TQ_Bycopy) 5822 S += 'O'; 5823 if (QT & Decl::OBJC_TQ_Byref) 5824 S += 'R'; 5825 if (QT & Decl::OBJC_TQ_Oneway) 5826 S += 'V'; 5827} 5828 5829TypedefDecl *ASTContext::getObjCIdDecl() const { 5830 if (!ObjCIdDecl) { 5831 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0); 5832 T = getObjCObjectPointerType(T); 5833 ObjCIdDecl = buildImplicitTypedef(T, "id"); 5834 } 5835 return ObjCIdDecl; 5836} 5837 5838TypedefDecl *ASTContext::getObjCSelDecl() const { 5839 if (!ObjCSelDecl) { 5840 QualType T = getPointerType(ObjCBuiltinSelTy); 5841 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 5842 } 5843 return ObjCSelDecl; 5844} 5845 5846TypedefDecl *ASTContext::getObjCClassDecl() const { 5847 if (!ObjCClassDecl) { 5848 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0); 5849 T = getObjCObjectPointerType(T); 5850 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 5851 } 5852 return ObjCClassDecl; 5853} 5854 5855ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 5856 if (!ObjCProtocolClassDecl) { 5857 ObjCProtocolClassDecl 5858 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 5859 SourceLocation(), 5860 &Idents.get("Protocol"), 5861 /*PrevDecl=*/nullptr, 5862 SourceLocation(), true); 5863 } 5864 5865 return ObjCProtocolClassDecl; 5866} 5867 5868//===----------------------------------------------------------------------===// 5869// __builtin_va_list Construction Functions 5870//===----------------------------------------------------------------------===// 5871 5872static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 5873 // typedef char* __builtin_va_list; 5874 QualType T = Context->getPointerType(Context->CharTy); 5875 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 5876} 5877 5878static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 5879 // typedef void* __builtin_va_list; 5880 QualType T = Context->getPointerType(Context->VoidTy); 5881 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 5882} 5883 5884static TypedefDecl * 5885CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 5886 // struct __va_list 5887 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 5888 if (Context->getLangOpts().CPlusPlus) { 5889 // namespace std { struct __va_list { 5890 NamespaceDecl *NS; 5891 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 5892 Context->getTranslationUnitDecl(), 5893 /*Inline*/ false, SourceLocation(), 5894 SourceLocation(), &Context->Idents.get("std"), 5895 /*PrevDecl*/ nullptr); 5896 NS->setImplicit(); 5897 VaListTagDecl->setDeclContext(NS); 5898 } 5899 5900 VaListTagDecl->startDefinition(); 5901 5902 const size_t NumFields = 5; 5903 QualType FieldTypes[NumFields]; 5904 const char *FieldNames[NumFields]; 5905 5906 // void *__stack; 5907 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 5908 FieldNames[0] = "__stack"; 5909 5910 // void *__gr_top; 5911 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 5912 FieldNames[1] = "__gr_top"; 5913 5914 // void *__vr_top; 5915 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 5916 FieldNames[2] = "__vr_top"; 5917 5918 // int __gr_offs; 5919 FieldTypes[3] = Context->IntTy; 5920 FieldNames[3] = "__gr_offs"; 5921 5922 // int __vr_offs; 5923 FieldTypes[4] = Context->IntTy; 5924 FieldNames[4] = "__vr_offs"; 5925 5926 // Create fields 5927 for (unsigned i = 0; i < NumFields; ++i) { 5928 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 5929 VaListTagDecl, 5930 SourceLocation(), 5931 SourceLocation(), 5932 &Context->Idents.get(FieldNames[i]), 5933 FieldTypes[i], /*TInfo=*/nullptr, 5934 /*BitWidth=*/nullptr, 5935 /*Mutable=*/false, 5936 ICIS_NoInit); 5937 Field->setAccess(AS_public); 5938 VaListTagDecl->addDecl(Field); 5939 } 5940 VaListTagDecl->completeDefinition(); 5941 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5942 Context->VaListTagTy = VaListTagType; 5943 5944 // } __builtin_va_list; 5945 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 5946} 5947 5948static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 5949 // typedef struct __va_list_tag { 5950 RecordDecl *VaListTagDecl; 5951 5952 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 5953 VaListTagDecl->startDefinition(); 5954 5955 const size_t NumFields = 5; 5956 QualType FieldTypes[NumFields]; 5957 const char *FieldNames[NumFields]; 5958 5959 // unsigned char gpr; 5960 FieldTypes[0] = Context->UnsignedCharTy; 5961 FieldNames[0] = "gpr"; 5962 5963 // unsigned char fpr; 5964 FieldTypes[1] = Context->UnsignedCharTy; 5965 FieldNames[1] = "fpr"; 5966 5967 // unsigned short reserved; 5968 FieldTypes[2] = Context->UnsignedShortTy; 5969 FieldNames[2] = "reserved"; 5970 5971 // void* overflow_arg_area; 5972 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5973 FieldNames[3] = "overflow_arg_area"; 5974 5975 // void* reg_save_area; 5976 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 5977 FieldNames[4] = "reg_save_area"; 5978 5979 // Create fields 5980 for (unsigned i = 0; i < NumFields; ++i) { 5981 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 5982 SourceLocation(), 5983 SourceLocation(), 5984 &Context->Idents.get(FieldNames[i]), 5985 FieldTypes[i], /*TInfo=*/nullptr, 5986 /*BitWidth=*/nullptr, 5987 /*Mutable=*/false, 5988 ICIS_NoInit); 5989 Field->setAccess(AS_public); 5990 VaListTagDecl->addDecl(Field); 5991 } 5992 VaListTagDecl->completeDefinition(); 5993 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5994 Context->VaListTagTy = VaListTagType; 5995 5996 // } __va_list_tag; 5997 TypedefDecl *VaListTagTypedefDecl = 5998 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 5999 6000 QualType VaListTagTypedefType = 6001 Context->getTypedefType(VaListTagTypedefDecl); 6002 6003 // typedef __va_list_tag __builtin_va_list[1]; 6004 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6005 QualType VaListTagArrayType 6006 = Context->getConstantArrayType(VaListTagTypedefType, 6007 Size, ArrayType::Normal, 0); 6008 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6009} 6010 6011static TypedefDecl * 6012CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 6013 // typedef struct __va_list_tag { 6014 RecordDecl *VaListTagDecl; 6015 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6016 VaListTagDecl->startDefinition(); 6017 6018 const size_t NumFields = 4; 6019 QualType FieldTypes[NumFields]; 6020 const char *FieldNames[NumFields]; 6021 6022 // unsigned gp_offset; 6023 FieldTypes[0] = Context->UnsignedIntTy; 6024 FieldNames[0] = "gp_offset"; 6025 6026 // unsigned fp_offset; 6027 FieldTypes[1] = Context->UnsignedIntTy; 6028 FieldNames[1] = "fp_offset"; 6029 6030 // void* overflow_arg_area; 6031 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6032 FieldNames[2] = "overflow_arg_area"; 6033 6034 // void* reg_save_area; 6035 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6036 FieldNames[3] = "reg_save_area"; 6037 6038 // Create fields 6039 for (unsigned i = 0; i < NumFields; ++i) { 6040 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6041 VaListTagDecl, 6042 SourceLocation(), 6043 SourceLocation(), 6044 &Context->Idents.get(FieldNames[i]), 6045 FieldTypes[i], /*TInfo=*/nullptr, 6046 /*BitWidth=*/nullptr, 6047 /*Mutable=*/false, 6048 ICIS_NoInit); 6049 Field->setAccess(AS_public); 6050 VaListTagDecl->addDecl(Field); 6051 } 6052 VaListTagDecl->completeDefinition(); 6053 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6054 Context->VaListTagTy = VaListTagType; 6055 6056 // } __va_list_tag; 6057 TypedefDecl *VaListTagTypedefDecl = 6058 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6059 6060 QualType VaListTagTypedefType = 6061 Context->getTypedefType(VaListTagTypedefDecl); 6062 6063 // typedef __va_list_tag __builtin_va_list[1]; 6064 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6065 QualType VaListTagArrayType 6066 = Context->getConstantArrayType(VaListTagTypedefType, 6067 Size, ArrayType::Normal,0); 6068 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6069} 6070 6071static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 6072 // typedef int __builtin_va_list[4]; 6073 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 6074 QualType IntArrayType 6075 = Context->getConstantArrayType(Context->IntTy, 6076 Size, ArrayType::Normal, 0); 6077 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 6078} 6079 6080static TypedefDecl * 6081CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 6082 // struct __va_list 6083 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 6084 if (Context->getLangOpts().CPlusPlus) { 6085 // namespace std { struct __va_list { 6086 NamespaceDecl *NS; 6087 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 6088 Context->getTranslationUnitDecl(), 6089 /*Inline*/false, SourceLocation(), 6090 SourceLocation(), &Context->Idents.get("std"), 6091 /*PrevDecl*/ nullptr); 6092 NS->setImplicit(); 6093 VaListDecl->setDeclContext(NS); 6094 } 6095 6096 VaListDecl->startDefinition(); 6097 6098 // void * __ap; 6099 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6100 VaListDecl, 6101 SourceLocation(), 6102 SourceLocation(), 6103 &Context->Idents.get("__ap"), 6104 Context->getPointerType(Context->VoidTy), 6105 /*TInfo=*/nullptr, 6106 /*BitWidth=*/nullptr, 6107 /*Mutable=*/false, 6108 ICIS_NoInit); 6109 Field->setAccess(AS_public); 6110 VaListDecl->addDecl(Field); 6111 6112 // }; 6113 VaListDecl->completeDefinition(); 6114 6115 // typedef struct __va_list __builtin_va_list; 6116 QualType T = Context->getRecordType(VaListDecl); 6117 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 6118} 6119 6120static TypedefDecl * 6121CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 6122 // typedef struct __va_list_tag { 6123 RecordDecl *VaListTagDecl; 6124 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6125 VaListTagDecl->startDefinition(); 6126 6127 const size_t NumFields = 4; 6128 QualType FieldTypes[NumFields]; 6129 const char *FieldNames[NumFields]; 6130 6131 // long __gpr; 6132 FieldTypes[0] = Context->LongTy; 6133 FieldNames[0] = "__gpr"; 6134 6135 // long __fpr; 6136 FieldTypes[1] = Context->LongTy; 6137 FieldNames[1] = "__fpr"; 6138 6139 // void *__overflow_arg_area; 6140 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6141 FieldNames[2] = "__overflow_arg_area"; 6142 6143 // void *__reg_save_area; 6144 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6145 FieldNames[3] = "__reg_save_area"; 6146 6147 // Create fields 6148 for (unsigned i = 0; i < NumFields; ++i) { 6149 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6150 VaListTagDecl, 6151 SourceLocation(), 6152 SourceLocation(), 6153 &Context->Idents.get(FieldNames[i]), 6154 FieldTypes[i], /*TInfo=*/nullptr, 6155 /*BitWidth=*/nullptr, 6156 /*Mutable=*/false, 6157 ICIS_NoInit); 6158 Field->setAccess(AS_public); 6159 VaListTagDecl->addDecl(Field); 6160 } 6161 VaListTagDecl->completeDefinition(); 6162 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6163 Context->VaListTagTy = VaListTagType; 6164 6165 // } __va_list_tag; 6166 TypedefDecl *VaListTagTypedefDecl = 6167 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6168 QualType VaListTagTypedefType = 6169 Context->getTypedefType(VaListTagTypedefDecl); 6170 6171 // typedef __va_list_tag __builtin_va_list[1]; 6172 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6173 QualType VaListTagArrayType 6174 = Context->getConstantArrayType(VaListTagTypedefType, 6175 Size, ArrayType::Normal,0); 6176 6177 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6178} 6179 6180static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 6181 TargetInfo::BuiltinVaListKind Kind) { 6182 switch (Kind) { 6183 case TargetInfo::CharPtrBuiltinVaList: 6184 return CreateCharPtrBuiltinVaListDecl(Context); 6185 case TargetInfo::VoidPtrBuiltinVaList: 6186 return CreateVoidPtrBuiltinVaListDecl(Context); 6187 case TargetInfo::AArch64ABIBuiltinVaList: 6188 return CreateAArch64ABIBuiltinVaListDecl(Context); 6189 case TargetInfo::PowerABIBuiltinVaList: 6190 return CreatePowerABIBuiltinVaListDecl(Context); 6191 case TargetInfo::X86_64ABIBuiltinVaList: 6192 return CreateX86_64ABIBuiltinVaListDecl(Context); 6193 case TargetInfo::PNaClABIBuiltinVaList: 6194 return CreatePNaClABIBuiltinVaListDecl(Context); 6195 case TargetInfo::AAPCSABIBuiltinVaList: 6196 return CreateAAPCSABIBuiltinVaListDecl(Context); 6197 case TargetInfo::SystemZBuiltinVaList: 6198 return CreateSystemZBuiltinVaListDecl(Context); 6199 } 6200 6201 llvm_unreachable("Unhandled __builtin_va_list type kind"); 6202} 6203 6204TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 6205 if (!BuiltinVaListDecl) { 6206 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 6207 assert(BuiltinVaListDecl->isImplicit()); 6208 } 6209 6210 return BuiltinVaListDecl; 6211} 6212 6213QualType ASTContext::getVaListTagType() const { 6214 // Force the creation of VaListTagTy by building the __builtin_va_list 6215 // declaration. 6216 if (VaListTagTy.isNull()) 6217 (void) getBuiltinVaListDecl(); 6218 6219 return VaListTagTy; 6220} 6221 6222void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 6223 assert(ObjCConstantStringType.isNull() && 6224 "'NSConstantString' type already set!"); 6225 6226 ObjCConstantStringType = getObjCInterfaceType(Decl); 6227} 6228 6229/// \brief Retrieve the template name that corresponds to a non-empty 6230/// lookup. 6231TemplateName 6232ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 6233 UnresolvedSetIterator End) const { 6234 unsigned size = End - Begin; 6235 assert(size > 1 && "set is not overloaded!"); 6236 6237 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 6238 size * sizeof(FunctionTemplateDecl*)); 6239 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 6240 6241 NamedDecl **Storage = OT->getStorage(); 6242 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 6243 NamedDecl *D = *I; 6244 assert(isa<FunctionTemplateDecl>(D) || 6245 (isa<UsingShadowDecl>(D) && 6246 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 6247 *Storage++ = D; 6248 } 6249 6250 return TemplateName(OT); 6251} 6252 6253/// \brief Retrieve the template name that represents a qualified 6254/// template name such as \c std::vector. 6255TemplateName 6256ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 6257 bool TemplateKeyword, 6258 TemplateDecl *Template) const { 6259 assert(NNS && "Missing nested-name-specifier in qualified template name"); 6260 6261 // FIXME: Canonicalization? 6262 llvm::FoldingSetNodeID ID; 6263 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 6264 6265 void *InsertPos = nullptr; 6266 QualifiedTemplateName *QTN = 6267 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6268 if (!QTN) { 6269 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>()) 6270 QualifiedTemplateName(NNS, TemplateKeyword, Template); 6271 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 6272 } 6273 6274 return TemplateName(QTN); 6275} 6276 6277/// \brief Retrieve the template name that represents a dependent 6278/// template name such as \c MetaFun::template apply. 6279TemplateName 6280ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 6281 const IdentifierInfo *Name) const { 6282 assert((!NNS || NNS->isDependent()) && 6283 "Nested name specifier must be dependent"); 6284 6285 llvm::FoldingSetNodeID ID; 6286 DependentTemplateName::Profile(ID, NNS, Name); 6287 6288 void *InsertPos = nullptr; 6289 DependentTemplateName *QTN = 6290 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6291 6292 if (QTN) 6293 return TemplateName(QTN); 6294 6295 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 6296 if (CanonNNS == NNS) { 6297 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6298 DependentTemplateName(NNS, Name); 6299 } else { 6300 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 6301 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6302 DependentTemplateName(NNS, Name, Canon); 6303 DependentTemplateName *CheckQTN = 6304 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6305 assert(!CheckQTN && "Dependent type name canonicalization broken"); 6306 (void)CheckQTN; 6307 } 6308 6309 DependentTemplateNames.InsertNode(QTN, InsertPos); 6310 return TemplateName(QTN); 6311} 6312 6313/// \brief Retrieve the template name that represents a dependent 6314/// template name such as \c MetaFun::template operator+. 6315TemplateName 6316ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 6317 OverloadedOperatorKind Operator) const { 6318 assert((!NNS || NNS->isDependent()) && 6319 "Nested name specifier must be dependent"); 6320 6321 llvm::FoldingSetNodeID ID; 6322 DependentTemplateName::Profile(ID, NNS, Operator); 6323 6324 void *InsertPos = nullptr; 6325 DependentTemplateName *QTN 6326 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6327 6328 if (QTN) 6329 return TemplateName(QTN); 6330 6331 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 6332 if (CanonNNS == NNS) { 6333 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6334 DependentTemplateName(NNS, Operator); 6335 } else { 6336 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 6337 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6338 DependentTemplateName(NNS, Operator, Canon); 6339 6340 DependentTemplateName *CheckQTN 6341 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6342 assert(!CheckQTN && "Dependent template name canonicalization broken"); 6343 (void)CheckQTN; 6344 } 6345 6346 DependentTemplateNames.InsertNode(QTN, InsertPos); 6347 return TemplateName(QTN); 6348} 6349 6350TemplateName 6351ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 6352 TemplateName replacement) const { 6353 llvm::FoldingSetNodeID ID; 6354 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 6355 6356 void *insertPos = nullptr; 6357 SubstTemplateTemplateParmStorage *subst 6358 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 6359 6360 if (!subst) { 6361 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 6362 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 6363 } 6364 6365 return TemplateName(subst); 6366} 6367 6368TemplateName 6369ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 6370 const TemplateArgument &ArgPack) const { 6371 ASTContext &Self = const_cast<ASTContext &>(*this); 6372 llvm::FoldingSetNodeID ID; 6373 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 6374 6375 void *InsertPos = nullptr; 6376 SubstTemplateTemplateParmPackStorage *Subst 6377 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 6378 6379 if (!Subst) { 6380 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 6381 ArgPack.pack_size(), 6382 ArgPack.pack_begin()); 6383 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 6384 } 6385 6386 return TemplateName(Subst); 6387} 6388 6389/// getFromTargetType - Given one of the integer types provided by 6390/// TargetInfo, produce the corresponding type. The unsigned @p Type 6391/// is actually a value of type @c TargetInfo::IntType. 6392CanQualType ASTContext::getFromTargetType(unsigned Type) const { 6393 switch (Type) { 6394 case TargetInfo::NoInt: return CanQualType(); 6395 case TargetInfo::SignedChar: return SignedCharTy; 6396 case TargetInfo::UnsignedChar: return UnsignedCharTy; 6397 case TargetInfo::SignedShort: return ShortTy; 6398 case TargetInfo::UnsignedShort: return UnsignedShortTy; 6399 case TargetInfo::SignedInt: return IntTy; 6400 case TargetInfo::UnsignedInt: return UnsignedIntTy; 6401 case TargetInfo::SignedLong: return LongTy; 6402 case TargetInfo::UnsignedLong: return UnsignedLongTy; 6403 case TargetInfo::SignedLongLong: return LongLongTy; 6404 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 6405 } 6406 6407 llvm_unreachable("Unhandled TargetInfo::IntType value"); 6408} 6409 6410//===----------------------------------------------------------------------===// 6411// Type Predicates. 6412//===----------------------------------------------------------------------===// 6413 6414/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 6415/// garbage collection attribute. 6416/// 6417Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 6418 if (getLangOpts().getGC() == LangOptions::NonGC) 6419 return Qualifiers::GCNone; 6420 6421 assert(getLangOpts().ObjC1); 6422 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 6423 6424 // Default behaviour under objective-C's gc is for ObjC pointers 6425 // (or pointers to them) be treated as though they were declared 6426 // as __strong. 6427 if (GCAttrs == Qualifiers::GCNone) { 6428 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 6429 return Qualifiers::Strong; 6430 else if (Ty->isPointerType()) 6431 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 6432 } else { 6433 // It's not valid to set GC attributes on anything that isn't a 6434 // pointer. 6435#ifndef NDEBUG 6436 QualType CT = Ty->getCanonicalTypeInternal(); 6437 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 6438 CT = AT->getElementType(); 6439 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 6440#endif 6441 } 6442 return GCAttrs; 6443} 6444 6445//===----------------------------------------------------------------------===// 6446// Type Compatibility Testing 6447//===----------------------------------------------------------------------===// 6448 6449/// areCompatVectorTypes - Return true if the two specified vector types are 6450/// compatible. 6451static bool areCompatVectorTypes(const VectorType *LHS, 6452 const VectorType *RHS) { 6453 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 6454 return LHS->getElementType() == RHS->getElementType() && 6455 LHS->getNumElements() == RHS->getNumElements(); 6456} 6457 6458bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 6459 QualType SecondVec) { 6460 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 6461 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 6462 6463 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 6464 return true; 6465 6466 // Treat Neon vector types and most AltiVec vector types as if they are the 6467 // equivalent GCC vector types. 6468 const VectorType *First = FirstVec->getAs<VectorType>(); 6469 const VectorType *Second = SecondVec->getAs<VectorType>(); 6470 if (First->getNumElements() == Second->getNumElements() && 6471 hasSameType(First->getElementType(), Second->getElementType()) && 6472 First->getVectorKind() != VectorType::AltiVecPixel && 6473 First->getVectorKind() != VectorType::AltiVecBool && 6474 Second->getVectorKind() != VectorType::AltiVecPixel && 6475 Second->getVectorKind() != VectorType::AltiVecBool) 6476 return true; 6477 6478 return false; 6479} 6480 6481//===----------------------------------------------------------------------===// 6482// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 6483//===----------------------------------------------------------------------===// 6484 6485/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 6486/// inheritance hierarchy of 'rProto'. 6487bool 6488ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 6489 ObjCProtocolDecl *rProto) const { 6490 if (declaresSameEntity(lProto, rProto)) 6491 return true; 6492 for (auto *PI : rProto->protocols()) 6493 if (ProtocolCompatibleWithProtocol(lProto, PI)) 6494 return true; 6495 return false; 6496} 6497 6498/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 6499/// Class<pr1, ...>. 6500bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 6501 QualType rhs) { 6502 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 6503 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 6504 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 6505 6506 for (auto *lhsProto : lhsQID->quals()) { 6507 bool match = false; 6508 for (auto *rhsProto : rhsOPT->quals()) { 6509 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 6510 match = true; 6511 break; 6512 } 6513 } 6514 if (!match) 6515 return false; 6516 } 6517 return true; 6518} 6519 6520/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 6521/// ObjCQualifiedIDType. 6522bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 6523 bool compare) { 6524 // Allow id<P..> and an 'id' or void* type in all cases. 6525 if (lhs->isVoidPointerType() || 6526 lhs->isObjCIdType() || lhs->isObjCClassType()) 6527 return true; 6528 else if (rhs->isVoidPointerType() || 6529 rhs->isObjCIdType() || rhs->isObjCClassType()) 6530 return true; 6531 6532 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 6533 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 6534 6535 if (!rhsOPT) return false; 6536 6537 if (rhsOPT->qual_empty()) { 6538 // If the RHS is a unqualified interface pointer "NSString*", 6539 // make sure we check the class hierarchy. 6540 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 6541 for (auto *I : lhsQID->quals()) { 6542 // when comparing an id<P> on lhs with a static type on rhs, 6543 // see if static class implements all of id's protocols, directly or 6544 // through its super class and categories. 6545 if (!rhsID->ClassImplementsProtocol(I, true)) 6546 return false; 6547 } 6548 } 6549 // If there are no qualifiers and no interface, we have an 'id'. 6550 return true; 6551 } 6552 // Both the right and left sides have qualifiers. 6553 for (auto *lhsProto : lhsQID->quals()) { 6554 bool match = false; 6555 6556 // when comparing an id<P> on lhs with a static type on rhs, 6557 // see if static class implements all of id's protocols, directly or 6558 // through its super class and categories. 6559 for (auto *rhsProto : rhsOPT->quals()) { 6560 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6561 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6562 match = true; 6563 break; 6564 } 6565 } 6566 // If the RHS is a qualified interface pointer "NSString<P>*", 6567 // make sure we check the class hierarchy. 6568 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 6569 for (auto *I : lhsQID->quals()) { 6570 // when comparing an id<P> on lhs with a static type on rhs, 6571 // see if static class implements all of id's protocols, directly or 6572 // through its super class and categories. 6573 if (rhsID->ClassImplementsProtocol(I, true)) { 6574 match = true; 6575 break; 6576 } 6577 } 6578 } 6579 if (!match) 6580 return false; 6581 } 6582 6583 return true; 6584 } 6585 6586 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 6587 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 6588 6589 if (const ObjCObjectPointerType *lhsOPT = 6590 lhs->getAsObjCInterfacePointerType()) { 6591 // If both the right and left sides have qualifiers. 6592 for (auto *lhsProto : lhsOPT->quals()) { 6593 bool match = false; 6594 6595 // when comparing an id<P> on rhs with a static type on lhs, 6596 // see if static class implements all of id's protocols, directly or 6597 // through its super class and categories. 6598 // First, lhs protocols in the qualifier list must be found, direct 6599 // or indirect in rhs's qualifier list or it is a mismatch. 6600 for (auto *rhsProto : rhsQID->quals()) { 6601 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6602 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6603 match = true; 6604 break; 6605 } 6606 } 6607 if (!match) 6608 return false; 6609 } 6610 6611 // Static class's protocols, or its super class or category protocols 6612 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 6613 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 6614 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 6615 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 6616 // This is rather dubious but matches gcc's behavior. If lhs has 6617 // no type qualifier and its class has no static protocol(s) 6618 // assume that it is mismatch. 6619 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 6620 return false; 6621 for (auto *lhsProto : LHSInheritedProtocols) { 6622 bool match = false; 6623 for (auto *rhsProto : rhsQID->quals()) { 6624 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6625 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6626 match = true; 6627 break; 6628 } 6629 } 6630 if (!match) 6631 return false; 6632 } 6633 } 6634 return true; 6635 } 6636 return false; 6637} 6638 6639/// canAssignObjCInterfaces - Return true if the two interface types are 6640/// compatible for assignment from RHS to LHS. This handles validation of any 6641/// protocol qualifiers on the LHS or RHS. 6642/// 6643bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 6644 const ObjCObjectPointerType *RHSOPT) { 6645 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 6646 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 6647 6648 // If either type represents the built-in 'id' or 'Class' types, return true. 6649 if (LHS->isObjCUnqualifiedIdOrClass() || 6650 RHS->isObjCUnqualifiedIdOrClass()) 6651 return true; 6652 6653 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 6654 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 6655 QualType(RHSOPT,0), 6656 false); 6657 6658 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 6659 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 6660 QualType(RHSOPT,0)); 6661 6662 // If we have 2 user-defined types, fall into that path. 6663 if (LHS->getInterface() && RHS->getInterface()) 6664 return canAssignObjCInterfaces(LHS, RHS); 6665 6666 return false; 6667} 6668 6669/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 6670/// for providing type-safety for objective-c pointers used to pass/return 6671/// arguments in block literals. When passed as arguments, passing 'A*' where 6672/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 6673/// not OK. For the return type, the opposite is not OK. 6674bool ASTContext::canAssignObjCInterfacesInBlockPointer( 6675 const ObjCObjectPointerType *LHSOPT, 6676 const ObjCObjectPointerType *RHSOPT, 6677 bool BlockReturnType) { 6678 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 6679 return true; 6680 6681 if (LHSOPT->isObjCBuiltinType()) { 6682 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 6683 } 6684 6685 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 6686 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 6687 QualType(RHSOPT,0), 6688 false); 6689 6690 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 6691 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 6692 if (LHS && RHS) { // We have 2 user-defined types. 6693 if (LHS != RHS) { 6694 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 6695 return BlockReturnType; 6696 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 6697 return !BlockReturnType; 6698 } 6699 else 6700 return true; 6701 } 6702 return false; 6703} 6704 6705/// getIntersectionOfProtocols - This routine finds the intersection of set 6706/// of protocols inherited from two distinct objective-c pointer objects. 6707/// It is used to build composite qualifier list of the composite type of 6708/// the conditional expression involving two objective-c pointer objects. 6709static 6710void getIntersectionOfProtocols(ASTContext &Context, 6711 const ObjCObjectPointerType *LHSOPT, 6712 const ObjCObjectPointerType *RHSOPT, 6713 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 6714 6715 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 6716 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 6717 assert(LHS->getInterface() && "LHS must have an interface base"); 6718 assert(RHS->getInterface() && "RHS must have an interface base"); 6719 6720 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 6721 unsigned LHSNumProtocols = LHS->getNumProtocols(); 6722 if (LHSNumProtocols > 0) 6723 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 6724 else { 6725 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 6726 Context.CollectInheritedProtocols(LHS->getInterface(), 6727 LHSInheritedProtocols); 6728 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 6729 LHSInheritedProtocols.end()); 6730 } 6731 6732 unsigned RHSNumProtocols = RHS->getNumProtocols(); 6733 if (RHSNumProtocols > 0) { 6734 ObjCProtocolDecl **RHSProtocols = 6735 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 6736 for (unsigned i = 0; i < RHSNumProtocols; ++i) 6737 if (InheritedProtocolSet.count(RHSProtocols[i])) 6738 IntersectionOfProtocols.push_back(RHSProtocols[i]); 6739 } else { 6740 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 6741 Context.CollectInheritedProtocols(RHS->getInterface(), 6742 RHSInheritedProtocols); 6743 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols) 6744 if (InheritedProtocolSet.count(ProtDecl)) 6745 IntersectionOfProtocols.push_back(ProtDecl); 6746 } 6747} 6748 6749/// areCommonBaseCompatible - Returns common base class of the two classes if 6750/// one found. Note that this is O'2 algorithm. But it will be called as the 6751/// last type comparison in a ?-exp of ObjC pointer types before a 6752/// warning is issued. So, its invokation is extremely rare. 6753QualType ASTContext::areCommonBaseCompatible( 6754 const ObjCObjectPointerType *Lptr, 6755 const ObjCObjectPointerType *Rptr) { 6756 const ObjCObjectType *LHS = Lptr->getObjectType(); 6757 const ObjCObjectType *RHS = Rptr->getObjectType(); 6758 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 6759 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 6760 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl))) 6761 return QualType(); 6762 6763 do { 6764 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 6765 if (canAssignObjCInterfaces(LHS, RHS)) { 6766 SmallVector<ObjCProtocolDecl *, 8> Protocols; 6767 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 6768 6769 QualType Result = QualType(LHS, 0); 6770 if (!Protocols.empty()) 6771 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 6772 Result = getObjCObjectPointerType(Result); 6773 return Result; 6774 } 6775 } while ((LDecl = LDecl->getSuperClass())); 6776 6777 return QualType(); 6778} 6779 6780bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 6781 const ObjCObjectType *RHS) { 6782 assert(LHS->getInterface() && "LHS is not an interface type"); 6783 assert(RHS->getInterface() && "RHS is not an interface type"); 6784 6785 // Verify that the base decls are compatible: the RHS must be a subclass of 6786 // the LHS. 6787 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 6788 return false; 6789 6790 // RHS must have a superset of the protocols in the LHS. If the LHS is not 6791 // protocol qualified at all, then we are good. 6792 if (LHS->getNumProtocols() == 0) 6793 return true; 6794 6795 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not. 6796 // More detailed analysis is required. 6797 // OK, if LHS is same or a superclass of RHS *and* 6798 // this LHS, or as RHS's super class is assignment compatible with LHS. 6799 bool IsSuperClass = 6800 LHS->getInterface()->isSuperClassOf(RHS->getInterface()); 6801 if (IsSuperClass) { 6802 // OK if conversion of LHS to SuperClass results in narrowing of types 6803 // ; i.e., SuperClass may implement at least one of the protocols 6804 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 6805 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 6806 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 6807 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 6808 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 6809 // qualifiers. 6810 for (auto *RHSPI : RHS->quals()) 6811 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl()); 6812 // If there is no protocols associated with RHS, it is not a match. 6813 if (SuperClassInheritedProtocols.empty()) 6814 return false; 6815 6816 for (const auto *LHSProto : LHS->quals()) { 6817 bool SuperImplementsProtocol = false; 6818 for (auto *SuperClassProto : SuperClassInheritedProtocols) 6819 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 6820 SuperImplementsProtocol = true; 6821 break; 6822 } 6823 if (!SuperImplementsProtocol) 6824 return false; 6825 } 6826 return true; 6827 } 6828 return false; 6829} 6830 6831bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 6832 // get the "pointed to" types 6833 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 6834 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 6835 6836 if (!LHSOPT || !RHSOPT) 6837 return false; 6838 6839 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 6840 canAssignObjCInterfaces(RHSOPT, LHSOPT); 6841} 6842 6843bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 6844 return canAssignObjCInterfaces( 6845 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 6846 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 6847} 6848 6849/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 6850/// both shall have the identically qualified version of a compatible type. 6851/// C99 6.2.7p1: Two types have compatible types if their types are the 6852/// same. See 6.7.[2,3,5] for additional rules. 6853bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 6854 bool CompareUnqualified) { 6855 if (getLangOpts().CPlusPlus) 6856 return hasSameType(LHS, RHS); 6857 6858 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 6859} 6860 6861bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 6862 return typesAreCompatible(LHS, RHS); 6863} 6864 6865bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 6866 return !mergeTypes(LHS, RHS, true).isNull(); 6867} 6868 6869/// mergeTransparentUnionType - if T is a transparent union type and a member 6870/// of T is compatible with SubType, return the merged type, else return 6871/// QualType() 6872QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 6873 bool OfBlockPointer, 6874 bool Unqualified) { 6875 if (const RecordType *UT = T->getAsUnionType()) { 6876 RecordDecl *UD = UT->getDecl(); 6877 if (UD->hasAttr<TransparentUnionAttr>()) { 6878 for (const auto *I : UD->fields()) { 6879 QualType ET = I->getType().getUnqualifiedType(); 6880 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 6881 if (!MT.isNull()) 6882 return MT; 6883 } 6884 } 6885 } 6886 6887 return QualType(); 6888} 6889 6890/// mergeFunctionParameterTypes - merge two types which appear as function 6891/// parameter types 6892QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 6893 bool OfBlockPointer, 6894 bool Unqualified) { 6895 // GNU extension: two types are compatible if they appear as a function 6896 // argument, one of the types is a transparent union type and the other 6897 // type is compatible with a union member 6898 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 6899 Unqualified); 6900 if (!lmerge.isNull()) 6901 return lmerge; 6902 6903 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 6904 Unqualified); 6905 if (!rmerge.isNull()) 6906 return rmerge; 6907 6908 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 6909} 6910 6911QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 6912 bool OfBlockPointer, 6913 bool Unqualified) { 6914 const FunctionType *lbase = lhs->getAs<FunctionType>(); 6915 const FunctionType *rbase = rhs->getAs<FunctionType>(); 6916 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 6917 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 6918 bool allLTypes = true; 6919 bool allRTypes = true; 6920 6921 // Check return type 6922 QualType retType; 6923 if (OfBlockPointer) { 6924 QualType RHS = rbase->getReturnType(); 6925 QualType LHS = lbase->getReturnType(); 6926 bool UnqualifiedResult = Unqualified; 6927 if (!UnqualifiedResult) 6928 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 6929 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 6930 } 6931 else 6932 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 6933 Unqualified); 6934 if (retType.isNull()) return QualType(); 6935 6936 if (Unqualified) 6937 retType = retType.getUnqualifiedType(); 6938 6939 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 6940 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 6941 if (Unqualified) { 6942 LRetType = LRetType.getUnqualifiedType(); 6943 RRetType = RRetType.getUnqualifiedType(); 6944 } 6945 6946 if (getCanonicalType(retType) != LRetType) 6947 allLTypes = false; 6948 if (getCanonicalType(retType) != RRetType) 6949 allRTypes = false; 6950 6951 // FIXME: double check this 6952 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 6953 // rbase->getRegParmAttr() != 0 && 6954 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 6955 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 6956 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 6957 6958 // Compatible functions must have compatible calling conventions 6959 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 6960 return QualType(); 6961 6962 // Regparm is part of the calling convention. 6963 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 6964 return QualType(); 6965 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 6966 return QualType(); 6967 6968 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 6969 return QualType(); 6970 6971 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 6972 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 6973 6974 if (lbaseInfo.getNoReturn() != NoReturn) 6975 allLTypes = false; 6976 if (rbaseInfo.getNoReturn() != NoReturn) 6977 allRTypes = false; 6978 6979 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 6980 6981 if (lproto && rproto) { // two C99 style function prototypes 6982 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 6983 "C++ shouldn't be here"); 6984 // Compatible functions must have the same number of parameters 6985 if (lproto->getNumParams() != rproto->getNumParams()) 6986 return QualType(); 6987 6988 // Variadic and non-variadic functions aren't compatible 6989 if (lproto->isVariadic() != rproto->isVariadic()) 6990 return QualType(); 6991 6992 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 6993 return QualType(); 6994 6995 if (LangOpts.ObjCAutoRefCount && 6996 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto)) 6997 return QualType(); 6998 6999 // Check parameter type compatibility 7000 SmallVector<QualType, 10> types; 7001 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 7002 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 7003 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 7004 QualType paramType = mergeFunctionParameterTypes( 7005 lParamType, rParamType, OfBlockPointer, Unqualified); 7006 if (paramType.isNull()) 7007 return QualType(); 7008 7009 if (Unqualified) 7010 paramType = paramType.getUnqualifiedType(); 7011 7012 types.push_back(paramType); 7013 if (Unqualified) { 7014 lParamType = lParamType.getUnqualifiedType(); 7015 rParamType = rParamType.getUnqualifiedType(); 7016 } 7017 7018 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 7019 allLTypes = false; 7020 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 7021 allRTypes = false; 7022 } 7023 7024 if (allLTypes) return lhs; 7025 if (allRTypes) return rhs; 7026 7027 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 7028 EPI.ExtInfo = einfo; 7029 return getFunctionType(retType, types, EPI); 7030 } 7031 7032 if (lproto) allRTypes = false; 7033 if (rproto) allLTypes = false; 7034 7035 const FunctionProtoType *proto = lproto ? lproto : rproto; 7036 if (proto) { 7037 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 7038 if (proto->isVariadic()) return QualType(); 7039 // Check that the types are compatible with the types that 7040 // would result from default argument promotions (C99 6.7.5.3p15). 7041 // The only types actually affected are promotable integer 7042 // types and floats, which would be passed as a different 7043 // type depending on whether the prototype is visible. 7044 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 7045 QualType paramTy = proto->getParamType(i); 7046 7047 // Look at the converted type of enum types, since that is the type used 7048 // to pass enum values. 7049 if (const EnumType *Enum = paramTy->getAs<EnumType>()) { 7050 paramTy = Enum->getDecl()->getIntegerType(); 7051 if (paramTy.isNull()) 7052 return QualType(); 7053 } 7054 7055 if (paramTy->isPromotableIntegerType() || 7056 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 7057 return QualType(); 7058 } 7059 7060 if (allLTypes) return lhs; 7061 if (allRTypes) return rhs; 7062 7063 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 7064 EPI.ExtInfo = einfo; 7065 return getFunctionType(retType, proto->getParamTypes(), EPI); 7066 } 7067 7068 if (allLTypes) return lhs; 7069 if (allRTypes) return rhs; 7070 return getFunctionNoProtoType(retType, einfo); 7071} 7072 7073/// Given that we have an enum type and a non-enum type, try to merge them. 7074static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 7075 QualType other, bool isBlockReturnType) { 7076 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 7077 // a signed integer type, or an unsigned integer type. 7078 // Compatibility is based on the underlying type, not the promotion 7079 // type. 7080 QualType underlyingType = ET->getDecl()->getIntegerType(); 7081 if (underlyingType.isNull()) return QualType(); 7082 if (Context.hasSameType(underlyingType, other)) 7083 return other; 7084 7085 // In block return types, we're more permissive and accept any 7086 // integral type of the same size. 7087 if (isBlockReturnType && other->isIntegerType() && 7088 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 7089 return other; 7090 7091 return QualType(); 7092} 7093 7094QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 7095 bool OfBlockPointer, 7096 bool Unqualified, bool BlockReturnType) { 7097 // C++ [expr]: If an expression initially has the type "reference to T", the 7098 // type is adjusted to "T" prior to any further analysis, the expression 7099 // designates the object or function denoted by the reference, and the 7100 // expression is an lvalue unless the reference is an rvalue reference and 7101 // the expression is a function call (possibly inside parentheses). 7102 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 7103 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 7104 7105 if (Unqualified) { 7106 LHS = LHS.getUnqualifiedType(); 7107 RHS = RHS.getUnqualifiedType(); 7108 } 7109 7110 QualType LHSCan = getCanonicalType(LHS), 7111 RHSCan = getCanonicalType(RHS); 7112 7113 // If two types are identical, they are compatible. 7114 if (LHSCan == RHSCan) 7115 return LHS; 7116 7117 // If the qualifiers are different, the types aren't compatible... mostly. 7118 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 7119 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 7120 if (LQuals != RQuals) { 7121 // If any of these qualifiers are different, we have a type 7122 // mismatch. 7123 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 7124 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 7125 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 7126 return QualType(); 7127 7128 // Exactly one GC qualifier difference is allowed: __strong is 7129 // okay if the other type has no GC qualifier but is an Objective 7130 // C object pointer (i.e. implicitly strong by default). We fix 7131 // this by pretending that the unqualified type was actually 7132 // qualified __strong. 7133 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 7134 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 7135 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 7136 7137 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 7138 return QualType(); 7139 7140 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 7141 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 7142 } 7143 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 7144 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 7145 } 7146 return QualType(); 7147 } 7148 7149 // Okay, qualifiers are equal. 7150 7151 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 7152 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 7153 7154 // We want to consider the two function types to be the same for these 7155 // comparisons, just force one to the other. 7156 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 7157 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 7158 7159 // Same as above for arrays 7160 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 7161 LHSClass = Type::ConstantArray; 7162 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 7163 RHSClass = Type::ConstantArray; 7164 7165 // ObjCInterfaces are just specialized ObjCObjects. 7166 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 7167 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 7168 7169 // Canonicalize ExtVector -> Vector. 7170 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 7171 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 7172 7173 // If the canonical type classes don't match. 7174 if (LHSClass != RHSClass) { 7175 // Note that we only have special rules for turning block enum 7176 // returns into block int returns, not vice-versa. 7177 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 7178 return mergeEnumWithInteger(*this, ETy, RHS, false); 7179 } 7180 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 7181 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 7182 } 7183 // allow block pointer type to match an 'id' type. 7184 if (OfBlockPointer && !BlockReturnType) { 7185 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 7186 return LHS; 7187 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 7188 return RHS; 7189 } 7190 7191 return QualType(); 7192 } 7193 7194 // The canonical type classes match. 7195 switch (LHSClass) { 7196#define TYPE(Class, Base) 7197#define ABSTRACT_TYPE(Class, Base) 7198#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 7199#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 7200#define DEPENDENT_TYPE(Class, Base) case Type::Class: 7201#include "clang/AST/TypeNodes.def" 7202 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 7203 7204 case Type::Auto: 7205 case Type::LValueReference: 7206 case Type::RValueReference: 7207 case Type::MemberPointer: 7208 llvm_unreachable("C++ should never be in mergeTypes"); 7209 7210 case Type::ObjCInterface: 7211 case Type::IncompleteArray: 7212 case Type::VariableArray: 7213 case Type::FunctionProto: 7214 case Type::ExtVector: 7215 llvm_unreachable("Types are eliminated above"); 7216 7217 case Type::Pointer: 7218 { 7219 // Merge two pointer types, while trying to preserve typedef info 7220 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 7221 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 7222 if (Unqualified) { 7223 LHSPointee = LHSPointee.getUnqualifiedType(); 7224 RHSPointee = RHSPointee.getUnqualifiedType(); 7225 } 7226 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 7227 Unqualified); 7228 if (ResultType.isNull()) return QualType(); 7229 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 7230 return LHS; 7231 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 7232 return RHS; 7233 return getPointerType(ResultType); 7234 } 7235 case Type::BlockPointer: 7236 { 7237 // Merge two block pointer types, while trying to preserve typedef info 7238 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 7239 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 7240 if (Unqualified) { 7241 LHSPointee = LHSPointee.getUnqualifiedType(); 7242 RHSPointee = RHSPointee.getUnqualifiedType(); 7243 } 7244 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 7245 Unqualified); 7246 if (ResultType.isNull()) return QualType(); 7247 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 7248 return LHS; 7249 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 7250 return RHS; 7251 return getBlockPointerType(ResultType); 7252 } 7253 case Type::Atomic: 7254 { 7255 // Merge two pointer types, while trying to preserve typedef info 7256 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 7257 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 7258 if (Unqualified) { 7259 LHSValue = LHSValue.getUnqualifiedType(); 7260 RHSValue = RHSValue.getUnqualifiedType(); 7261 } 7262 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 7263 Unqualified); 7264 if (ResultType.isNull()) return QualType(); 7265 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 7266 return LHS; 7267 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 7268 return RHS; 7269 return getAtomicType(ResultType); 7270 } 7271 case Type::ConstantArray: 7272 { 7273 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 7274 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 7275 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 7276 return QualType(); 7277 7278 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 7279 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 7280 if (Unqualified) { 7281 LHSElem = LHSElem.getUnqualifiedType(); 7282 RHSElem = RHSElem.getUnqualifiedType(); 7283 } 7284 7285 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 7286 if (ResultType.isNull()) return QualType(); 7287 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 7288 return LHS; 7289 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 7290 return RHS; 7291 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 7292 ArrayType::ArraySizeModifier(), 0); 7293 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 7294 ArrayType::ArraySizeModifier(), 0); 7295 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 7296 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 7297 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 7298 return LHS; 7299 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 7300 return RHS; 7301 if (LVAT) { 7302 // FIXME: This isn't correct! But tricky to implement because 7303 // the array's size has to be the size of LHS, but the type 7304 // has to be different. 7305 return LHS; 7306 } 7307 if (RVAT) { 7308 // FIXME: This isn't correct! But tricky to implement because 7309 // the array's size has to be the size of RHS, but the type 7310 // has to be different. 7311 return RHS; 7312 } 7313 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 7314 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 7315 return getIncompleteArrayType(ResultType, 7316 ArrayType::ArraySizeModifier(), 0); 7317 } 7318 case Type::FunctionNoProto: 7319 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 7320 case Type::Record: 7321 case Type::Enum: 7322 return QualType(); 7323 case Type::Builtin: 7324 // Only exactly equal builtin types are compatible, which is tested above. 7325 return QualType(); 7326 case Type::Complex: 7327 // Distinct complex types are incompatible. 7328 return QualType(); 7329 case Type::Vector: 7330 // FIXME: The merged type should be an ExtVector! 7331 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 7332 RHSCan->getAs<VectorType>())) 7333 return LHS; 7334 return QualType(); 7335 case Type::ObjCObject: { 7336 // Check if the types are assignment compatible. 7337 // FIXME: This should be type compatibility, e.g. whether 7338 // "LHS x; RHS x;" at global scope is legal. 7339 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 7340 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 7341 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 7342 return LHS; 7343 7344 return QualType(); 7345 } 7346 case Type::ObjCObjectPointer: { 7347 if (OfBlockPointer) { 7348 if (canAssignObjCInterfacesInBlockPointer( 7349 LHS->getAs<ObjCObjectPointerType>(), 7350 RHS->getAs<ObjCObjectPointerType>(), 7351 BlockReturnType)) 7352 return LHS; 7353 return QualType(); 7354 } 7355 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 7356 RHS->getAs<ObjCObjectPointerType>())) 7357 return LHS; 7358 7359 return QualType(); 7360 } 7361 } 7362 7363 llvm_unreachable("Invalid Type::Class!"); 7364} 7365 7366bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs( 7367 const FunctionProtoType *FromFunctionType, 7368 const FunctionProtoType *ToFunctionType) { 7369 if (FromFunctionType->hasAnyConsumedParams() != 7370 ToFunctionType->hasAnyConsumedParams()) 7371 return false; 7372 FunctionProtoType::ExtProtoInfo FromEPI = 7373 FromFunctionType->getExtProtoInfo(); 7374 FunctionProtoType::ExtProtoInfo ToEPI = 7375 ToFunctionType->getExtProtoInfo(); 7376 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters) 7377 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) { 7378 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i]) 7379 return false; 7380 } 7381 return true; 7382} 7383 7384/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 7385/// 'RHS' attributes and returns the merged version; including for function 7386/// return types. 7387QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 7388 QualType LHSCan = getCanonicalType(LHS), 7389 RHSCan = getCanonicalType(RHS); 7390 // If two types are identical, they are compatible. 7391 if (LHSCan == RHSCan) 7392 return LHS; 7393 if (RHSCan->isFunctionType()) { 7394 if (!LHSCan->isFunctionType()) 7395 return QualType(); 7396 QualType OldReturnType = 7397 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 7398 QualType NewReturnType = 7399 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 7400 QualType ResReturnType = 7401 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 7402 if (ResReturnType.isNull()) 7403 return QualType(); 7404 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 7405 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 7406 // In either case, use OldReturnType to build the new function type. 7407 const FunctionType *F = LHS->getAs<FunctionType>(); 7408 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 7409 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7410 EPI.ExtInfo = getFunctionExtInfo(LHS); 7411 QualType ResultType = 7412 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 7413 return ResultType; 7414 } 7415 } 7416 return QualType(); 7417 } 7418 7419 // If the qualifiers are different, the types can still be merged. 7420 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 7421 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 7422 if (LQuals != RQuals) { 7423 // If any of these qualifiers are different, we have a type mismatch. 7424 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 7425 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 7426 return QualType(); 7427 7428 // Exactly one GC qualifier difference is allowed: __strong is 7429 // okay if the other type has no GC qualifier but is an Objective 7430 // C object pointer (i.e. implicitly strong by default). We fix 7431 // this by pretending that the unqualified type was actually 7432 // qualified __strong. 7433 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 7434 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 7435 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 7436 7437 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 7438 return QualType(); 7439 7440 if (GC_L == Qualifiers::Strong) 7441 return LHS; 7442 if (GC_R == Qualifiers::Strong) 7443 return RHS; 7444 return QualType(); 7445 } 7446 7447 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 7448 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 7449 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 7450 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 7451 if (ResQT == LHSBaseQT) 7452 return LHS; 7453 if (ResQT == RHSBaseQT) 7454 return RHS; 7455 } 7456 return QualType(); 7457} 7458 7459//===----------------------------------------------------------------------===// 7460// Integer Predicates 7461//===----------------------------------------------------------------------===// 7462 7463unsigned ASTContext::getIntWidth(QualType T) const { 7464 if (const EnumType *ET = T->getAs<EnumType>()) 7465 T = ET->getDecl()->getIntegerType(); 7466 if (T->isBooleanType()) 7467 return 1; 7468 // For builtin types, just use the standard type sizing method 7469 return (unsigned)getTypeSize(T); 7470} 7471 7472QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 7473 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 7474 7475 // Turn <4 x signed int> -> <4 x unsigned int> 7476 if (const VectorType *VTy = T->getAs<VectorType>()) 7477 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 7478 VTy->getNumElements(), VTy->getVectorKind()); 7479 7480 // For enums, we return the unsigned version of the base type. 7481 if (const EnumType *ETy = T->getAs<EnumType>()) 7482 T = ETy->getDecl()->getIntegerType(); 7483 7484 const BuiltinType *BTy = T->getAs<BuiltinType>(); 7485 assert(BTy && "Unexpected signed integer type"); 7486 switch (BTy->getKind()) { 7487 case BuiltinType::Char_S: 7488 case BuiltinType::SChar: 7489 return UnsignedCharTy; 7490 case BuiltinType::Short: 7491 return UnsignedShortTy; 7492 case BuiltinType::Int: 7493 return UnsignedIntTy; 7494 case BuiltinType::Long: 7495 return UnsignedLongTy; 7496 case BuiltinType::LongLong: 7497 return UnsignedLongLongTy; 7498 case BuiltinType::Int128: 7499 return UnsignedInt128Ty; 7500 default: 7501 llvm_unreachable("Unexpected signed integer type"); 7502 } 7503} 7504 7505ASTMutationListener::~ASTMutationListener() { } 7506 7507void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 7508 QualType ReturnType) {} 7509 7510//===----------------------------------------------------------------------===// 7511// Builtin Type Computation 7512//===----------------------------------------------------------------------===// 7513 7514/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 7515/// pointer over the consumed characters. This returns the resultant type. If 7516/// AllowTypeModifiers is false then modifier like * are not parsed, just basic 7517/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 7518/// a vector of "i*". 7519/// 7520/// RequiresICE is filled in on return to indicate whether the value is required 7521/// to be an Integer Constant Expression. 7522static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 7523 ASTContext::GetBuiltinTypeError &Error, 7524 bool &RequiresICE, 7525 bool AllowTypeModifiers) { 7526 // Modifiers. 7527 int HowLong = 0; 7528 bool Signed = false, Unsigned = false; 7529 RequiresICE = false; 7530 7531 // Read the prefixed modifiers first. 7532 bool Done = false; 7533 while (!Done) { 7534 switch (*Str++) { 7535 default: Done = true; --Str; break; 7536 case 'I': 7537 RequiresICE = true; 7538 break; 7539 case 'S': 7540 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 7541 assert(!Signed && "Can't use 'S' modifier multiple times!"); 7542 Signed = true; 7543 break; 7544 case 'U': 7545 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 7546 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 7547 Unsigned = true; 7548 break; 7549 case 'L': 7550 assert(HowLong <= 2 && "Can't have LLLL modifier"); 7551 ++HowLong; 7552 break; 7553 case 'W': 7554 // This modifier represents int64 type. 7555 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 7556 switch (Context.getTargetInfo().getInt64Type()) { 7557 default: 7558 llvm_unreachable("Unexpected integer type"); 7559 case TargetInfo::SignedLong: 7560 HowLong = 1; 7561 break; 7562 case TargetInfo::SignedLongLong: 7563 HowLong = 2; 7564 break; 7565 } 7566 } 7567 } 7568 7569 QualType Type; 7570 7571 // Read the base type. 7572 switch (*Str++) { 7573 default: llvm_unreachable("Unknown builtin type letter!"); 7574 case 'v': 7575 assert(HowLong == 0 && !Signed && !Unsigned && 7576 "Bad modifiers used with 'v'!"); 7577 Type = Context.VoidTy; 7578 break; 7579 case 'h': 7580 assert(HowLong == 0 && !Signed && !Unsigned && 7581 "Bad modifiers used with 'f'!"); 7582 Type = Context.HalfTy; 7583 break; 7584 case 'f': 7585 assert(HowLong == 0 && !Signed && !Unsigned && 7586 "Bad modifiers used with 'f'!"); 7587 Type = Context.FloatTy; 7588 break; 7589 case 'd': 7590 assert(HowLong < 2 && !Signed && !Unsigned && 7591 "Bad modifiers used with 'd'!"); 7592 if (HowLong) 7593 Type = Context.LongDoubleTy; 7594 else 7595 Type = Context.DoubleTy; 7596 break; 7597 case 's': 7598 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 7599 if (Unsigned) 7600 Type = Context.UnsignedShortTy; 7601 else 7602 Type = Context.ShortTy; 7603 break; 7604 case 'i': 7605 if (HowLong == 3) 7606 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 7607 else if (HowLong == 2) 7608 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 7609 else if (HowLong == 1) 7610 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 7611 else 7612 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 7613 break; 7614 case 'c': 7615 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 7616 if (Signed) 7617 Type = Context.SignedCharTy; 7618 else if (Unsigned) 7619 Type = Context.UnsignedCharTy; 7620 else 7621 Type = Context.CharTy; 7622 break; 7623 case 'b': // boolean 7624 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 7625 Type = Context.BoolTy; 7626 break; 7627 case 'z': // size_t. 7628 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 7629 Type = Context.getSizeType(); 7630 break; 7631 case 'F': 7632 Type = Context.getCFConstantStringType(); 7633 break; 7634 case 'G': 7635 Type = Context.getObjCIdType(); 7636 break; 7637 case 'H': 7638 Type = Context.getObjCSelType(); 7639 break; 7640 case 'M': 7641 Type = Context.getObjCSuperType(); 7642 break; 7643 case 'a': 7644 Type = Context.getBuiltinVaListType(); 7645 assert(!Type.isNull() && "builtin va list type not initialized!"); 7646 break; 7647 case 'A': 7648 // This is a "reference" to a va_list; however, what exactly 7649 // this means depends on how va_list is defined. There are two 7650 // different kinds of va_list: ones passed by value, and ones 7651 // passed by reference. An example of a by-value va_list is 7652 // x86, where va_list is a char*. An example of by-ref va_list 7653 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 7654 // we want this argument to be a char*&; for x86-64, we want 7655 // it to be a __va_list_tag*. 7656 Type = Context.getBuiltinVaListType(); 7657 assert(!Type.isNull() && "builtin va list type not initialized!"); 7658 if (Type->isArrayType()) 7659 Type = Context.getArrayDecayedType(Type); 7660 else 7661 Type = Context.getLValueReferenceType(Type); 7662 break; 7663 case 'V': { 7664 char *End; 7665 unsigned NumElements = strtoul(Str, &End, 10); 7666 assert(End != Str && "Missing vector size"); 7667 Str = End; 7668 7669 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 7670 RequiresICE, false); 7671 assert(!RequiresICE && "Can't require vector ICE"); 7672 7673 // TODO: No way to make AltiVec vectors in builtins yet. 7674 Type = Context.getVectorType(ElementType, NumElements, 7675 VectorType::GenericVector); 7676 break; 7677 } 7678 case 'E': { 7679 char *End; 7680 7681 unsigned NumElements = strtoul(Str, &End, 10); 7682 assert(End != Str && "Missing vector size"); 7683 7684 Str = End; 7685 7686 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 7687 false); 7688 Type = Context.getExtVectorType(ElementType, NumElements); 7689 break; 7690 } 7691 case 'X': { 7692 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 7693 false); 7694 assert(!RequiresICE && "Can't require complex ICE"); 7695 Type = Context.getComplexType(ElementType); 7696 break; 7697 } 7698 case 'Y' : { 7699 Type = Context.getPointerDiffType(); 7700 break; 7701 } 7702 case 'P': 7703 Type = Context.getFILEType(); 7704 if (Type.isNull()) { 7705 Error = ASTContext::GE_Missing_stdio; 7706 return QualType(); 7707 } 7708 break; 7709 case 'J': 7710 if (Signed) 7711 Type = Context.getsigjmp_bufType(); 7712 else 7713 Type = Context.getjmp_bufType(); 7714 7715 if (Type.isNull()) { 7716 Error = ASTContext::GE_Missing_setjmp; 7717 return QualType(); 7718 } 7719 break; 7720 case 'K': 7721 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 7722 Type = Context.getucontext_tType(); 7723 7724 if (Type.isNull()) { 7725 Error = ASTContext::GE_Missing_ucontext; 7726 return QualType(); 7727 } 7728 break; 7729 case 'p': 7730 Type = Context.getProcessIDType(); 7731 break; 7732 } 7733 7734 // If there are modifiers and if we're allowed to parse them, go for it. 7735 Done = !AllowTypeModifiers; 7736 while (!Done) { 7737 switch (char c = *Str++) { 7738 default: Done = true; --Str; break; 7739 case '*': 7740 case '&': { 7741 // Both pointers and references can have their pointee types 7742 // qualified with an address space. 7743 char *End; 7744 unsigned AddrSpace = strtoul(Str, &End, 10); 7745 if (End != Str && AddrSpace != 0) { 7746 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 7747 Str = End; 7748 } 7749 if (c == '*') 7750 Type = Context.getPointerType(Type); 7751 else 7752 Type = Context.getLValueReferenceType(Type); 7753 break; 7754 } 7755 // FIXME: There's no way to have a built-in with an rvalue ref arg. 7756 case 'C': 7757 Type = Type.withConst(); 7758 break; 7759 case 'D': 7760 Type = Context.getVolatileType(Type); 7761 break; 7762 case 'R': 7763 Type = Type.withRestrict(); 7764 break; 7765 } 7766 } 7767 7768 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 7769 "Integer constant 'I' type must be an integer"); 7770 7771 return Type; 7772} 7773 7774/// GetBuiltinType - Return the type for the specified builtin. 7775QualType ASTContext::GetBuiltinType(unsigned Id, 7776 GetBuiltinTypeError &Error, 7777 unsigned *IntegerConstantArgs) const { 7778 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 7779 7780 SmallVector<QualType, 8> ArgTypes; 7781 7782 bool RequiresICE = false; 7783 Error = GE_None; 7784 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 7785 RequiresICE, true); 7786 if (Error != GE_None) 7787 return QualType(); 7788 7789 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 7790 7791 while (TypeStr[0] && TypeStr[0] != '.') { 7792 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 7793 if (Error != GE_None) 7794 return QualType(); 7795 7796 // If this argument is required to be an IntegerConstantExpression and the 7797 // caller cares, fill in the bitmask we return. 7798 if (RequiresICE && IntegerConstantArgs) 7799 *IntegerConstantArgs |= 1 << ArgTypes.size(); 7800 7801 // Do array -> pointer decay. The builtin should use the decayed type. 7802 if (Ty->isArrayType()) 7803 Ty = getArrayDecayedType(Ty); 7804 7805 ArgTypes.push_back(Ty); 7806 } 7807 7808 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 7809 "'.' should only occur at end of builtin type list!"); 7810 7811 FunctionType::ExtInfo EI(CC_C); 7812 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 7813 7814 bool Variadic = (TypeStr[0] == '.'); 7815 7816 // We really shouldn't be making a no-proto type here, especially in C++. 7817 if (ArgTypes.empty() && Variadic) 7818 return getFunctionNoProtoType(ResType, EI); 7819 7820 FunctionProtoType::ExtProtoInfo EPI; 7821 EPI.ExtInfo = EI; 7822 EPI.Variadic = Variadic; 7823 7824 return getFunctionType(ResType, ArgTypes, EPI); 7825} 7826 7827static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 7828 const FunctionDecl *FD) { 7829 if (!FD->isExternallyVisible()) 7830 return GVA_Internal; 7831 7832 GVALinkage External = GVA_StrongExternal; 7833 switch (FD->getTemplateSpecializationKind()) { 7834 case TSK_Undeclared: 7835 case TSK_ExplicitSpecialization: 7836 External = GVA_StrongExternal; 7837 break; 7838 7839 case TSK_ExplicitInstantiationDefinition: 7840 return GVA_StrongODR; 7841 7842 // C++11 [temp.explicit]p10: 7843 // [ Note: The intent is that an inline function that is the subject of 7844 // an explicit instantiation declaration will still be implicitly 7845 // instantiated when used so that the body can be considered for 7846 // inlining, but that no out-of-line copy of the inline function would be 7847 // generated in the translation unit. -- end note ] 7848 case TSK_ExplicitInstantiationDeclaration: 7849 return GVA_AvailableExternally; 7850 7851 case TSK_ImplicitInstantiation: 7852 External = GVA_DiscardableODR; 7853 break; 7854 } 7855 7856 if (!FD->isInlined()) 7857 return External; 7858 7859 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat && 7860 !FD->hasAttr<DLLExportAttr>()) || 7861 FD->hasAttr<GNUInlineAttr>()) { 7862 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 7863 7864 // GNU or C99 inline semantics. Determine whether this symbol should be 7865 // externally visible. 7866 if (FD->isInlineDefinitionExternallyVisible()) 7867 return External; 7868 7869 // C99 inline semantics, where the symbol is not externally visible. 7870 return GVA_AvailableExternally; 7871 } 7872 7873 // Functions specified with extern and inline in -fms-compatibility mode 7874 // forcibly get emitted. While the body of the function cannot be later 7875 // replaced, the function definition cannot be discarded.
| 686 case TargetCXXABI::GenericItanium: 687 return CreateItaniumCXXABI(*this); 688 case TargetCXXABI::Microsoft: 689 return CreateMicrosoftCXXABI(*this); 690 } 691 llvm_unreachable("Invalid CXXABI type!"); 692} 693 694static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 695 const LangOptions &LOpts) { 696 if (LOpts.FakeAddressSpaceMap) { 697 // The fake address space map must have a distinct entry for each 698 // language-specific address space. 699 static const unsigned FakeAddrSpaceMap[] = { 700 1, // opencl_global 701 2, // opencl_local 702 3, // opencl_constant 703 4, // opencl_generic 704 5, // cuda_device 705 6, // cuda_constant 706 7 // cuda_shared 707 }; 708 return &FakeAddrSpaceMap; 709 } else { 710 return &T.getAddressSpaceMap(); 711 } 712} 713 714static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI, 715 const LangOptions &LangOpts) { 716 switch (LangOpts.getAddressSpaceMapMangling()) { 717 case LangOptions::ASMM_Target: 718 return TI.useAddressSpaceMapMangling(); 719 case LangOptions::ASMM_On: 720 return true; 721 case LangOptions::ASMM_Off: 722 return false; 723 } 724 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything."); 725} 726 727ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM, 728 IdentifierTable &idents, SelectorTable &sels, 729 Builtin::Context &builtins) 730 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()), 731 DependentTemplateSpecializationTypes(this_()), 732 SubstTemplateTemplateParmPacks(this_()), 733 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr), 734 UInt128Decl(nullptr), Float128StubDecl(nullptr), 735 BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr), 736 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr), 737 CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr), 738 FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr), 739 ucontext_tDecl(nullptr), BlockDescriptorType(nullptr), 740 BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr), 741 FirstLocalImport(), LastLocalImport(), 742 SourceMgr(SM), LangOpts(LOpts), 743 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFile, SM)), 744 AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts), 745 Idents(idents), Selectors(sels), BuiltinInfo(builtins), 746 DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr), 747 Comments(SM), CommentsLoaded(false), 748 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) { 749 TUDecl = TranslationUnitDecl::Create(*this); 750} 751 752ASTContext::~ASTContext() { 753 ReleaseParentMapEntries(); 754 755 // Release the DenseMaps associated with DeclContext objects. 756 // FIXME: Is this the ideal solution? 757 ReleaseDeclContextMaps(); 758 759 // Call all of the deallocation functions on all of their targets. 760 for (DeallocationMap::const_iterator I = Deallocations.begin(), 761 E = Deallocations.end(); I != E; ++I) 762 for (unsigned J = 0, N = I->second.size(); J != N; ++J) 763 (I->first)((I->second)[J]); 764 765 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 766 // because they can contain DenseMaps. 767 for (llvm::DenseMap<const ObjCContainerDecl*, 768 const ASTRecordLayout*>::iterator 769 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 770 // Increment in loop to prevent using deallocated memory. 771 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 772 R->Destroy(*this); 773 774 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 775 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 776 // Increment in loop to prevent using deallocated memory. 777 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 778 R->Destroy(*this); 779 } 780 781 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 782 AEnd = DeclAttrs.end(); 783 A != AEnd; ++A) 784 A->second->~AttrVec(); 785 786 llvm::DeleteContainerSeconds(MangleNumberingContexts); 787} 788 789void ASTContext::ReleaseParentMapEntries() { 790 if (!AllParents) return; 791 for (const auto &Entry : *AllParents) { 792 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) { 793 delete Entry.second.get<ast_type_traits::DynTypedNode *>(); 794 } else { 795 assert(Entry.second.is<ParentVector *>()); 796 delete Entry.second.get<ParentVector *>(); 797 } 798 } 799} 800 801void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 802 Deallocations[Callback].push_back(Data); 803} 804 805void 806ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) { 807 ExternalSource = Source; 808} 809 810void ASTContext::PrintStats() const { 811 llvm::errs() << "\n*** AST Context Stats:\n"; 812 llvm::errs() << " " << Types.size() << " types total.\n"; 813 814 unsigned counts[] = { 815#define TYPE(Name, Parent) 0, 816#define ABSTRACT_TYPE(Name, Parent) 817#include "clang/AST/TypeNodes.def" 818 0 // Extra 819 }; 820 821 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 822 Type *T = Types[i]; 823 counts[(unsigned)T->getTypeClass()]++; 824 } 825 826 unsigned Idx = 0; 827 unsigned TotalBytes = 0; 828#define TYPE(Name, Parent) \ 829 if (counts[Idx]) \ 830 llvm::errs() << " " << counts[Idx] << " " << #Name \ 831 << " types\n"; \ 832 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 833 ++Idx; 834#define ABSTRACT_TYPE(Name, Parent) 835#include "clang/AST/TypeNodes.def" 836 837 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 838 839 // Implicit special member functions. 840 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 841 << NumImplicitDefaultConstructors 842 << " implicit default constructors created\n"; 843 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 844 << NumImplicitCopyConstructors 845 << " implicit copy constructors created\n"; 846 if (getLangOpts().CPlusPlus) 847 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 848 << NumImplicitMoveConstructors 849 << " implicit move constructors created\n"; 850 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 851 << NumImplicitCopyAssignmentOperators 852 << " implicit copy assignment operators created\n"; 853 if (getLangOpts().CPlusPlus) 854 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 855 << NumImplicitMoveAssignmentOperators 856 << " implicit move assignment operators created\n"; 857 llvm::errs() << NumImplicitDestructorsDeclared << "/" 858 << NumImplicitDestructors 859 << " implicit destructors created\n"; 860 861 if (ExternalSource) { 862 llvm::errs() << "\n"; 863 ExternalSource->PrintStats(); 864 } 865 866 BumpAlloc.PrintStats(); 867} 868 869RecordDecl *ASTContext::buildImplicitRecord(StringRef Name, 870 RecordDecl::TagKind TK) const { 871 SourceLocation Loc; 872 RecordDecl *NewDecl; 873 if (getLangOpts().CPlusPlus) 874 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, 875 Loc, &Idents.get(Name)); 876 else 877 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc, 878 &Idents.get(Name)); 879 NewDecl->setImplicit(); 880 return NewDecl; 881} 882 883TypedefDecl *ASTContext::buildImplicitTypedef(QualType T, 884 StringRef Name) const { 885 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 886 TypedefDecl *NewDecl = TypedefDecl::Create( 887 const_cast<ASTContext &>(*this), getTranslationUnitDecl(), 888 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo); 889 NewDecl->setImplicit(); 890 return NewDecl; 891} 892 893TypedefDecl *ASTContext::getInt128Decl() const { 894 if (!Int128Decl) 895 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t"); 896 return Int128Decl; 897} 898 899TypedefDecl *ASTContext::getUInt128Decl() const { 900 if (!UInt128Decl) 901 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t"); 902 return UInt128Decl; 903} 904 905TypeDecl *ASTContext::getFloat128StubType() const { 906 assert(LangOpts.CPlusPlus && "should only be called for c++"); 907 if (!Float128StubDecl) 908 Float128StubDecl = buildImplicitRecord("__float128"); 909 910 return Float128StubDecl; 911} 912 913void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 914 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 915 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 916 Types.push_back(Ty); 917} 918 919void ASTContext::InitBuiltinTypes(const TargetInfo &Target) { 920 assert((!this->Target || this->Target == &Target) && 921 "Incorrect target reinitialization"); 922 assert(VoidTy.isNull() && "Context reinitialized?"); 923 924 this->Target = &Target; 925 926 ABI.reset(createCXXABI(Target)); 927 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 928 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts); 929 930 // C99 6.2.5p19. 931 InitBuiltinType(VoidTy, BuiltinType::Void); 932 933 // C99 6.2.5p2. 934 InitBuiltinType(BoolTy, BuiltinType::Bool); 935 // C99 6.2.5p3. 936 if (LangOpts.CharIsSigned) 937 InitBuiltinType(CharTy, BuiltinType::Char_S); 938 else 939 InitBuiltinType(CharTy, BuiltinType::Char_U); 940 // C99 6.2.5p4. 941 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 942 InitBuiltinType(ShortTy, BuiltinType::Short); 943 InitBuiltinType(IntTy, BuiltinType::Int); 944 InitBuiltinType(LongTy, BuiltinType::Long); 945 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 946 947 // C99 6.2.5p6. 948 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 949 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 950 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 951 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 952 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 953 954 // C99 6.2.5p10. 955 InitBuiltinType(FloatTy, BuiltinType::Float); 956 InitBuiltinType(DoubleTy, BuiltinType::Double); 957 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 958 959 // GNU extension, 128-bit integers. 960 InitBuiltinType(Int128Ty, BuiltinType::Int128); 961 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 962 963 // C++ 3.9.1p5 964 if (TargetInfo::isTypeSigned(Target.getWCharType())) 965 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 966 else // -fshort-wchar makes wchar_t be unsigned. 967 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 968 if (LangOpts.CPlusPlus && LangOpts.WChar) 969 WideCharTy = WCharTy; 970 else { 971 // C99 (or C++ using -fno-wchar). 972 WideCharTy = getFromTargetType(Target.getWCharType()); 973 } 974 975 WIntTy = getFromTargetType(Target.getWIntType()); 976 977 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 978 InitBuiltinType(Char16Ty, BuiltinType::Char16); 979 else // C99 980 Char16Ty = getFromTargetType(Target.getChar16Type()); 981 982 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 983 InitBuiltinType(Char32Ty, BuiltinType::Char32); 984 else // C99 985 Char32Ty = getFromTargetType(Target.getChar32Type()); 986 987 // Placeholder type for type-dependent expressions whose type is 988 // completely unknown. No code should ever check a type against 989 // DependentTy and users should never see it; however, it is here to 990 // help diagnose failures to properly check for type-dependent 991 // expressions. 992 InitBuiltinType(DependentTy, BuiltinType::Dependent); 993 994 // Placeholder type for functions. 995 InitBuiltinType(OverloadTy, BuiltinType::Overload); 996 997 // Placeholder type for bound members. 998 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 999 1000 // Placeholder type for pseudo-objects. 1001 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 1002 1003 // "any" type; useful for debugger-like clients. 1004 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 1005 1006 // Placeholder type for unbridged ARC casts. 1007 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 1008 1009 // Placeholder type for builtin functions. 1010 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn); 1011 1012 // C99 6.2.5p11. 1013 FloatComplexTy = getComplexType(FloatTy); 1014 DoubleComplexTy = getComplexType(DoubleTy); 1015 LongDoubleComplexTy = getComplexType(LongDoubleTy); 1016 1017 // Builtin types for 'id', 'Class', and 'SEL'. 1018 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 1019 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 1020 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 1021 1022 if (LangOpts.OpenCL) { 1023 InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d); 1024 InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray); 1025 InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer); 1026 InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d); 1027 InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray); 1028 InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d); 1029 1030 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler); 1031 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent); 1032 } 1033 1034 // Builtin type for __objc_yes and __objc_no 1035 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 1036 SignedCharTy : BoolTy); 1037 1038 ObjCConstantStringType = QualType(); 1039 1040 ObjCSuperType = QualType(); 1041 1042 // void * type 1043 VoidPtrTy = getPointerType(VoidTy); 1044 1045 // nullptr type (C++0x 2.14.7) 1046 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 1047 1048 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 1049 InitBuiltinType(HalfTy, BuiltinType::Half); 1050 1051 // Builtin type used to help define __builtin_va_list. 1052 VaListTagTy = QualType(); 1053} 1054 1055DiagnosticsEngine &ASTContext::getDiagnostics() const { 1056 return SourceMgr.getDiagnostics(); 1057} 1058 1059AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 1060 AttrVec *&Result = DeclAttrs[D]; 1061 if (!Result) { 1062 void *Mem = Allocate(sizeof(AttrVec)); 1063 Result = new (Mem) AttrVec; 1064 } 1065 1066 return *Result; 1067} 1068 1069/// \brief Erase the attributes corresponding to the given declaration. 1070void ASTContext::eraseDeclAttrs(const Decl *D) { 1071 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 1072 if (Pos != DeclAttrs.end()) { 1073 Pos->second->~AttrVec(); 1074 DeclAttrs.erase(Pos); 1075 } 1076} 1077 1078// FIXME: Remove ? 1079MemberSpecializationInfo * 1080ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 1081 assert(Var->isStaticDataMember() && "Not a static data member"); 1082 return getTemplateOrSpecializationInfo(Var) 1083 .dyn_cast<MemberSpecializationInfo *>(); 1084} 1085 1086ASTContext::TemplateOrSpecializationInfo 1087ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) { 1088 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos = 1089 TemplateOrInstantiation.find(Var); 1090 if (Pos == TemplateOrInstantiation.end()) 1091 return TemplateOrSpecializationInfo(); 1092 1093 return Pos->second; 1094} 1095 1096void 1097ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 1098 TemplateSpecializationKind TSK, 1099 SourceLocation PointOfInstantiation) { 1100 assert(Inst->isStaticDataMember() && "Not a static data member"); 1101 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 1102 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo( 1103 Tmpl, TSK, PointOfInstantiation)); 1104} 1105 1106void 1107ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst, 1108 TemplateOrSpecializationInfo TSI) { 1109 assert(!TemplateOrInstantiation[Inst] && 1110 "Already noted what the variable was instantiated from"); 1111 TemplateOrInstantiation[Inst] = TSI; 1112} 1113 1114FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 1115 const FunctionDecl *FD){ 1116 assert(FD && "Specialization is 0"); 1117 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 1118 = ClassScopeSpecializationPattern.find(FD); 1119 if (Pos == ClassScopeSpecializationPattern.end()) 1120 return nullptr; 1121 1122 return Pos->second; 1123} 1124 1125void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 1126 FunctionDecl *Pattern) { 1127 assert(FD && "Specialization is 0"); 1128 assert(Pattern && "Class scope specialization pattern is 0"); 1129 ClassScopeSpecializationPattern[FD] = Pattern; 1130} 1131 1132NamedDecl * 1133ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 1134 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 1135 = InstantiatedFromUsingDecl.find(UUD); 1136 if (Pos == InstantiatedFromUsingDecl.end()) 1137 return nullptr; 1138 1139 return Pos->second; 1140} 1141 1142void 1143ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 1144 assert((isa<UsingDecl>(Pattern) || 1145 isa<UnresolvedUsingValueDecl>(Pattern) || 1146 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 1147 "pattern decl is not a using decl"); 1148 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 1149 InstantiatedFromUsingDecl[Inst] = Pattern; 1150} 1151 1152UsingShadowDecl * 1153ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 1154 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 1155 = InstantiatedFromUsingShadowDecl.find(Inst); 1156 if (Pos == InstantiatedFromUsingShadowDecl.end()) 1157 return nullptr; 1158 1159 return Pos->second; 1160} 1161 1162void 1163ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 1164 UsingShadowDecl *Pattern) { 1165 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 1166 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 1167} 1168 1169FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 1170 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 1171 = InstantiatedFromUnnamedFieldDecl.find(Field); 1172 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 1173 return nullptr; 1174 1175 return Pos->second; 1176} 1177 1178void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 1179 FieldDecl *Tmpl) { 1180 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 1181 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 1182 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 1183 "Already noted what unnamed field was instantiated from"); 1184 1185 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 1186} 1187 1188ASTContext::overridden_cxx_method_iterator 1189ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 1190 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1191 = OverriddenMethods.find(Method->getCanonicalDecl()); 1192 if (Pos == OverriddenMethods.end()) 1193 return nullptr; 1194 1195 return Pos->second.begin(); 1196} 1197 1198ASTContext::overridden_cxx_method_iterator 1199ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 1200 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1201 = OverriddenMethods.find(Method->getCanonicalDecl()); 1202 if (Pos == OverriddenMethods.end()) 1203 return nullptr; 1204 1205 return Pos->second.end(); 1206} 1207 1208unsigned 1209ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 1210 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 1211 = OverriddenMethods.find(Method->getCanonicalDecl()); 1212 if (Pos == OverriddenMethods.end()) 1213 return 0; 1214 1215 return Pos->second.size(); 1216} 1217 1218void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 1219 const CXXMethodDecl *Overridden) { 1220 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl()); 1221 OverriddenMethods[Method].push_back(Overridden); 1222} 1223 1224void ASTContext::getOverriddenMethods( 1225 const NamedDecl *D, 1226 SmallVectorImpl<const NamedDecl *> &Overridden) const { 1227 assert(D); 1228 1229 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) { 1230 Overridden.append(overridden_methods_begin(CXXMethod), 1231 overridden_methods_end(CXXMethod)); 1232 return; 1233 } 1234 1235 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D); 1236 if (!Method) 1237 return; 1238 1239 SmallVector<const ObjCMethodDecl *, 8> OverDecls; 1240 Method->getOverriddenMethods(OverDecls); 1241 Overridden.append(OverDecls.begin(), OverDecls.end()); 1242} 1243 1244void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 1245 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 1246 assert(!Import->isFromASTFile() && "Non-local import declaration"); 1247 if (!FirstLocalImport) { 1248 FirstLocalImport = Import; 1249 LastLocalImport = Import; 1250 return; 1251 } 1252 1253 LastLocalImport->NextLocalImport = Import; 1254 LastLocalImport = Import; 1255} 1256 1257//===----------------------------------------------------------------------===// 1258// Type Sizing and Analysis 1259//===----------------------------------------------------------------------===// 1260 1261/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 1262/// scalar floating point type. 1263const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 1264 const BuiltinType *BT = T->getAs<BuiltinType>(); 1265 assert(BT && "Not a floating point type!"); 1266 switch (BT->getKind()) { 1267 default: llvm_unreachable("Not a floating point type!"); 1268 case BuiltinType::Half: return Target->getHalfFormat(); 1269 case BuiltinType::Float: return Target->getFloatFormat(); 1270 case BuiltinType::Double: return Target->getDoubleFormat(); 1271 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 1272 } 1273} 1274 1275CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const { 1276 unsigned Align = Target->getCharWidth(); 1277 1278 bool UseAlignAttrOnly = false; 1279 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 1280 Align = AlignFromAttr; 1281 1282 // __attribute__((aligned)) can increase or decrease alignment 1283 // *except* on a struct or struct member, where it only increases 1284 // alignment unless 'packed' is also specified. 1285 // 1286 // It is an error for alignas to decrease alignment, so we can 1287 // ignore that possibility; Sema should diagnose it. 1288 if (isa<FieldDecl>(D)) { 1289 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 1290 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1291 } else { 1292 UseAlignAttrOnly = true; 1293 } 1294 } 1295 else if (isa<FieldDecl>(D)) 1296 UseAlignAttrOnly = 1297 D->hasAttr<PackedAttr>() || 1298 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 1299 1300 // If we're using the align attribute only, just ignore everything 1301 // else about the declaration and its type. 1302 if (UseAlignAttrOnly) { 1303 // do nothing 1304 1305 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 1306 QualType T = VD->getType(); 1307 if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 1308 if (ForAlignof) 1309 T = RT->getPointeeType(); 1310 else 1311 T = getPointerType(RT->getPointeeType()); 1312 } 1313 QualType BaseT = getBaseElementType(T); 1314 if (!BaseT->isIncompleteType() && !T->isFunctionType()) { 1315 // Adjust alignments of declarations with array type by the 1316 // large-array alignment on the target. 1317 if (const ArrayType *arrayType = getAsArrayType(T)) { 1318 unsigned MinWidth = Target->getLargeArrayMinWidth(); 1319 if (!ForAlignof && MinWidth) { 1320 if (isa<VariableArrayType>(arrayType)) 1321 Align = std::max(Align, Target->getLargeArrayAlign()); 1322 else if (isa<ConstantArrayType>(arrayType) && 1323 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 1324 Align = std::max(Align, Target->getLargeArrayAlign()); 1325 } 1326 } 1327 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 1328 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1329 if (VD->hasGlobalStorage()) 1330 Align = std::max(Align, getTargetInfo().getMinGlobalAlign()); 1331 } 1332 } 1333 1334 // Fields can be subject to extra alignment constraints, like if 1335 // the field is packed, the struct is packed, or the struct has a 1336 // a max-field-alignment constraint (#pragma pack). So calculate 1337 // the actual alignment of the field within the struct, and then 1338 // (as we're expected to) constrain that by the alignment of the type. 1339 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 1340 const RecordDecl *Parent = Field->getParent(); 1341 // We can only produce a sensible answer if the record is valid. 1342 if (!Parent->isInvalidDecl()) { 1343 const ASTRecordLayout &Layout = getASTRecordLayout(Parent); 1344 1345 // Start with the record's overall alignment. 1346 unsigned FieldAlign = toBits(Layout.getAlignment()); 1347 1348 // Use the GCD of that and the offset within the record. 1349 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex()); 1350 if (Offset > 0) { 1351 // Alignment is always a power of 2, so the GCD will be a power of 2, 1352 // which means we get to do this crazy thing instead of Euclid's. 1353 uint64_t LowBitOfOffset = Offset & (~Offset + 1); 1354 if (LowBitOfOffset < FieldAlign) 1355 FieldAlign = static_cast<unsigned>(LowBitOfOffset); 1356 } 1357 1358 Align = std::min(Align, FieldAlign); 1359 } 1360 } 1361 } 1362 1363 return toCharUnitsFromBits(Align); 1364} 1365 1366// getTypeInfoDataSizeInChars - Return the size of a type, in 1367// chars. If the type is a record, its data size is returned. This is 1368// the size of the memcpy that's performed when assigning this type 1369// using a trivial copy/move assignment operator. 1370std::pair<CharUnits, CharUnits> 1371ASTContext::getTypeInfoDataSizeInChars(QualType T) const { 1372 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T); 1373 1374 // In C++, objects can sometimes be allocated into the tail padding 1375 // of a base-class subobject. We decide whether that's possible 1376 // during class layout, so here we can just trust the layout results. 1377 if (getLangOpts().CPlusPlus) { 1378 if (const RecordType *RT = T->getAs<RecordType>()) { 1379 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl()); 1380 sizeAndAlign.first = layout.getDataSize(); 1381 } 1382 } 1383 1384 return sizeAndAlign; 1385} 1386 1387/// getConstantArrayInfoInChars - Performing the computation in CharUnits 1388/// instead of in bits prevents overflowing the uint64_t for some large arrays. 1389std::pair<CharUnits, CharUnits> 1390static getConstantArrayInfoInChars(const ASTContext &Context, 1391 const ConstantArrayType *CAT) { 1392 std::pair<CharUnits, CharUnits> EltInfo = 1393 Context.getTypeInfoInChars(CAT->getElementType()); 1394 uint64_t Size = CAT->getSize().getZExtValue(); 1395 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <= 1396 (uint64_t)(-1)/Size) && 1397 "Overflow in array type char size evaluation"); 1398 uint64_t Width = EltInfo.first.getQuantity() * Size; 1399 unsigned Align = EltInfo.second.getQuantity(); 1400 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() || 1401 Context.getTargetInfo().getPointerWidth(0) == 64) 1402 Width = llvm::RoundUpToAlignment(Width, Align); 1403 return std::make_pair(CharUnits::fromQuantity(Width), 1404 CharUnits::fromQuantity(Align)); 1405} 1406 1407std::pair<CharUnits, CharUnits> 1408ASTContext::getTypeInfoInChars(const Type *T) const { 1409 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) 1410 return getConstantArrayInfoInChars(*this, CAT); 1411 TypeInfo Info = getTypeInfo(T); 1412 return std::make_pair(toCharUnitsFromBits(Info.Width), 1413 toCharUnitsFromBits(Info.Align)); 1414} 1415 1416std::pair<CharUnits, CharUnits> 1417ASTContext::getTypeInfoInChars(QualType T) const { 1418 return getTypeInfoInChars(T.getTypePtr()); 1419} 1420 1421bool ASTContext::isAlignmentRequired(const Type *T) const { 1422 return getTypeInfo(T).AlignIsRequired; 1423} 1424 1425bool ASTContext::isAlignmentRequired(QualType T) const { 1426 return isAlignmentRequired(T.getTypePtr()); 1427} 1428 1429TypeInfo ASTContext::getTypeInfo(const Type *T) const { 1430 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T); 1431 if (I != MemoizedTypeInfo.end()) 1432 return I->second; 1433 1434 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup. 1435 TypeInfo TI = getTypeInfoImpl(T); 1436 MemoizedTypeInfo[T] = TI; 1437 return TI; 1438} 1439 1440/// getTypeInfoImpl - Return the size of the specified type, in bits. This 1441/// method does not work on incomplete types. 1442/// 1443/// FIXME: Pointers into different addr spaces could have different sizes and 1444/// alignment requirements: getPointerInfo should take an AddrSpace, this 1445/// should take a QualType, &c. 1446TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const { 1447 uint64_t Width = 0; 1448 unsigned Align = 8; 1449 bool AlignIsRequired = false; 1450 switch (T->getTypeClass()) { 1451#define TYPE(Class, Base) 1452#define ABSTRACT_TYPE(Class, Base) 1453#define NON_CANONICAL_TYPE(Class, Base) 1454#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1455#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \ 1456 case Type::Class: \ 1457 assert(!T->isDependentType() && "should not see dependent types here"); \ 1458 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr()); 1459#include "clang/AST/TypeNodes.def" 1460 llvm_unreachable("Should not see dependent types"); 1461 1462 case Type::FunctionNoProto: 1463 case Type::FunctionProto: 1464 // GCC extension: alignof(function) = 32 bits 1465 Width = 0; 1466 Align = 32; 1467 break; 1468 1469 case Type::IncompleteArray: 1470 case Type::VariableArray: 1471 Width = 0; 1472 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 1473 break; 1474 1475 case Type::ConstantArray: { 1476 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 1477 1478 TypeInfo EltInfo = getTypeInfo(CAT->getElementType()); 1479 uint64_t Size = CAT->getSize().getZExtValue(); 1480 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) && 1481 "Overflow in array type bit size evaluation"); 1482 Width = EltInfo.Width * Size; 1483 Align = EltInfo.Align; 1484 if (!getTargetInfo().getCXXABI().isMicrosoft() || 1485 getTargetInfo().getPointerWidth(0) == 64) 1486 Width = llvm::RoundUpToAlignment(Width, Align); 1487 break; 1488 } 1489 case Type::ExtVector: 1490 case Type::Vector: { 1491 const VectorType *VT = cast<VectorType>(T); 1492 TypeInfo EltInfo = getTypeInfo(VT->getElementType()); 1493 Width = EltInfo.Width * VT->getNumElements(); 1494 Align = Width; 1495 // If the alignment is not a power of 2, round up to the next power of 2. 1496 // This happens for non-power-of-2 length vectors. 1497 if (Align & (Align-1)) { 1498 Align = llvm::NextPowerOf2(Align); 1499 Width = llvm::RoundUpToAlignment(Width, Align); 1500 } 1501 // Adjust the alignment based on the target max. 1502 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1503 if (TargetVectorAlign && TargetVectorAlign < Align) 1504 Align = TargetVectorAlign; 1505 break; 1506 } 1507 1508 case Type::Builtin: 1509 switch (cast<BuiltinType>(T)->getKind()) { 1510 default: llvm_unreachable("Unknown builtin type!"); 1511 case BuiltinType::Void: 1512 // GCC extension: alignof(void) = 8 bits. 1513 Width = 0; 1514 Align = 8; 1515 break; 1516 1517 case BuiltinType::Bool: 1518 Width = Target->getBoolWidth(); 1519 Align = Target->getBoolAlign(); 1520 break; 1521 case BuiltinType::Char_S: 1522 case BuiltinType::Char_U: 1523 case BuiltinType::UChar: 1524 case BuiltinType::SChar: 1525 Width = Target->getCharWidth(); 1526 Align = Target->getCharAlign(); 1527 break; 1528 case BuiltinType::WChar_S: 1529 case BuiltinType::WChar_U: 1530 Width = Target->getWCharWidth(); 1531 Align = Target->getWCharAlign(); 1532 break; 1533 case BuiltinType::Char16: 1534 Width = Target->getChar16Width(); 1535 Align = Target->getChar16Align(); 1536 break; 1537 case BuiltinType::Char32: 1538 Width = Target->getChar32Width(); 1539 Align = Target->getChar32Align(); 1540 break; 1541 case BuiltinType::UShort: 1542 case BuiltinType::Short: 1543 Width = Target->getShortWidth(); 1544 Align = Target->getShortAlign(); 1545 break; 1546 case BuiltinType::UInt: 1547 case BuiltinType::Int: 1548 Width = Target->getIntWidth(); 1549 Align = Target->getIntAlign(); 1550 break; 1551 case BuiltinType::ULong: 1552 case BuiltinType::Long: 1553 Width = Target->getLongWidth(); 1554 Align = Target->getLongAlign(); 1555 break; 1556 case BuiltinType::ULongLong: 1557 case BuiltinType::LongLong: 1558 Width = Target->getLongLongWidth(); 1559 Align = Target->getLongLongAlign(); 1560 break; 1561 case BuiltinType::Int128: 1562 case BuiltinType::UInt128: 1563 Width = 128; 1564 Align = 128; // int128_t is 128-bit aligned on all targets. 1565 break; 1566 case BuiltinType::Half: 1567 Width = Target->getHalfWidth(); 1568 Align = Target->getHalfAlign(); 1569 break; 1570 case BuiltinType::Float: 1571 Width = Target->getFloatWidth(); 1572 Align = Target->getFloatAlign(); 1573 break; 1574 case BuiltinType::Double: 1575 Width = Target->getDoubleWidth(); 1576 Align = Target->getDoubleAlign(); 1577 break; 1578 case BuiltinType::LongDouble: 1579 Width = Target->getLongDoubleWidth(); 1580 Align = Target->getLongDoubleAlign(); 1581 break; 1582 case BuiltinType::NullPtr: 1583 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1584 Align = Target->getPointerAlign(0); // == sizeof(void*) 1585 break; 1586 case BuiltinType::ObjCId: 1587 case BuiltinType::ObjCClass: 1588 case BuiltinType::ObjCSel: 1589 Width = Target->getPointerWidth(0); 1590 Align = Target->getPointerAlign(0); 1591 break; 1592 case BuiltinType::OCLSampler: 1593 // Samplers are modeled as integers. 1594 Width = Target->getIntWidth(); 1595 Align = Target->getIntAlign(); 1596 break; 1597 case BuiltinType::OCLEvent: 1598 case BuiltinType::OCLImage1d: 1599 case BuiltinType::OCLImage1dArray: 1600 case BuiltinType::OCLImage1dBuffer: 1601 case BuiltinType::OCLImage2d: 1602 case BuiltinType::OCLImage2dArray: 1603 case BuiltinType::OCLImage3d: 1604 // Currently these types are pointers to opaque types. 1605 Width = Target->getPointerWidth(0); 1606 Align = Target->getPointerAlign(0); 1607 break; 1608 } 1609 break; 1610 case Type::ObjCObjectPointer: 1611 Width = Target->getPointerWidth(0); 1612 Align = Target->getPointerAlign(0); 1613 break; 1614 case Type::BlockPointer: { 1615 unsigned AS = getTargetAddressSpace( 1616 cast<BlockPointerType>(T)->getPointeeType()); 1617 Width = Target->getPointerWidth(AS); 1618 Align = Target->getPointerAlign(AS); 1619 break; 1620 } 1621 case Type::LValueReference: 1622 case Type::RValueReference: { 1623 // alignof and sizeof should never enter this code path here, so we go 1624 // the pointer route. 1625 unsigned AS = getTargetAddressSpace( 1626 cast<ReferenceType>(T)->getPointeeType()); 1627 Width = Target->getPointerWidth(AS); 1628 Align = Target->getPointerAlign(AS); 1629 break; 1630 } 1631 case Type::Pointer: { 1632 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1633 Width = Target->getPointerWidth(AS); 1634 Align = Target->getPointerAlign(AS); 1635 break; 1636 } 1637 case Type::MemberPointer: { 1638 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1639 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT); 1640 break; 1641 } 1642 case Type::Complex: { 1643 // Complex types have the same alignment as their elements, but twice the 1644 // size. 1645 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType()); 1646 Width = EltInfo.Width * 2; 1647 Align = EltInfo.Align; 1648 break; 1649 } 1650 case Type::ObjCObject: 1651 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1652 case Type::Adjusted: 1653 case Type::Decayed: 1654 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr()); 1655 case Type::ObjCInterface: { 1656 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1657 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1658 Width = toBits(Layout.getSize()); 1659 Align = toBits(Layout.getAlignment()); 1660 break; 1661 } 1662 case Type::Record: 1663 case Type::Enum: { 1664 const TagType *TT = cast<TagType>(T); 1665 1666 if (TT->getDecl()->isInvalidDecl()) { 1667 Width = 8; 1668 Align = 8; 1669 break; 1670 } 1671 1672 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 1673 return getTypeInfo(ET->getDecl()->getIntegerType()); 1674 1675 const RecordType *RT = cast<RecordType>(TT); 1676 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 1677 Width = toBits(Layout.getSize()); 1678 Align = toBits(Layout.getAlignment()); 1679 break; 1680 } 1681 1682 case Type::SubstTemplateTypeParm: 1683 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1684 getReplacementType().getTypePtr()); 1685 1686 case Type::Auto: { 1687 const AutoType *A = cast<AutoType>(T); 1688 assert(!A->getDeducedType().isNull() && 1689 "cannot request the size of an undeduced or dependent auto type"); 1690 return getTypeInfo(A->getDeducedType().getTypePtr()); 1691 } 1692 1693 case Type::Paren: 1694 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1695 1696 case Type::Typedef: { 1697 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1698 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1699 // If the typedef has an aligned attribute on it, it overrides any computed 1700 // alignment we have. This violates the GCC documentation (which says that 1701 // attribute(aligned) can only round up) but matches its implementation. 1702 if (unsigned AttrAlign = Typedef->getMaxAlignment()) { 1703 Align = AttrAlign; 1704 AlignIsRequired = true; 1705 } else { 1706 Align = Info.Align; 1707 AlignIsRequired = Info.AlignIsRequired; 1708 } 1709 Width = Info.Width; 1710 break; 1711 } 1712 1713 case Type::Elaborated: 1714 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1715 1716 case Type::Attributed: 1717 return getTypeInfo( 1718 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1719 1720 case Type::Atomic: { 1721 // Start with the base type information. 1722 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1723 Width = Info.Width; 1724 Align = Info.Align; 1725 1726 // If the size of the type doesn't exceed the platform's max 1727 // atomic promotion width, make the size and alignment more 1728 // favorable to atomic operations: 1729 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) { 1730 // Round the size up to a power of 2. 1731 if (!llvm::isPowerOf2_64(Width)) 1732 Width = llvm::NextPowerOf2(Width); 1733 1734 // Set the alignment equal to the size. 1735 Align = static_cast<unsigned>(Width); 1736 } 1737 } 1738 1739 } 1740 1741 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1742 return TypeInfo(Width, Align, AlignIsRequired); 1743} 1744 1745/// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1746CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1747 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1748} 1749 1750/// toBits - Convert a size in characters to a size in characters. 1751int64_t ASTContext::toBits(CharUnits CharSize) const { 1752 return CharSize.getQuantity() * getCharWidth(); 1753} 1754 1755/// getTypeSizeInChars - Return the size of the specified type, in characters. 1756/// This method does not work on incomplete types. 1757CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1758 return getTypeInfoInChars(T).first; 1759} 1760CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1761 return getTypeInfoInChars(T).first; 1762} 1763 1764/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1765/// characters. This method does not work on incomplete types. 1766CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1767 return toCharUnitsFromBits(getTypeAlign(T)); 1768} 1769CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1770 return toCharUnitsFromBits(getTypeAlign(T)); 1771} 1772 1773/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1774/// type for the current target in bits. This can be different than the ABI 1775/// alignment in cases where it is beneficial for performance to overalign 1776/// a data type. 1777unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1778 TypeInfo TI = getTypeInfo(T); 1779 unsigned ABIAlign = TI.Align; 1780 1781 if (Target->getTriple().getArch() == llvm::Triple::xcore) 1782 return ABIAlign; // Never overalign on XCore. 1783 1784 // Double and long long should be naturally aligned if possible. 1785 T = T->getBaseElementTypeUnsafe(); 1786 if (const ComplexType *CT = T->getAs<ComplexType>()) 1787 T = CT->getElementType().getTypePtr(); 1788 if (T->isSpecificBuiltinType(BuiltinType::Double) || 1789 T->isSpecificBuiltinType(BuiltinType::LongLong) || 1790 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 1791 // Don't increase the alignment if an alignment attribute was specified on a 1792 // typedef declaration. 1793 if (!TI.AlignIsRequired) 1794 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 1795 1796 return ABIAlign; 1797} 1798 1799/// getAlignOfGlobalVar - Return the alignment in bits that should be given 1800/// to a global variable of the specified type. 1801unsigned ASTContext::getAlignOfGlobalVar(QualType T) const { 1802 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign()); 1803} 1804 1805/// getAlignOfGlobalVarInChars - Return the alignment in characters that 1806/// should be given to a global variable of the specified type. 1807CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const { 1808 return toCharUnitsFromBits(getAlignOfGlobalVar(T)); 1809} 1810 1811/// DeepCollectObjCIvars - 1812/// This routine first collects all declared, but not synthesized, ivars in 1813/// super class and then collects all ivars, including those synthesized for 1814/// current class. This routine is used for implementation of current class 1815/// when all ivars, declared and synthesized are known. 1816/// 1817void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 1818 bool leafClass, 1819 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 1820 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 1821 DeepCollectObjCIvars(SuperClass, false, Ivars); 1822 if (!leafClass) { 1823 for (const auto *I : OI->ivars()) 1824 Ivars.push_back(I); 1825 } else { 1826 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 1827 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 1828 Iv= Iv->getNextIvar()) 1829 Ivars.push_back(Iv); 1830 } 1831} 1832 1833/// CollectInheritedProtocols - Collect all protocols in current class and 1834/// those inherited by it. 1835void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 1836 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 1837 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1838 // We can use protocol_iterator here instead of 1839 // all_referenced_protocol_iterator since we are walking all categories. 1840 for (auto *Proto : OI->all_referenced_protocols()) { 1841 Protocols.insert(Proto->getCanonicalDecl()); 1842 for (auto *P : Proto->protocols()) { 1843 Protocols.insert(P->getCanonicalDecl()); 1844 CollectInheritedProtocols(P, Protocols); 1845 } 1846 } 1847 1848 // Categories of this Interface. 1849 for (const auto *Cat : OI->visible_categories()) 1850 CollectInheritedProtocols(Cat, Protocols); 1851 1852 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 1853 while (SD) { 1854 CollectInheritedProtocols(SD, Protocols); 1855 SD = SD->getSuperClass(); 1856 } 1857 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1858 for (auto *Proto : OC->protocols()) { 1859 Protocols.insert(Proto->getCanonicalDecl()); 1860 for (const auto *P : Proto->protocols()) 1861 CollectInheritedProtocols(P, Protocols); 1862 } 1863 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1864 for (auto *Proto : OP->protocols()) { 1865 Protocols.insert(Proto->getCanonicalDecl()); 1866 for (const auto *P : Proto->protocols()) 1867 CollectInheritedProtocols(P, Protocols); 1868 } 1869 } 1870} 1871 1872unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 1873 unsigned count = 0; 1874 // Count ivars declared in class extension. 1875 for (const auto *Ext : OI->known_extensions()) 1876 count += Ext->ivar_size(); 1877 1878 // Count ivar defined in this class's implementation. This 1879 // includes synthesized ivars. 1880 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 1881 count += ImplDecl->ivar_size(); 1882 1883 return count; 1884} 1885 1886bool ASTContext::isSentinelNullExpr(const Expr *E) { 1887 if (!E) 1888 return false; 1889 1890 // nullptr_t is always treated as null. 1891 if (E->getType()->isNullPtrType()) return true; 1892 1893 if (E->getType()->isAnyPointerType() && 1894 E->IgnoreParenCasts()->isNullPointerConstant(*this, 1895 Expr::NPC_ValueDependentIsNull)) 1896 return true; 1897 1898 // Unfortunately, __null has type 'int'. 1899 if (isa<GNUNullExpr>(E)) return true; 1900 1901 return false; 1902} 1903 1904/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 1905ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 1906 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1907 I = ObjCImpls.find(D); 1908 if (I != ObjCImpls.end()) 1909 return cast<ObjCImplementationDecl>(I->second); 1910 return nullptr; 1911} 1912/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 1913ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 1914 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1915 I = ObjCImpls.find(D); 1916 if (I != ObjCImpls.end()) 1917 return cast<ObjCCategoryImplDecl>(I->second); 1918 return nullptr; 1919} 1920 1921/// \brief Set the implementation of ObjCInterfaceDecl. 1922void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1923 ObjCImplementationDecl *ImplD) { 1924 assert(IFaceD && ImplD && "Passed null params"); 1925 ObjCImpls[IFaceD] = ImplD; 1926} 1927/// \brief Set the implementation of ObjCCategoryDecl. 1928void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1929 ObjCCategoryImplDecl *ImplD) { 1930 assert(CatD && ImplD && "Passed null params"); 1931 ObjCImpls[CatD] = ImplD; 1932} 1933 1934const ObjCInterfaceDecl *ASTContext::getObjContainingInterface( 1935 const NamedDecl *ND) const { 1936 if (const ObjCInterfaceDecl *ID = 1937 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 1938 return ID; 1939 if (const ObjCCategoryDecl *CD = 1940 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 1941 return CD->getClassInterface(); 1942 if (const ObjCImplDecl *IMD = 1943 dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 1944 return IMD->getClassInterface(); 1945 1946 return nullptr; 1947} 1948 1949/// \brief Get the copy initialization expression of VarDecl,or NULL if 1950/// none exists. 1951Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1952 assert(VD && "Passed null params"); 1953 assert(VD->hasAttr<BlocksAttr>() && 1954 "getBlockVarCopyInits - not __block var"); 1955 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1956 I = BlockVarCopyInits.find(VD); 1957 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr; 1958} 1959 1960/// \brief Set the copy inialization expression of a block var decl. 1961void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1962 assert(VD && Init && "Passed null params"); 1963 assert(VD->hasAttr<BlocksAttr>() && 1964 "setBlockVarCopyInits - not __block var"); 1965 BlockVarCopyInits[VD] = Init; 1966} 1967 1968TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1969 unsigned DataSize) const { 1970 if (!DataSize) 1971 DataSize = TypeLoc::getFullDataSizeForType(T); 1972 else 1973 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1974 "incorrect data size provided to CreateTypeSourceInfo!"); 1975 1976 TypeSourceInfo *TInfo = 1977 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1978 new (TInfo) TypeSourceInfo(T); 1979 return TInfo; 1980} 1981 1982TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1983 SourceLocation L) const { 1984 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1985 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 1986 return DI; 1987} 1988 1989const ASTRecordLayout & 1990ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 1991 return getObjCLayout(D, nullptr); 1992} 1993 1994const ASTRecordLayout & 1995ASTContext::getASTObjCImplementationLayout( 1996 const ObjCImplementationDecl *D) const { 1997 return getObjCLayout(D->getClassInterface(), D); 1998} 1999 2000//===----------------------------------------------------------------------===// 2001// Type creation/memoization methods 2002//===----------------------------------------------------------------------===// 2003 2004QualType 2005ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 2006 unsigned fastQuals = quals.getFastQualifiers(); 2007 quals.removeFastQualifiers(); 2008 2009 // Check if we've already instantiated this type. 2010 llvm::FoldingSetNodeID ID; 2011 ExtQuals::Profile(ID, baseType, quals); 2012 void *insertPos = nullptr; 2013 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 2014 assert(eq->getQualifiers() == quals); 2015 return QualType(eq, fastQuals); 2016 } 2017 2018 // If the base type is not canonical, make the appropriate canonical type. 2019 QualType canon; 2020 if (!baseType->isCanonicalUnqualified()) { 2021 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 2022 canonSplit.Quals.addConsistentQualifiers(quals); 2023 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 2024 2025 // Re-find the insert position. 2026 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 2027 } 2028 2029 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 2030 ExtQualNodes.InsertNode(eq, insertPos); 2031 return QualType(eq, fastQuals); 2032} 2033 2034QualType 2035ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 2036 QualType CanT = getCanonicalType(T); 2037 if (CanT.getAddressSpace() == AddressSpace) 2038 return T; 2039 2040 // If we are composing extended qualifiers together, merge together 2041 // into one ExtQuals node. 2042 QualifierCollector Quals; 2043 const Type *TypeNode = Quals.strip(T); 2044 2045 // If this type already has an address space specified, it cannot get 2046 // another one. 2047 assert(!Quals.hasAddressSpace() && 2048 "Type cannot be in multiple addr spaces!"); 2049 Quals.addAddressSpace(AddressSpace); 2050 2051 return getExtQualType(TypeNode, Quals); 2052} 2053 2054QualType ASTContext::getObjCGCQualType(QualType T, 2055 Qualifiers::GC GCAttr) const { 2056 QualType CanT = getCanonicalType(T); 2057 if (CanT.getObjCGCAttr() == GCAttr) 2058 return T; 2059 2060 if (const PointerType *ptr = T->getAs<PointerType>()) { 2061 QualType Pointee = ptr->getPointeeType(); 2062 if (Pointee->isAnyPointerType()) { 2063 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 2064 return getPointerType(ResultType); 2065 } 2066 } 2067 2068 // If we are composing extended qualifiers together, merge together 2069 // into one ExtQuals node. 2070 QualifierCollector Quals; 2071 const Type *TypeNode = Quals.strip(T); 2072 2073 // If this type already has an ObjCGC specified, it cannot get 2074 // another one. 2075 assert(!Quals.hasObjCGCAttr() && 2076 "Type cannot have multiple ObjCGCs!"); 2077 Quals.addObjCGCAttr(GCAttr); 2078 2079 return getExtQualType(TypeNode, Quals); 2080} 2081 2082const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 2083 FunctionType::ExtInfo Info) { 2084 if (T->getExtInfo() == Info) 2085 return T; 2086 2087 QualType Result; 2088 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 2089 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info); 2090 } else { 2091 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 2092 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2093 EPI.ExtInfo = Info; 2094 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI); 2095 } 2096 2097 return cast<FunctionType>(Result.getTypePtr()); 2098} 2099 2100void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD, 2101 QualType ResultType) { 2102 FD = FD->getMostRecentDecl(); 2103 while (true) { 2104 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 2105 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 2106 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI)); 2107 if (FunctionDecl *Next = FD->getPreviousDecl()) 2108 FD = Next; 2109 else 2110 break; 2111 } 2112 if (ASTMutationListener *L = getASTMutationListener()) 2113 L->DeducedReturnType(FD, ResultType); 2114} 2115 2116/// Get a function type and produce the equivalent function type with the 2117/// specified exception specification. Type sugar that can be present on a 2118/// declaration of a function with an exception specification is permitted 2119/// and preserved. Other type sugar (for instance, typedefs) is not. 2120static QualType getFunctionTypeWithExceptionSpec( 2121 ASTContext &Context, QualType Orig, 2122 const FunctionProtoType::ExceptionSpecInfo &ESI) { 2123 // Might have some parens. 2124 if (auto *PT = dyn_cast<ParenType>(Orig)) 2125 return Context.getParenType( 2126 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI)); 2127 2128 // Might have a calling-convention attribute. 2129 if (auto *AT = dyn_cast<AttributedType>(Orig)) 2130 return Context.getAttributedType( 2131 AT->getAttrKind(), 2132 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI), 2133 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(), 2134 ESI)); 2135 2136 // Anything else must be a function type. Rebuild it with the new exception 2137 // specification. 2138 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig); 2139 return Context.getFunctionType( 2140 Proto->getReturnType(), Proto->getParamTypes(), 2141 Proto->getExtProtoInfo().withExceptionSpec(ESI)); 2142} 2143 2144void ASTContext::adjustExceptionSpec( 2145 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI, 2146 bool AsWritten) { 2147 // Update the type. 2148 QualType Updated = 2149 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI); 2150 FD->setType(Updated); 2151 2152 if (!AsWritten) 2153 return; 2154 2155 // Update the type in the type source information too. 2156 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) { 2157 // If the type and the type-as-written differ, we may need to update 2158 // the type-as-written too. 2159 if (TSInfo->getType() != FD->getType()) 2160 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI); 2161 2162 // FIXME: When we get proper type location information for exceptions, 2163 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch 2164 // up the TypeSourceInfo; 2165 assert(TypeLoc::getFullDataSizeForType(Updated) == 2166 TypeLoc::getFullDataSizeForType(TSInfo->getType()) && 2167 "TypeLoc size mismatch from updating exception specification"); 2168 TSInfo->overrideType(Updated); 2169 } 2170} 2171 2172/// getComplexType - Return the uniqued reference to the type for a complex 2173/// number with the specified element type. 2174QualType ASTContext::getComplexType(QualType T) const { 2175 // Unique pointers, to guarantee there is only one pointer of a particular 2176 // structure. 2177 llvm::FoldingSetNodeID ID; 2178 ComplexType::Profile(ID, T); 2179 2180 void *InsertPos = nullptr; 2181 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 2182 return QualType(CT, 0); 2183 2184 // If the pointee type isn't canonical, this won't be a canonical type either, 2185 // so fill in the canonical type field. 2186 QualType Canonical; 2187 if (!T.isCanonical()) { 2188 Canonical = getComplexType(getCanonicalType(T)); 2189 2190 // Get the new insert position for the node we care about. 2191 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 2192 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2193 } 2194 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 2195 Types.push_back(New); 2196 ComplexTypes.InsertNode(New, InsertPos); 2197 return QualType(New, 0); 2198} 2199 2200/// getPointerType - Return the uniqued reference to the type for a pointer to 2201/// the specified type. 2202QualType ASTContext::getPointerType(QualType T) const { 2203 // Unique pointers, to guarantee there is only one pointer of a particular 2204 // structure. 2205 llvm::FoldingSetNodeID ID; 2206 PointerType::Profile(ID, T); 2207 2208 void *InsertPos = nullptr; 2209 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2210 return QualType(PT, 0); 2211 2212 // If the pointee type isn't canonical, this won't be a canonical type either, 2213 // so fill in the canonical type field. 2214 QualType Canonical; 2215 if (!T.isCanonical()) { 2216 Canonical = getPointerType(getCanonicalType(T)); 2217 2218 // Get the new insert position for the node we care about. 2219 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2220 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2221 } 2222 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 2223 Types.push_back(New); 2224 PointerTypes.InsertNode(New, InsertPos); 2225 return QualType(New, 0); 2226} 2227 2228QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const { 2229 llvm::FoldingSetNodeID ID; 2230 AdjustedType::Profile(ID, Orig, New); 2231 void *InsertPos = nullptr; 2232 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2233 if (AT) 2234 return QualType(AT, 0); 2235 2236 QualType Canonical = getCanonicalType(New); 2237 2238 // Get the new insert position for the node we care about. 2239 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2240 assert(!AT && "Shouldn't be in the map!"); 2241 2242 AT = new (*this, TypeAlignment) 2243 AdjustedType(Type::Adjusted, Orig, New, Canonical); 2244 Types.push_back(AT); 2245 AdjustedTypes.InsertNode(AT, InsertPos); 2246 return QualType(AT, 0); 2247} 2248 2249QualType ASTContext::getDecayedType(QualType T) const { 2250 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay"); 2251 2252 QualType Decayed; 2253 2254 // C99 6.7.5.3p7: 2255 // A declaration of a parameter as "array of type" shall be 2256 // adjusted to "qualified pointer to type", where the type 2257 // qualifiers (if any) are those specified within the [ and ] of 2258 // the array type derivation. 2259 if (T->isArrayType()) 2260 Decayed = getArrayDecayedType(T); 2261 2262 // C99 6.7.5.3p8: 2263 // A declaration of a parameter as "function returning type" 2264 // shall be adjusted to "pointer to function returning type", as 2265 // in 6.3.2.1. 2266 if (T->isFunctionType()) 2267 Decayed = getPointerType(T); 2268 2269 llvm::FoldingSetNodeID ID; 2270 AdjustedType::Profile(ID, T, Decayed); 2271 void *InsertPos = nullptr; 2272 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2273 if (AT) 2274 return QualType(AT, 0); 2275 2276 QualType Canonical = getCanonicalType(Decayed); 2277 2278 // Get the new insert position for the node we care about. 2279 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos); 2280 assert(!AT && "Shouldn't be in the map!"); 2281 2282 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical); 2283 Types.push_back(AT); 2284 AdjustedTypes.InsertNode(AT, InsertPos); 2285 return QualType(AT, 0); 2286} 2287 2288/// getBlockPointerType - Return the uniqued reference to the type for 2289/// a pointer to the specified block. 2290QualType ASTContext::getBlockPointerType(QualType T) const { 2291 assert(T->isFunctionType() && "block of function types only"); 2292 // Unique pointers, to guarantee there is only one block of a particular 2293 // structure. 2294 llvm::FoldingSetNodeID ID; 2295 BlockPointerType::Profile(ID, T); 2296 2297 void *InsertPos = nullptr; 2298 if (BlockPointerType *PT = 2299 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2300 return QualType(PT, 0); 2301 2302 // If the block pointee type isn't canonical, this won't be a canonical 2303 // type either so fill in the canonical type field. 2304 QualType Canonical; 2305 if (!T.isCanonical()) { 2306 Canonical = getBlockPointerType(getCanonicalType(T)); 2307 2308 // Get the new insert position for the node we care about. 2309 BlockPointerType *NewIP = 2310 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2311 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2312 } 2313 BlockPointerType *New 2314 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 2315 Types.push_back(New); 2316 BlockPointerTypes.InsertNode(New, InsertPos); 2317 return QualType(New, 0); 2318} 2319 2320/// getLValueReferenceType - Return the uniqued reference to the type for an 2321/// lvalue reference to the specified type. 2322QualType 2323ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 2324 assert(getCanonicalType(T) != OverloadTy && 2325 "Unresolved overloaded function type"); 2326 2327 // Unique pointers, to guarantee there is only one pointer of a particular 2328 // structure. 2329 llvm::FoldingSetNodeID ID; 2330 ReferenceType::Profile(ID, T, SpelledAsLValue); 2331 2332 void *InsertPos = nullptr; 2333 if (LValueReferenceType *RT = 2334 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2335 return QualType(RT, 0); 2336 2337 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2338 2339 // If the referencee type isn't canonical, this won't be a canonical type 2340 // either, so fill in the canonical type field. 2341 QualType Canonical; 2342 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 2343 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2344 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 2345 2346 // Get the new insert position for the node we care about. 2347 LValueReferenceType *NewIP = 2348 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2349 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2350 } 2351 2352 LValueReferenceType *New 2353 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 2354 SpelledAsLValue); 2355 Types.push_back(New); 2356 LValueReferenceTypes.InsertNode(New, InsertPos); 2357 2358 return QualType(New, 0); 2359} 2360 2361/// getRValueReferenceType - Return the uniqued reference to the type for an 2362/// rvalue reference to the specified type. 2363QualType ASTContext::getRValueReferenceType(QualType T) const { 2364 // Unique pointers, to guarantee there is only one pointer of a particular 2365 // structure. 2366 llvm::FoldingSetNodeID ID; 2367 ReferenceType::Profile(ID, T, false); 2368 2369 void *InsertPos = nullptr; 2370 if (RValueReferenceType *RT = 2371 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 2372 return QualType(RT, 0); 2373 2374 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 2375 2376 // If the referencee type isn't canonical, this won't be a canonical type 2377 // either, so fill in the canonical type field. 2378 QualType Canonical; 2379 if (InnerRef || !T.isCanonical()) { 2380 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 2381 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 2382 2383 // Get the new insert position for the node we care about. 2384 RValueReferenceType *NewIP = 2385 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 2386 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2387 } 2388 2389 RValueReferenceType *New 2390 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 2391 Types.push_back(New); 2392 RValueReferenceTypes.InsertNode(New, InsertPos); 2393 return QualType(New, 0); 2394} 2395 2396/// getMemberPointerType - Return the uniqued reference to the type for a 2397/// member pointer to the specified type, in the specified class. 2398QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 2399 // Unique pointers, to guarantee there is only one pointer of a particular 2400 // structure. 2401 llvm::FoldingSetNodeID ID; 2402 MemberPointerType::Profile(ID, T, Cls); 2403 2404 void *InsertPos = nullptr; 2405 if (MemberPointerType *PT = 2406 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2407 return QualType(PT, 0); 2408 2409 // If the pointee or class type isn't canonical, this won't be a canonical 2410 // type either, so fill in the canonical type field. 2411 QualType Canonical; 2412 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 2413 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 2414 2415 // Get the new insert position for the node we care about. 2416 MemberPointerType *NewIP = 2417 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2418 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2419 } 2420 MemberPointerType *New 2421 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 2422 Types.push_back(New); 2423 MemberPointerTypes.InsertNode(New, InsertPos); 2424 return QualType(New, 0); 2425} 2426 2427/// getConstantArrayType - Return the unique reference to the type for an 2428/// array of the specified element type. 2429QualType ASTContext::getConstantArrayType(QualType EltTy, 2430 const llvm::APInt &ArySizeIn, 2431 ArrayType::ArraySizeModifier ASM, 2432 unsigned IndexTypeQuals) const { 2433 assert((EltTy->isDependentType() || 2434 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 2435 "Constant array of VLAs is illegal!"); 2436 2437 // Convert the array size into a canonical width matching the pointer size for 2438 // the target. 2439 llvm::APInt ArySize(ArySizeIn); 2440 ArySize = 2441 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 2442 2443 llvm::FoldingSetNodeID ID; 2444 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 2445 2446 void *InsertPos = nullptr; 2447 if (ConstantArrayType *ATP = 2448 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 2449 return QualType(ATP, 0); 2450 2451 // If the element type isn't canonical or has qualifiers, this won't 2452 // be a canonical type either, so fill in the canonical type field. 2453 QualType Canon; 2454 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2455 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2456 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 2457 ASM, IndexTypeQuals); 2458 Canon = getQualifiedType(Canon, canonSplit.Quals); 2459 2460 // Get the new insert position for the node we care about. 2461 ConstantArrayType *NewIP = 2462 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 2463 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2464 } 2465 2466 ConstantArrayType *New = new(*this,TypeAlignment) 2467 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 2468 ConstantArrayTypes.InsertNode(New, InsertPos); 2469 Types.push_back(New); 2470 return QualType(New, 0); 2471} 2472 2473/// getVariableArrayDecayedType - Turns the given type, which may be 2474/// variably-modified, into the corresponding type with all the known 2475/// sizes replaced with [*]. 2476QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 2477 // Vastly most common case. 2478 if (!type->isVariablyModifiedType()) return type; 2479 2480 QualType result; 2481 2482 SplitQualType split = type.getSplitDesugaredType(); 2483 const Type *ty = split.Ty; 2484 switch (ty->getTypeClass()) { 2485#define TYPE(Class, Base) 2486#define ABSTRACT_TYPE(Class, Base) 2487#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 2488#include "clang/AST/TypeNodes.def" 2489 llvm_unreachable("didn't desugar past all non-canonical types?"); 2490 2491 // These types should never be variably-modified. 2492 case Type::Builtin: 2493 case Type::Complex: 2494 case Type::Vector: 2495 case Type::ExtVector: 2496 case Type::DependentSizedExtVector: 2497 case Type::ObjCObject: 2498 case Type::ObjCInterface: 2499 case Type::ObjCObjectPointer: 2500 case Type::Record: 2501 case Type::Enum: 2502 case Type::UnresolvedUsing: 2503 case Type::TypeOfExpr: 2504 case Type::TypeOf: 2505 case Type::Decltype: 2506 case Type::UnaryTransform: 2507 case Type::DependentName: 2508 case Type::InjectedClassName: 2509 case Type::TemplateSpecialization: 2510 case Type::DependentTemplateSpecialization: 2511 case Type::TemplateTypeParm: 2512 case Type::SubstTemplateTypeParmPack: 2513 case Type::Auto: 2514 case Type::PackExpansion: 2515 llvm_unreachable("type should never be variably-modified"); 2516 2517 // These types can be variably-modified but should never need to 2518 // further decay. 2519 case Type::FunctionNoProto: 2520 case Type::FunctionProto: 2521 case Type::BlockPointer: 2522 case Type::MemberPointer: 2523 return type; 2524 2525 // These types can be variably-modified. All these modifications 2526 // preserve structure except as noted by comments. 2527 // TODO: if we ever care about optimizing VLAs, there are no-op 2528 // optimizations available here. 2529 case Type::Pointer: 2530 result = getPointerType(getVariableArrayDecayedType( 2531 cast<PointerType>(ty)->getPointeeType())); 2532 break; 2533 2534 case Type::LValueReference: { 2535 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 2536 result = getLValueReferenceType( 2537 getVariableArrayDecayedType(lv->getPointeeType()), 2538 lv->isSpelledAsLValue()); 2539 break; 2540 } 2541 2542 case Type::RValueReference: { 2543 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 2544 result = getRValueReferenceType( 2545 getVariableArrayDecayedType(lv->getPointeeType())); 2546 break; 2547 } 2548 2549 case Type::Atomic: { 2550 const AtomicType *at = cast<AtomicType>(ty); 2551 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 2552 break; 2553 } 2554 2555 case Type::ConstantArray: { 2556 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 2557 result = getConstantArrayType( 2558 getVariableArrayDecayedType(cat->getElementType()), 2559 cat->getSize(), 2560 cat->getSizeModifier(), 2561 cat->getIndexTypeCVRQualifiers()); 2562 break; 2563 } 2564 2565 case Type::DependentSizedArray: { 2566 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 2567 result = getDependentSizedArrayType( 2568 getVariableArrayDecayedType(dat->getElementType()), 2569 dat->getSizeExpr(), 2570 dat->getSizeModifier(), 2571 dat->getIndexTypeCVRQualifiers(), 2572 dat->getBracketsRange()); 2573 break; 2574 } 2575 2576 // Turn incomplete types into [*] types. 2577 case Type::IncompleteArray: { 2578 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 2579 result = getVariableArrayType( 2580 getVariableArrayDecayedType(iat->getElementType()), 2581 /*size*/ nullptr, 2582 ArrayType::Normal, 2583 iat->getIndexTypeCVRQualifiers(), 2584 SourceRange()); 2585 break; 2586 } 2587 2588 // Turn VLA types into [*] types. 2589 case Type::VariableArray: { 2590 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2591 result = getVariableArrayType( 2592 getVariableArrayDecayedType(vat->getElementType()), 2593 /*size*/ nullptr, 2594 ArrayType::Star, 2595 vat->getIndexTypeCVRQualifiers(), 2596 vat->getBracketsRange()); 2597 break; 2598 } 2599 } 2600 2601 // Apply the top-level qualifiers from the original. 2602 return getQualifiedType(result, split.Quals); 2603} 2604 2605/// getVariableArrayType - Returns a non-unique reference to the type for a 2606/// variable array of the specified element type. 2607QualType ASTContext::getVariableArrayType(QualType EltTy, 2608 Expr *NumElts, 2609 ArrayType::ArraySizeModifier ASM, 2610 unsigned IndexTypeQuals, 2611 SourceRange Brackets) const { 2612 // Since we don't unique expressions, it isn't possible to unique VLA's 2613 // that have an expression provided for their size. 2614 QualType Canon; 2615 2616 // Be sure to pull qualifiers off the element type. 2617 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2618 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2619 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 2620 IndexTypeQuals, Brackets); 2621 Canon = getQualifiedType(Canon, canonSplit.Quals); 2622 } 2623 2624 VariableArrayType *New = new(*this, TypeAlignment) 2625 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 2626 2627 VariableArrayTypes.push_back(New); 2628 Types.push_back(New); 2629 return QualType(New, 0); 2630} 2631 2632/// getDependentSizedArrayType - Returns a non-unique reference to 2633/// the type for a dependently-sized array of the specified element 2634/// type. 2635QualType ASTContext::getDependentSizedArrayType(QualType elementType, 2636 Expr *numElements, 2637 ArrayType::ArraySizeModifier ASM, 2638 unsigned elementTypeQuals, 2639 SourceRange brackets) const { 2640 assert((!numElements || numElements->isTypeDependent() || 2641 numElements->isValueDependent()) && 2642 "Size must be type- or value-dependent!"); 2643 2644 // Dependently-sized array types that do not have a specified number 2645 // of elements will have their sizes deduced from a dependent 2646 // initializer. We do no canonicalization here at all, which is okay 2647 // because they can't be used in most locations. 2648 if (!numElements) { 2649 DependentSizedArrayType *newType 2650 = new (*this, TypeAlignment) 2651 DependentSizedArrayType(*this, elementType, QualType(), 2652 numElements, ASM, elementTypeQuals, 2653 brackets); 2654 Types.push_back(newType); 2655 return QualType(newType, 0); 2656 } 2657 2658 // Otherwise, we actually build a new type every time, but we 2659 // also build a canonical type. 2660 2661 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2662 2663 void *insertPos = nullptr; 2664 llvm::FoldingSetNodeID ID; 2665 DependentSizedArrayType::Profile(ID, *this, 2666 QualType(canonElementType.Ty, 0), 2667 ASM, elementTypeQuals, numElements); 2668 2669 // Look for an existing type with these properties. 2670 DependentSizedArrayType *canonTy = 2671 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2672 2673 // If we don't have one, build one. 2674 if (!canonTy) { 2675 canonTy = new (*this, TypeAlignment) 2676 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2677 QualType(), numElements, ASM, elementTypeQuals, 2678 brackets); 2679 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2680 Types.push_back(canonTy); 2681 } 2682 2683 // Apply qualifiers from the element type to the array. 2684 QualType canon = getQualifiedType(QualType(canonTy,0), 2685 canonElementType.Quals); 2686 2687 // If we didn't need extra canonicalization for the element type, 2688 // then just use that as our result. 2689 if (QualType(canonElementType.Ty, 0) == elementType) 2690 return canon; 2691 2692 // Otherwise, we need to build a type which follows the spelling 2693 // of the element type. 2694 DependentSizedArrayType *sugaredType 2695 = new (*this, TypeAlignment) 2696 DependentSizedArrayType(*this, elementType, canon, numElements, 2697 ASM, elementTypeQuals, brackets); 2698 Types.push_back(sugaredType); 2699 return QualType(sugaredType, 0); 2700} 2701 2702QualType ASTContext::getIncompleteArrayType(QualType elementType, 2703 ArrayType::ArraySizeModifier ASM, 2704 unsigned elementTypeQuals) const { 2705 llvm::FoldingSetNodeID ID; 2706 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2707 2708 void *insertPos = nullptr; 2709 if (IncompleteArrayType *iat = 2710 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2711 return QualType(iat, 0); 2712 2713 // If the element type isn't canonical, this won't be a canonical type 2714 // either, so fill in the canonical type field. We also have to pull 2715 // qualifiers off the element type. 2716 QualType canon; 2717 2718 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2719 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2720 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2721 ASM, elementTypeQuals); 2722 canon = getQualifiedType(canon, canonSplit.Quals); 2723 2724 // Get the new insert position for the node we care about. 2725 IncompleteArrayType *existing = 2726 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2727 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2728 } 2729 2730 IncompleteArrayType *newType = new (*this, TypeAlignment) 2731 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2732 2733 IncompleteArrayTypes.InsertNode(newType, insertPos); 2734 Types.push_back(newType); 2735 return QualType(newType, 0); 2736} 2737 2738/// getVectorType - Return the unique reference to a vector type of 2739/// the specified element type and size. VectorType must be a built-in type. 2740QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2741 VectorType::VectorKind VecKind) const { 2742 assert(vecType->isBuiltinType()); 2743 2744 // Check if we've already instantiated a vector of this type. 2745 llvm::FoldingSetNodeID ID; 2746 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2747 2748 void *InsertPos = nullptr; 2749 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2750 return QualType(VTP, 0); 2751 2752 // If the element type isn't canonical, this won't be a canonical type either, 2753 // so fill in the canonical type field. 2754 QualType Canonical; 2755 if (!vecType.isCanonical()) { 2756 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 2757 2758 // Get the new insert position for the node we care about. 2759 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2760 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2761 } 2762 VectorType *New = new (*this, TypeAlignment) 2763 VectorType(vecType, NumElts, Canonical, VecKind); 2764 VectorTypes.InsertNode(New, InsertPos); 2765 Types.push_back(New); 2766 return QualType(New, 0); 2767} 2768 2769/// getExtVectorType - Return the unique reference to an extended vector type of 2770/// the specified element type and size. VectorType must be a built-in type. 2771QualType 2772ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 2773 assert(vecType->isBuiltinType() || vecType->isDependentType()); 2774 2775 // Check if we've already instantiated a vector of this type. 2776 llvm::FoldingSetNodeID ID; 2777 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 2778 VectorType::GenericVector); 2779 void *InsertPos = nullptr; 2780 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2781 return QualType(VTP, 0); 2782 2783 // If the element type isn't canonical, this won't be a canonical type either, 2784 // so fill in the canonical type field. 2785 QualType Canonical; 2786 if (!vecType.isCanonical()) { 2787 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 2788 2789 // Get the new insert position for the node we care about. 2790 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2791 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2792 } 2793 ExtVectorType *New = new (*this, TypeAlignment) 2794 ExtVectorType(vecType, NumElts, Canonical); 2795 VectorTypes.InsertNode(New, InsertPos); 2796 Types.push_back(New); 2797 return QualType(New, 0); 2798} 2799 2800QualType 2801ASTContext::getDependentSizedExtVectorType(QualType vecType, 2802 Expr *SizeExpr, 2803 SourceLocation AttrLoc) const { 2804 llvm::FoldingSetNodeID ID; 2805 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 2806 SizeExpr); 2807 2808 void *InsertPos = nullptr; 2809 DependentSizedExtVectorType *Canon 2810 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2811 DependentSizedExtVectorType *New; 2812 if (Canon) { 2813 // We already have a canonical version of this array type; use it as 2814 // the canonical type for a newly-built type. 2815 New = new (*this, TypeAlignment) 2816 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 2817 SizeExpr, AttrLoc); 2818 } else { 2819 QualType CanonVecTy = getCanonicalType(vecType); 2820 if (CanonVecTy == vecType) { 2821 New = new (*this, TypeAlignment) 2822 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 2823 AttrLoc); 2824 2825 DependentSizedExtVectorType *CanonCheck 2826 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2827 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 2828 (void)CanonCheck; 2829 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 2830 } else { 2831 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 2832 SourceLocation()); 2833 New = new (*this, TypeAlignment) 2834 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 2835 } 2836 } 2837 2838 Types.push_back(New); 2839 return QualType(New, 0); 2840} 2841 2842/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 2843/// 2844QualType 2845ASTContext::getFunctionNoProtoType(QualType ResultTy, 2846 const FunctionType::ExtInfo &Info) const { 2847 const CallingConv CallConv = Info.getCC(); 2848 2849 // Unique functions, to guarantee there is only one function of a particular 2850 // structure. 2851 llvm::FoldingSetNodeID ID; 2852 FunctionNoProtoType::Profile(ID, ResultTy, Info); 2853 2854 void *InsertPos = nullptr; 2855 if (FunctionNoProtoType *FT = 2856 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2857 return QualType(FT, 0); 2858 2859 QualType Canonical; 2860 if (!ResultTy.isCanonical()) { 2861 Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info); 2862 2863 // Get the new insert position for the node we care about. 2864 FunctionNoProtoType *NewIP = 2865 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2866 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2867 } 2868 2869 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv); 2870 FunctionNoProtoType *New = new (*this, TypeAlignment) 2871 FunctionNoProtoType(ResultTy, Canonical, newInfo); 2872 Types.push_back(New); 2873 FunctionNoProtoTypes.InsertNode(New, InsertPos); 2874 return QualType(New, 0); 2875} 2876 2877/// \brief Determine whether \p T is canonical as the result type of a function. 2878static bool isCanonicalResultType(QualType T) { 2879 return T.isCanonical() && 2880 (T.getObjCLifetime() == Qualifiers::OCL_None || 2881 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone); 2882} 2883 2884QualType 2885ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray, 2886 const FunctionProtoType::ExtProtoInfo &EPI) const { 2887 size_t NumArgs = ArgArray.size(); 2888 2889 // Unique functions, to guarantee there is only one function of a particular 2890 // structure. 2891 llvm::FoldingSetNodeID ID; 2892 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, 2893 *this); 2894 2895 void *InsertPos = nullptr; 2896 if (FunctionProtoType *FTP = 2897 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2898 return QualType(FTP, 0); 2899 2900 // Determine whether the type being created is already canonical or not. 2901 bool isCanonical = 2902 EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) && 2903 !EPI.HasTrailingReturn; 2904 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 2905 if (!ArgArray[i].isCanonicalAsParam()) 2906 isCanonical = false; 2907 2908 // If this type isn't canonical, get the canonical version of it. 2909 // The exception spec is not part of the canonical type. 2910 QualType Canonical; 2911 if (!isCanonical) { 2912 SmallVector<QualType, 16> CanonicalArgs; 2913 CanonicalArgs.reserve(NumArgs); 2914 for (unsigned i = 0; i != NumArgs; ++i) 2915 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 2916 2917 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 2918 CanonicalEPI.HasTrailingReturn = false; 2919 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo(); 2920 2921 // Result types do not have ARC lifetime qualifiers. 2922 QualType CanResultTy = getCanonicalType(ResultTy); 2923 if (ResultTy.getQualifiers().hasObjCLifetime()) { 2924 Qualifiers Qs = CanResultTy.getQualifiers(); 2925 Qs.removeObjCLifetime(); 2926 CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs); 2927 } 2928 2929 Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI); 2930 2931 // Get the new insert position for the node we care about. 2932 FunctionProtoType *NewIP = 2933 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2934 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 2935 } 2936 2937 // FunctionProtoType objects are allocated with extra bytes after 2938 // them for three variable size arrays at the end: 2939 // - parameter types 2940 // - exception types 2941 // - consumed-arguments flags 2942 // Instead of the exception types, there could be a noexcept 2943 // expression, or information used to resolve the exception 2944 // specification. 2945 size_t Size = sizeof(FunctionProtoType) + 2946 NumArgs * sizeof(QualType); 2947 if (EPI.ExceptionSpec.Type == EST_Dynamic) { 2948 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType); 2949 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) { 2950 Size += sizeof(Expr*); 2951 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) { 2952 Size += 2 * sizeof(FunctionDecl*); 2953 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) { 2954 Size += sizeof(FunctionDecl*); 2955 } 2956 if (EPI.ConsumedParameters) 2957 Size += NumArgs * sizeof(bool); 2958 2959 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 2960 FunctionProtoType::ExtProtoInfo newEPI = EPI; 2961 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI); 2962 Types.push_back(FTP); 2963 FunctionProtoTypes.InsertNode(FTP, InsertPos); 2964 return QualType(FTP, 0); 2965} 2966 2967#ifndef NDEBUG 2968static bool NeedsInjectedClassNameType(const RecordDecl *D) { 2969 if (!isa<CXXRecordDecl>(D)) return false; 2970 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 2971 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 2972 return true; 2973 if (RD->getDescribedClassTemplate() && 2974 !isa<ClassTemplateSpecializationDecl>(RD)) 2975 return true; 2976 return false; 2977} 2978#endif 2979 2980/// getInjectedClassNameType - Return the unique reference to the 2981/// injected class name type for the specified templated declaration. 2982QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 2983 QualType TST) const { 2984 assert(NeedsInjectedClassNameType(Decl)); 2985 if (Decl->TypeForDecl) { 2986 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2987 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 2988 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 2989 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2990 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2991 } else { 2992 Type *newType = 2993 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 2994 Decl->TypeForDecl = newType; 2995 Types.push_back(newType); 2996 } 2997 return QualType(Decl->TypeForDecl, 0); 2998} 2999 3000/// getTypeDeclType - Return the unique reference to the type for the 3001/// specified type declaration. 3002QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 3003 assert(Decl && "Passed null for Decl param"); 3004 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 3005 3006 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 3007 return getTypedefType(Typedef); 3008 3009 assert(!isa<TemplateTypeParmDecl>(Decl) && 3010 "Template type parameter types are always available."); 3011 3012 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 3013 assert(Record->isFirstDecl() && "struct/union has previous declaration"); 3014 assert(!NeedsInjectedClassNameType(Record)); 3015 return getRecordType(Record); 3016 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 3017 assert(Enum->isFirstDecl() && "enum has previous declaration"); 3018 return getEnumType(Enum); 3019 } else if (const UnresolvedUsingTypenameDecl *Using = 3020 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 3021 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 3022 Decl->TypeForDecl = newType; 3023 Types.push_back(newType); 3024 } else 3025 llvm_unreachable("TypeDecl without a type?"); 3026 3027 return QualType(Decl->TypeForDecl, 0); 3028} 3029 3030/// getTypedefType - Return the unique reference to the type for the 3031/// specified typedef name decl. 3032QualType 3033ASTContext::getTypedefType(const TypedefNameDecl *Decl, 3034 QualType Canonical) const { 3035 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3036 3037 if (Canonical.isNull()) 3038 Canonical = getCanonicalType(Decl->getUnderlyingType()); 3039 TypedefType *newType = new(*this, TypeAlignment) 3040 TypedefType(Type::Typedef, Decl, Canonical); 3041 Decl->TypeForDecl = newType; 3042 Types.push_back(newType); 3043 return QualType(newType, 0); 3044} 3045 3046QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 3047 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3048 3049 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 3050 if (PrevDecl->TypeForDecl) 3051 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3052 3053 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 3054 Decl->TypeForDecl = newType; 3055 Types.push_back(newType); 3056 return QualType(newType, 0); 3057} 3058 3059QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 3060 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 3061 3062 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 3063 if (PrevDecl->TypeForDecl) 3064 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 3065 3066 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 3067 Decl->TypeForDecl = newType; 3068 Types.push_back(newType); 3069 return QualType(newType, 0); 3070} 3071 3072QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 3073 QualType modifiedType, 3074 QualType equivalentType) { 3075 llvm::FoldingSetNodeID id; 3076 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 3077 3078 void *insertPos = nullptr; 3079 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 3080 if (type) return QualType(type, 0); 3081 3082 QualType canon = getCanonicalType(equivalentType); 3083 type = new (*this, TypeAlignment) 3084 AttributedType(canon, attrKind, modifiedType, equivalentType); 3085 3086 Types.push_back(type); 3087 AttributedTypes.InsertNode(type, insertPos); 3088 3089 return QualType(type, 0); 3090} 3091 3092 3093/// \brief Retrieve a substitution-result type. 3094QualType 3095ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 3096 QualType Replacement) const { 3097 assert(Replacement.isCanonical() 3098 && "replacement types must always be canonical"); 3099 3100 llvm::FoldingSetNodeID ID; 3101 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 3102 void *InsertPos = nullptr; 3103 SubstTemplateTypeParmType *SubstParm 3104 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3105 3106 if (!SubstParm) { 3107 SubstParm = new (*this, TypeAlignment) 3108 SubstTemplateTypeParmType(Parm, Replacement); 3109 Types.push_back(SubstParm); 3110 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3111 } 3112 3113 return QualType(SubstParm, 0); 3114} 3115 3116/// \brief Retrieve a 3117QualType ASTContext::getSubstTemplateTypeParmPackType( 3118 const TemplateTypeParmType *Parm, 3119 const TemplateArgument &ArgPack) { 3120#ifndef NDEBUG 3121 for (const auto &P : ArgPack.pack_elements()) { 3122 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 3123 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type"); 3124 } 3125#endif 3126 3127 llvm::FoldingSetNodeID ID; 3128 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 3129 void *InsertPos = nullptr; 3130 if (SubstTemplateTypeParmPackType *SubstParm 3131 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 3132 return QualType(SubstParm, 0); 3133 3134 QualType Canon; 3135 if (!Parm->isCanonicalUnqualified()) { 3136 Canon = getCanonicalType(QualType(Parm, 0)); 3137 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 3138 ArgPack); 3139 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 3140 } 3141 3142 SubstTemplateTypeParmPackType *SubstParm 3143 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 3144 ArgPack); 3145 Types.push_back(SubstParm); 3146 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 3147 return QualType(SubstParm, 0); 3148} 3149 3150/// \brief Retrieve the template type parameter type for a template 3151/// parameter or parameter pack with the given depth, index, and (optionally) 3152/// name. 3153QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 3154 bool ParameterPack, 3155 TemplateTypeParmDecl *TTPDecl) const { 3156 llvm::FoldingSetNodeID ID; 3157 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 3158 void *InsertPos = nullptr; 3159 TemplateTypeParmType *TypeParm 3160 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3161 3162 if (TypeParm) 3163 return QualType(TypeParm, 0); 3164 3165 if (TTPDecl) { 3166 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 3167 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 3168 3169 TemplateTypeParmType *TypeCheck 3170 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 3171 assert(!TypeCheck && "Template type parameter canonical type broken"); 3172 (void)TypeCheck; 3173 } else 3174 TypeParm = new (*this, TypeAlignment) 3175 TemplateTypeParmType(Depth, Index, ParameterPack); 3176 3177 Types.push_back(TypeParm); 3178 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 3179 3180 return QualType(TypeParm, 0); 3181} 3182 3183TypeSourceInfo * 3184ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 3185 SourceLocation NameLoc, 3186 const TemplateArgumentListInfo &Args, 3187 QualType Underlying) const { 3188 assert(!Name.getAsDependentTemplateName() && 3189 "No dependent template names here!"); 3190 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 3191 3192 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 3193 TemplateSpecializationTypeLoc TL = 3194 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>(); 3195 TL.setTemplateKeywordLoc(SourceLocation()); 3196 TL.setTemplateNameLoc(NameLoc); 3197 TL.setLAngleLoc(Args.getLAngleLoc()); 3198 TL.setRAngleLoc(Args.getRAngleLoc()); 3199 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 3200 TL.setArgLocInfo(i, Args[i].getLocInfo()); 3201 return DI; 3202} 3203 3204QualType 3205ASTContext::getTemplateSpecializationType(TemplateName Template, 3206 const TemplateArgumentListInfo &Args, 3207 QualType Underlying) const { 3208 assert(!Template.getAsDependentTemplateName() && 3209 "No dependent template names here!"); 3210 3211 unsigned NumArgs = Args.size(); 3212 3213 SmallVector<TemplateArgument, 4> ArgVec; 3214 ArgVec.reserve(NumArgs); 3215 for (unsigned i = 0; i != NumArgs; ++i) 3216 ArgVec.push_back(Args[i].getArgument()); 3217 3218 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 3219 Underlying); 3220} 3221 3222#ifndef NDEBUG 3223static bool hasAnyPackExpansions(const TemplateArgument *Args, 3224 unsigned NumArgs) { 3225 for (unsigned I = 0; I != NumArgs; ++I) 3226 if (Args[I].isPackExpansion()) 3227 return true; 3228 3229 return true; 3230} 3231#endif 3232 3233QualType 3234ASTContext::getTemplateSpecializationType(TemplateName Template, 3235 const TemplateArgument *Args, 3236 unsigned NumArgs, 3237 QualType Underlying) const { 3238 assert(!Template.getAsDependentTemplateName() && 3239 "No dependent template names here!"); 3240 // Look through qualified template names. 3241 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3242 Template = TemplateName(QTN->getTemplateDecl()); 3243 3244 bool IsTypeAlias = 3245 Template.getAsTemplateDecl() && 3246 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 3247 QualType CanonType; 3248 if (!Underlying.isNull()) 3249 CanonType = getCanonicalType(Underlying); 3250 else { 3251 // We can get here with an alias template when the specialization contains 3252 // a pack expansion that does not match up with a parameter pack. 3253 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) && 3254 "Caller must compute aliased type"); 3255 IsTypeAlias = false; 3256 CanonType = getCanonicalTemplateSpecializationType(Template, Args, 3257 NumArgs); 3258 } 3259 3260 // Allocate the (non-canonical) template specialization type, but don't 3261 // try to unique it: these types typically have location information that 3262 // we don't unique and don't want to lose. 3263 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 3264 sizeof(TemplateArgument) * NumArgs + 3265 (IsTypeAlias? sizeof(QualType) : 0), 3266 TypeAlignment); 3267 TemplateSpecializationType *Spec 3268 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType, 3269 IsTypeAlias ? Underlying : QualType()); 3270 3271 Types.push_back(Spec); 3272 return QualType(Spec, 0); 3273} 3274 3275QualType 3276ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 3277 const TemplateArgument *Args, 3278 unsigned NumArgs) const { 3279 assert(!Template.getAsDependentTemplateName() && 3280 "No dependent template names here!"); 3281 3282 // Look through qualified template names. 3283 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 3284 Template = TemplateName(QTN->getTemplateDecl()); 3285 3286 // Build the canonical template specialization type. 3287 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 3288 SmallVector<TemplateArgument, 4> CanonArgs; 3289 CanonArgs.reserve(NumArgs); 3290 for (unsigned I = 0; I != NumArgs; ++I) 3291 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 3292 3293 // Determine whether this canonical template specialization type already 3294 // exists. 3295 llvm::FoldingSetNodeID ID; 3296 TemplateSpecializationType::Profile(ID, CanonTemplate, 3297 CanonArgs.data(), NumArgs, *this); 3298 3299 void *InsertPos = nullptr; 3300 TemplateSpecializationType *Spec 3301 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3302 3303 if (!Spec) { 3304 // Allocate a new canonical template specialization type. 3305 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 3306 sizeof(TemplateArgument) * NumArgs), 3307 TypeAlignment); 3308 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 3309 CanonArgs.data(), NumArgs, 3310 QualType(), QualType()); 3311 Types.push_back(Spec); 3312 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 3313 } 3314 3315 assert(Spec->isDependentType() && 3316 "Non-dependent template-id type must have a canonical type"); 3317 return QualType(Spec, 0); 3318} 3319 3320QualType 3321ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 3322 NestedNameSpecifier *NNS, 3323 QualType NamedType) const { 3324 llvm::FoldingSetNodeID ID; 3325 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 3326 3327 void *InsertPos = nullptr; 3328 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3329 if (T) 3330 return QualType(T, 0); 3331 3332 QualType Canon = NamedType; 3333 if (!Canon.isCanonical()) { 3334 Canon = getCanonicalType(NamedType); 3335 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 3336 assert(!CheckT && "Elaborated canonical type broken"); 3337 (void)CheckT; 3338 } 3339 3340 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 3341 Types.push_back(T); 3342 ElaboratedTypes.InsertNode(T, InsertPos); 3343 return QualType(T, 0); 3344} 3345 3346QualType 3347ASTContext::getParenType(QualType InnerType) const { 3348 llvm::FoldingSetNodeID ID; 3349 ParenType::Profile(ID, InnerType); 3350 3351 void *InsertPos = nullptr; 3352 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3353 if (T) 3354 return QualType(T, 0); 3355 3356 QualType Canon = InnerType; 3357 if (!Canon.isCanonical()) { 3358 Canon = getCanonicalType(InnerType); 3359 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 3360 assert(!CheckT && "Paren canonical type broken"); 3361 (void)CheckT; 3362 } 3363 3364 T = new (*this) ParenType(InnerType, Canon); 3365 Types.push_back(T); 3366 ParenTypes.InsertNode(T, InsertPos); 3367 return QualType(T, 0); 3368} 3369 3370QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 3371 NestedNameSpecifier *NNS, 3372 const IdentifierInfo *Name, 3373 QualType Canon) const { 3374 if (Canon.isNull()) { 3375 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3376 ElaboratedTypeKeyword CanonKeyword = Keyword; 3377 if (Keyword == ETK_None) 3378 CanonKeyword = ETK_Typename; 3379 3380 if (CanonNNS != NNS || CanonKeyword != Keyword) 3381 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 3382 } 3383 3384 llvm::FoldingSetNodeID ID; 3385 DependentNameType::Profile(ID, Keyword, NNS, Name); 3386 3387 void *InsertPos = nullptr; 3388 DependentNameType *T 3389 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 3390 if (T) 3391 return QualType(T, 0); 3392 3393 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 3394 Types.push_back(T); 3395 DependentNameTypes.InsertNode(T, InsertPos); 3396 return QualType(T, 0); 3397} 3398 3399QualType 3400ASTContext::getDependentTemplateSpecializationType( 3401 ElaboratedTypeKeyword Keyword, 3402 NestedNameSpecifier *NNS, 3403 const IdentifierInfo *Name, 3404 const TemplateArgumentListInfo &Args) const { 3405 // TODO: avoid this copy 3406 SmallVector<TemplateArgument, 16> ArgCopy; 3407 for (unsigned I = 0, E = Args.size(); I != E; ++I) 3408 ArgCopy.push_back(Args[I].getArgument()); 3409 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 3410 ArgCopy.size(), 3411 ArgCopy.data()); 3412} 3413 3414QualType 3415ASTContext::getDependentTemplateSpecializationType( 3416 ElaboratedTypeKeyword Keyword, 3417 NestedNameSpecifier *NNS, 3418 const IdentifierInfo *Name, 3419 unsigned NumArgs, 3420 const TemplateArgument *Args) const { 3421 assert((!NNS || NNS->isDependent()) && 3422 "nested-name-specifier must be dependent"); 3423 3424 llvm::FoldingSetNodeID ID; 3425 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 3426 Name, NumArgs, Args); 3427 3428 void *InsertPos = nullptr; 3429 DependentTemplateSpecializationType *T 3430 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3431 if (T) 3432 return QualType(T, 0); 3433 3434 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 3435 3436 ElaboratedTypeKeyword CanonKeyword = Keyword; 3437 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 3438 3439 bool AnyNonCanonArgs = false; 3440 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 3441 for (unsigned I = 0; I != NumArgs; ++I) { 3442 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 3443 if (!CanonArgs[I].structurallyEquals(Args[I])) 3444 AnyNonCanonArgs = true; 3445 } 3446 3447 QualType Canon; 3448 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 3449 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 3450 Name, NumArgs, 3451 CanonArgs.data()); 3452 3453 // Find the insert position again. 3454 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 3455 } 3456 3457 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 3458 sizeof(TemplateArgument) * NumArgs), 3459 TypeAlignment); 3460 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 3461 Name, NumArgs, Args, Canon); 3462 Types.push_back(T); 3463 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 3464 return QualType(T, 0); 3465} 3466 3467QualType ASTContext::getPackExpansionType(QualType Pattern, 3468 Optional<unsigned> NumExpansions) { 3469 llvm::FoldingSetNodeID ID; 3470 PackExpansionType::Profile(ID, Pattern, NumExpansions); 3471 3472 assert(Pattern->containsUnexpandedParameterPack() && 3473 "Pack expansions must expand one or more parameter packs"); 3474 void *InsertPos = nullptr; 3475 PackExpansionType *T 3476 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3477 if (T) 3478 return QualType(T, 0); 3479 3480 QualType Canon; 3481 if (!Pattern.isCanonical()) { 3482 Canon = getCanonicalType(Pattern); 3483 // The canonical type might not contain an unexpanded parameter pack, if it 3484 // contains an alias template specialization which ignores one of its 3485 // parameters. 3486 if (Canon->containsUnexpandedParameterPack()) { 3487 Canon = getPackExpansionType(Canon, NumExpansions); 3488 3489 // Find the insert position again, in case we inserted an element into 3490 // PackExpansionTypes and invalidated our insert position. 3491 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 3492 } 3493 } 3494 3495 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions); 3496 Types.push_back(T); 3497 PackExpansionTypes.InsertNode(T, InsertPos); 3498 return QualType(T, 0); 3499} 3500 3501/// CmpProtocolNames - Comparison predicate for sorting protocols 3502/// alphabetically. 3503static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 3504 const ObjCProtocolDecl *RHS) { 3505 return LHS->getDeclName() < RHS->getDeclName(); 3506} 3507 3508static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 3509 unsigned NumProtocols) { 3510 if (NumProtocols == 0) return true; 3511 3512 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 3513 return false; 3514 3515 for (unsigned i = 1; i != NumProtocols; ++i) 3516 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) || 3517 Protocols[i]->getCanonicalDecl() != Protocols[i]) 3518 return false; 3519 return true; 3520} 3521 3522static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 3523 unsigned &NumProtocols) { 3524 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 3525 3526 // Sort protocols, keyed by name. 3527 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 3528 3529 // Canonicalize. 3530 for (unsigned I = 0, N = NumProtocols; I != N; ++I) 3531 Protocols[I] = Protocols[I]->getCanonicalDecl(); 3532 3533 // Remove duplicates. 3534 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 3535 NumProtocols = ProtocolsEnd-Protocols; 3536} 3537 3538QualType ASTContext::getObjCObjectType(QualType BaseType, 3539 ObjCProtocolDecl * const *Protocols, 3540 unsigned NumProtocols) const { 3541 // If the base type is an interface and there aren't any protocols 3542 // to add, then the interface type will do just fine. 3543 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 3544 return BaseType; 3545 3546 // Look in the folding set for an existing type. 3547 llvm::FoldingSetNodeID ID; 3548 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 3549 void *InsertPos = nullptr; 3550 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 3551 return QualType(QT, 0); 3552 3553 // Build the canonical type, which has the canonical base type and 3554 // a sorted-and-uniqued list of protocols. 3555 QualType Canonical; 3556 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 3557 if (!ProtocolsSorted || !BaseType.isCanonical()) { 3558 if (!ProtocolsSorted) { 3559 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 3560 Protocols + NumProtocols); 3561 unsigned UniqueCount = NumProtocols; 3562 3563 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 3564 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3565 &Sorted[0], UniqueCount); 3566 } else { 3567 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3568 Protocols, NumProtocols); 3569 } 3570 3571 // Regenerate InsertPos. 3572 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 3573 } 3574 3575 unsigned Size = sizeof(ObjCObjectTypeImpl); 3576 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 3577 void *Mem = Allocate(Size, TypeAlignment); 3578 ObjCObjectTypeImpl *T = 3579 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 3580 3581 Types.push_back(T); 3582 ObjCObjectTypes.InsertNode(T, InsertPos); 3583 return QualType(T, 0); 3584} 3585 3586/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's 3587/// protocol list adopt all protocols in QT's qualified-id protocol 3588/// list. 3589bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT, 3590 ObjCInterfaceDecl *IC) { 3591 if (!QT->isObjCQualifiedIdType()) 3592 return false; 3593 3594 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) { 3595 // If both the right and left sides have qualifiers. 3596 for (auto *Proto : OPT->quals()) { 3597 if (!IC->ClassImplementsProtocol(Proto, false)) 3598 return false; 3599 } 3600 return true; 3601 } 3602 return false; 3603} 3604 3605/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in 3606/// QT's qualified-id protocol list adopt all protocols in IDecl's list 3607/// of protocols. 3608bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT, 3609 ObjCInterfaceDecl *IDecl) { 3610 if (!QT->isObjCQualifiedIdType()) 3611 return false; 3612 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>(); 3613 if (!OPT) 3614 return false; 3615 if (!IDecl->hasDefinition()) 3616 return false; 3617 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols; 3618 CollectInheritedProtocols(IDecl, InheritedProtocols); 3619 if (InheritedProtocols.empty()) 3620 return false; 3621 // Check that if every protocol in list of id<plist> conforms to a protcol 3622 // of IDecl's, then bridge casting is ok. 3623 bool Conforms = false; 3624 for (auto *Proto : OPT->quals()) { 3625 Conforms = false; 3626 for (auto *PI : InheritedProtocols) { 3627 if (ProtocolCompatibleWithProtocol(Proto, PI)) { 3628 Conforms = true; 3629 break; 3630 } 3631 } 3632 if (!Conforms) 3633 break; 3634 } 3635 if (Conforms) 3636 return true; 3637 3638 for (auto *PI : InheritedProtocols) { 3639 // If both the right and left sides have qualifiers. 3640 bool Adopts = false; 3641 for (auto *Proto : OPT->quals()) { 3642 // return 'true' if 'PI' is in the inheritance hierarchy of Proto 3643 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto))) 3644 break; 3645 } 3646 if (!Adopts) 3647 return false; 3648 } 3649 return true; 3650} 3651 3652/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 3653/// the given object type. 3654QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 3655 llvm::FoldingSetNodeID ID; 3656 ObjCObjectPointerType::Profile(ID, ObjectT); 3657 3658 void *InsertPos = nullptr; 3659 if (ObjCObjectPointerType *QT = 3660 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3661 return QualType(QT, 0); 3662 3663 // Find the canonical object type. 3664 QualType Canonical; 3665 if (!ObjectT.isCanonical()) { 3666 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 3667 3668 // Regenerate InsertPos. 3669 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3670 } 3671 3672 // No match. 3673 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 3674 ObjCObjectPointerType *QType = 3675 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 3676 3677 Types.push_back(QType); 3678 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 3679 return QualType(QType, 0); 3680} 3681 3682/// getObjCInterfaceType - Return the unique reference to the type for the 3683/// specified ObjC interface decl. The list of protocols is optional. 3684QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 3685 ObjCInterfaceDecl *PrevDecl) const { 3686 if (Decl->TypeForDecl) 3687 return QualType(Decl->TypeForDecl, 0); 3688 3689 if (PrevDecl) { 3690 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 3691 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3692 return QualType(PrevDecl->TypeForDecl, 0); 3693 } 3694 3695 // Prefer the definition, if there is one. 3696 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 3697 Decl = Def; 3698 3699 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 3700 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 3701 Decl->TypeForDecl = T; 3702 Types.push_back(T); 3703 return QualType(T, 0); 3704} 3705 3706/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 3707/// TypeOfExprType AST's (since expression's are never shared). For example, 3708/// multiple declarations that refer to "typeof(x)" all contain different 3709/// DeclRefExpr's. This doesn't effect the type checker, since it operates 3710/// on canonical type's (which are always unique). 3711QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 3712 TypeOfExprType *toe; 3713 if (tofExpr->isTypeDependent()) { 3714 llvm::FoldingSetNodeID ID; 3715 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 3716 3717 void *InsertPos = nullptr; 3718 DependentTypeOfExprType *Canon 3719 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 3720 if (Canon) { 3721 // We already have a "canonical" version of an identical, dependent 3722 // typeof(expr) type. Use that as our canonical type. 3723 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 3724 QualType((TypeOfExprType*)Canon, 0)); 3725 } else { 3726 // Build a new, canonical typeof(expr) type. 3727 Canon 3728 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 3729 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 3730 toe = Canon; 3731 } 3732 } else { 3733 QualType Canonical = getCanonicalType(tofExpr->getType()); 3734 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 3735 } 3736 Types.push_back(toe); 3737 return QualType(toe, 0); 3738} 3739 3740/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 3741/// TypeOfType nodes. The only motivation to unique these nodes would be 3742/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 3743/// an issue. This doesn't affect the type checker, since it operates 3744/// on canonical types (which are always unique). 3745QualType ASTContext::getTypeOfType(QualType tofType) const { 3746 QualType Canonical = getCanonicalType(tofType); 3747 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 3748 Types.push_back(tot); 3749 return QualType(tot, 0); 3750} 3751 3752 3753/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType 3754/// nodes. This would never be helpful, since each such type has its own 3755/// expression, and would not give a significant memory saving, since there 3756/// is an Expr tree under each such type. 3757QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 3758 DecltypeType *dt; 3759 3760 // C++11 [temp.type]p2: 3761 // If an expression e involves a template parameter, decltype(e) denotes a 3762 // unique dependent type. Two such decltype-specifiers refer to the same 3763 // type only if their expressions are equivalent (14.5.6.1). 3764 if (e->isInstantiationDependent()) { 3765 llvm::FoldingSetNodeID ID; 3766 DependentDecltypeType::Profile(ID, *this, e); 3767 3768 void *InsertPos = nullptr; 3769 DependentDecltypeType *Canon 3770 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 3771 if (!Canon) { 3772 // Build a new, canonical typeof(expr) type. 3773 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 3774 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 3775 } 3776 dt = new (*this, TypeAlignment) 3777 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0)); 3778 } else { 3779 dt = new (*this, TypeAlignment) 3780 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType)); 3781 } 3782 Types.push_back(dt); 3783 return QualType(dt, 0); 3784} 3785 3786/// getUnaryTransformationType - We don't unique these, since the memory 3787/// savings are minimal and these are rare. 3788QualType ASTContext::getUnaryTransformType(QualType BaseType, 3789 QualType UnderlyingType, 3790 UnaryTransformType::UTTKind Kind) 3791 const { 3792 UnaryTransformType *Ty = 3793 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 3794 Kind, 3795 UnderlyingType->isDependentType() ? 3796 QualType() : getCanonicalType(UnderlyingType)); 3797 Types.push_back(Ty); 3798 return QualType(Ty, 0); 3799} 3800 3801/// getAutoType - Return the uniqued reference to the 'auto' type which has been 3802/// deduced to the given type, or to the canonical undeduced 'auto' type, or the 3803/// canonical deduced-but-dependent 'auto' type. 3804QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto, 3805 bool IsDependent) const { 3806 if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent) 3807 return getAutoDeductType(); 3808 3809 // Look in the folding set for an existing type. 3810 void *InsertPos = nullptr; 3811 llvm::FoldingSetNodeID ID; 3812 AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent); 3813 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3814 return QualType(AT, 0); 3815 3816 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType, 3817 IsDecltypeAuto, 3818 IsDependent); 3819 Types.push_back(AT); 3820 if (InsertPos) 3821 AutoTypes.InsertNode(AT, InsertPos); 3822 return QualType(AT, 0); 3823} 3824 3825/// getAtomicType - Return the uniqued reference to the atomic type for 3826/// the given value type. 3827QualType ASTContext::getAtomicType(QualType T) const { 3828 // Unique pointers, to guarantee there is only one pointer of a particular 3829 // structure. 3830 llvm::FoldingSetNodeID ID; 3831 AtomicType::Profile(ID, T); 3832 3833 void *InsertPos = nullptr; 3834 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 3835 return QualType(AT, 0); 3836 3837 // If the atomic value type isn't canonical, this won't be a canonical type 3838 // either, so fill in the canonical type field. 3839 QualType Canonical; 3840 if (!T.isCanonical()) { 3841 Canonical = getAtomicType(getCanonicalType(T)); 3842 3843 // Get the new insert position for the node we care about. 3844 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3845 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP; 3846 } 3847 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3848 Types.push_back(New); 3849 AtomicTypes.InsertNode(New, InsertPos); 3850 return QualType(New, 0); 3851} 3852 3853/// getAutoDeductType - Get type pattern for deducing against 'auto'. 3854QualType ASTContext::getAutoDeductType() const { 3855 if (AutoDeductTy.isNull()) 3856 AutoDeductTy = QualType( 3857 new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false, 3858 /*dependent*/false), 3859 0); 3860 return AutoDeductTy; 3861} 3862 3863/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3864QualType ASTContext::getAutoRRefDeductType() const { 3865 if (AutoRRefDeductTy.isNull()) 3866 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3867 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3868 return AutoRRefDeductTy; 3869} 3870 3871/// getTagDeclType - Return the unique reference to the type for the 3872/// specified TagDecl (struct/union/class/enum) decl. 3873QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3874 assert (Decl); 3875 // FIXME: What is the design on getTagDeclType when it requires casting 3876 // away const? mutable? 3877 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3878} 3879 3880/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3881/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3882/// needs to agree with the definition in <stddef.h>. 3883CanQualType ASTContext::getSizeType() const { 3884 return getFromTargetType(Target->getSizeType()); 3885} 3886 3887/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3888CanQualType ASTContext::getIntMaxType() const { 3889 return getFromTargetType(Target->getIntMaxType()); 3890} 3891 3892/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3893CanQualType ASTContext::getUIntMaxType() const { 3894 return getFromTargetType(Target->getUIntMaxType()); 3895} 3896 3897/// getSignedWCharType - Return the type of "signed wchar_t". 3898/// Used when in C++, as a GCC extension. 3899QualType ASTContext::getSignedWCharType() const { 3900 // FIXME: derive from "Target" ? 3901 return WCharTy; 3902} 3903 3904/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3905/// Used when in C++, as a GCC extension. 3906QualType ASTContext::getUnsignedWCharType() const { 3907 // FIXME: derive from "Target" ? 3908 return UnsignedIntTy; 3909} 3910 3911QualType ASTContext::getIntPtrType() const { 3912 return getFromTargetType(Target->getIntPtrType()); 3913} 3914 3915QualType ASTContext::getUIntPtrType() const { 3916 return getCorrespondingUnsignedType(getIntPtrType()); 3917} 3918 3919/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3920/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3921QualType ASTContext::getPointerDiffType() const { 3922 return getFromTargetType(Target->getPtrDiffType(0)); 3923} 3924 3925/// \brief Return the unique type for "pid_t" defined in 3926/// <sys/types.h>. We need this to compute the correct type for vfork(). 3927QualType ASTContext::getProcessIDType() const { 3928 return getFromTargetType(Target->getProcessIDType()); 3929} 3930 3931//===----------------------------------------------------------------------===// 3932// Type Operators 3933//===----------------------------------------------------------------------===// 3934 3935CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3936 // Push qualifiers into arrays, and then discard any remaining 3937 // qualifiers. 3938 T = getCanonicalType(T); 3939 T = getVariableArrayDecayedType(T); 3940 const Type *Ty = T.getTypePtr(); 3941 QualType Result; 3942 if (isa<ArrayType>(Ty)) { 3943 Result = getArrayDecayedType(QualType(Ty,0)); 3944 } else if (isa<FunctionType>(Ty)) { 3945 Result = getPointerType(QualType(Ty, 0)); 3946 } else { 3947 Result = QualType(Ty, 0); 3948 } 3949 3950 return CanQualType::CreateUnsafe(Result); 3951} 3952 3953QualType ASTContext::getUnqualifiedArrayType(QualType type, 3954 Qualifiers &quals) { 3955 SplitQualType splitType = type.getSplitUnqualifiedType(); 3956 3957 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3958 // the unqualified desugared type and then drops it on the floor. 3959 // We then have to strip that sugar back off with 3960 // getUnqualifiedDesugaredType(), which is silly. 3961 const ArrayType *AT = 3962 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 3963 3964 // If we don't have an array, just use the results in splitType. 3965 if (!AT) { 3966 quals = splitType.Quals; 3967 return QualType(splitType.Ty, 0); 3968 } 3969 3970 // Otherwise, recurse on the array's element type. 3971 QualType elementType = AT->getElementType(); 3972 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3973 3974 // If that didn't change the element type, AT has no qualifiers, so we 3975 // can just use the results in splitType. 3976 if (elementType == unqualElementType) { 3977 assert(quals.empty()); // from the recursive call 3978 quals = splitType.Quals; 3979 return QualType(splitType.Ty, 0); 3980 } 3981 3982 // Otherwise, add in the qualifiers from the outermost type, then 3983 // build the type back up. 3984 quals.addConsistentQualifiers(splitType.Quals); 3985 3986 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3987 return getConstantArrayType(unqualElementType, CAT->getSize(), 3988 CAT->getSizeModifier(), 0); 3989 } 3990 3991 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3992 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3993 } 3994 3995 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3996 return getVariableArrayType(unqualElementType, 3997 VAT->getSizeExpr(), 3998 VAT->getSizeModifier(), 3999 VAT->getIndexTypeCVRQualifiers(), 4000 VAT->getBracketsRange()); 4001 } 4002 4003 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 4004 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 4005 DSAT->getSizeModifier(), 0, 4006 SourceRange()); 4007} 4008 4009/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 4010/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 4011/// they point to and return true. If T1 and T2 aren't pointer types 4012/// or pointer-to-member types, or if they are not similar at this 4013/// level, returns false and leaves T1 and T2 unchanged. Top-level 4014/// qualifiers on T1 and T2 are ignored. This function will typically 4015/// be called in a loop that successively "unwraps" pointer and 4016/// pointer-to-member types to compare them at each level. 4017bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 4018 const PointerType *T1PtrType = T1->getAs<PointerType>(), 4019 *T2PtrType = T2->getAs<PointerType>(); 4020 if (T1PtrType && T2PtrType) { 4021 T1 = T1PtrType->getPointeeType(); 4022 T2 = T2PtrType->getPointeeType(); 4023 return true; 4024 } 4025 4026 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 4027 *T2MPType = T2->getAs<MemberPointerType>(); 4028 if (T1MPType && T2MPType && 4029 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 4030 QualType(T2MPType->getClass(), 0))) { 4031 T1 = T1MPType->getPointeeType(); 4032 T2 = T2MPType->getPointeeType(); 4033 return true; 4034 } 4035 4036 if (getLangOpts().ObjC1) { 4037 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 4038 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 4039 if (T1OPType && T2OPType) { 4040 T1 = T1OPType->getPointeeType(); 4041 T2 = T2OPType->getPointeeType(); 4042 return true; 4043 } 4044 } 4045 4046 // FIXME: Block pointers, too? 4047 4048 return false; 4049} 4050 4051DeclarationNameInfo 4052ASTContext::getNameForTemplate(TemplateName Name, 4053 SourceLocation NameLoc) const { 4054 switch (Name.getKind()) { 4055 case TemplateName::QualifiedTemplate: 4056 case TemplateName::Template: 4057 // DNInfo work in progress: CHECKME: what about DNLoc? 4058 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 4059 NameLoc); 4060 4061 case TemplateName::OverloadedTemplate: { 4062 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 4063 // DNInfo work in progress: CHECKME: what about DNLoc? 4064 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 4065 } 4066 4067 case TemplateName::DependentTemplate: { 4068 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4069 DeclarationName DName; 4070 if (DTN->isIdentifier()) { 4071 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 4072 return DeclarationNameInfo(DName, NameLoc); 4073 } else { 4074 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 4075 // DNInfo work in progress: FIXME: source locations? 4076 DeclarationNameLoc DNLoc; 4077 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 4078 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 4079 return DeclarationNameInfo(DName, NameLoc, DNLoc); 4080 } 4081 } 4082 4083 case TemplateName::SubstTemplateTemplateParm: { 4084 SubstTemplateTemplateParmStorage *subst 4085 = Name.getAsSubstTemplateTemplateParm(); 4086 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 4087 NameLoc); 4088 } 4089 4090 case TemplateName::SubstTemplateTemplateParmPack: { 4091 SubstTemplateTemplateParmPackStorage *subst 4092 = Name.getAsSubstTemplateTemplateParmPack(); 4093 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 4094 NameLoc); 4095 } 4096 } 4097 4098 llvm_unreachable("bad template name kind!"); 4099} 4100 4101TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 4102 switch (Name.getKind()) { 4103 case TemplateName::QualifiedTemplate: 4104 case TemplateName::Template: { 4105 TemplateDecl *Template = Name.getAsTemplateDecl(); 4106 if (TemplateTemplateParmDecl *TTP 4107 = dyn_cast<TemplateTemplateParmDecl>(Template)) 4108 Template = getCanonicalTemplateTemplateParmDecl(TTP); 4109 4110 // The canonical template name is the canonical template declaration. 4111 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 4112 } 4113 4114 case TemplateName::OverloadedTemplate: 4115 llvm_unreachable("cannot canonicalize overloaded template"); 4116 4117 case TemplateName::DependentTemplate: { 4118 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 4119 assert(DTN && "Non-dependent template names must refer to template decls."); 4120 return DTN->CanonicalTemplateName; 4121 } 4122 4123 case TemplateName::SubstTemplateTemplateParm: { 4124 SubstTemplateTemplateParmStorage *subst 4125 = Name.getAsSubstTemplateTemplateParm(); 4126 return getCanonicalTemplateName(subst->getReplacement()); 4127 } 4128 4129 case TemplateName::SubstTemplateTemplateParmPack: { 4130 SubstTemplateTemplateParmPackStorage *subst 4131 = Name.getAsSubstTemplateTemplateParmPack(); 4132 TemplateTemplateParmDecl *canonParameter 4133 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 4134 TemplateArgument canonArgPack 4135 = getCanonicalTemplateArgument(subst->getArgumentPack()); 4136 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 4137 } 4138 } 4139 4140 llvm_unreachable("bad template name!"); 4141} 4142 4143bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 4144 X = getCanonicalTemplateName(X); 4145 Y = getCanonicalTemplateName(Y); 4146 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 4147} 4148 4149TemplateArgument 4150ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 4151 switch (Arg.getKind()) { 4152 case TemplateArgument::Null: 4153 return Arg; 4154 4155 case TemplateArgument::Expression: 4156 return Arg; 4157 4158 case TemplateArgument::Declaration: { 4159 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl()); 4160 return TemplateArgument(D, Arg.getParamTypeForDecl()); 4161 } 4162 4163 case TemplateArgument::NullPtr: 4164 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()), 4165 /*isNullPtr*/true); 4166 4167 case TemplateArgument::Template: 4168 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 4169 4170 case TemplateArgument::TemplateExpansion: 4171 return TemplateArgument(getCanonicalTemplateName( 4172 Arg.getAsTemplateOrTemplatePattern()), 4173 Arg.getNumTemplateExpansions()); 4174 4175 case TemplateArgument::Integral: 4176 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 4177 4178 case TemplateArgument::Type: 4179 return TemplateArgument(getCanonicalType(Arg.getAsType())); 4180 4181 case TemplateArgument::Pack: { 4182 if (Arg.pack_size() == 0) 4183 return Arg; 4184 4185 TemplateArgument *CanonArgs 4186 = new (*this) TemplateArgument[Arg.pack_size()]; 4187 unsigned Idx = 0; 4188 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 4189 AEnd = Arg.pack_end(); 4190 A != AEnd; (void)++A, ++Idx) 4191 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 4192 4193 return TemplateArgument(CanonArgs, Arg.pack_size()); 4194 } 4195 } 4196 4197 // Silence GCC warning 4198 llvm_unreachable("Unhandled template argument kind"); 4199} 4200 4201NestedNameSpecifier * 4202ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 4203 if (!NNS) 4204 return nullptr; 4205 4206 switch (NNS->getKind()) { 4207 case NestedNameSpecifier::Identifier: 4208 // Canonicalize the prefix but keep the identifier the same. 4209 return NestedNameSpecifier::Create(*this, 4210 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 4211 NNS->getAsIdentifier()); 4212 4213 case NestedNameSpecifier::Namespace: 4214 // A namespace is canonical; build a nested-name-specifier with 4215 // this namespace and no prefix. 4216 return NestedNameSpecifier::Create(*this, nullptr, 4217 NNS->getAsNamespace()->getOriginalNamespace()); 4218 4219 case NestedNameSpecifier::NamespaceAlias: 4220 // A namespace is canonical; build a nested-name-specifier with 4221 // this namespace and no prefix. 4222 return NestedNameSpecifier::Create(*this, nullptr, 4223 NNS->getAsNamespaceAlias()->getNamespace() 4224 ->getOriginalNamespace()); 4225 4226 case NestedNameSpecifier::TypeSpec: 4227 case NestedNameSpecifier::TypeSpecWithTemplate: { 4228 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 4229 4230 // If we have some kind of dependent-named type (e.g., "typename T::type"), 4231 // break it apart into its prefix and identifier, then reconsititute those 4232 // as the canonical nested-name-specifier. This is required to canonicalize 4233 // a dependent nested-name-specifier involving typedefs of dependent-name 4234 // types, e.g., 4235 // typedef typename T::type T1; 4236 // typedef typename T1::type T2; 4237 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 4238 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 4239 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 4240 4241 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 4242 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 4243 // first place? 4244 return NestedNameSpecifier::Create(*this, nullptr, false, 4245 const_cast<Type *>(T.getTypePtr())); 4246 } 4247 4248 case NestedNameSpecifier::Global: 4249 case NestedNameSpecifier::Super: 4250 // The global specifier and __super specifer are canonical and unique. 4251 return NNS; 4252 } 4253 4254 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 4255} 4256 4257 4258const ArrayType *ASTContext::getAsArrayType(QualType T) const { 4259 // Handle the non-qualified case efficiently. 4260 if (!T.hasLocalQualifiers()) { 4261 // Handle the common positive case fast. 4262 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 4263 return AT; 4264 } 4265 4266 // Handle the common negative case fast. 4267 if (!isa<ArrayType>(T.getCanonicalType())) 4268 return nullptr; 4269 4270 // Apply any qualifiers from the array type to the element type. This 4271 // implements C99 6.7.3p8: "If the specification of an array type includes 4272 // any type qualifiers, the element type is so qualified, not the array type." 4273 4274 // If we get here, we either have type qualifiers on the type, or we have 4275 // sugar such as a typedef in the way. If we have type qualifiers on the type 4276 // we must propagate them down into the element type. 4277 4278 SplitQualType split = T.getSplitDesugaredType(); 4279 Qualifiers qs = split.Quals; 4280 4281 // If we have a simple case, just return now. 4282 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 4283 if (!ATy || qs.empty()) 4284 return ATy; 4285 4286 // Otherwise, we have an array and we have qualifiers on it. Push the 4287 // qualifiers into the array element type and return a new array type. 4288 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 4289 4290 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 4291 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 4292 CAT->getSizeModifier(), 4293 CAT->getIndexTypeCVRQualifiers())); 4294 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 4295 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 4296 IAT->getSizeModifier(), 4297 IAT->getIndexTypeCVRQualifiers())); 4298 4299 if (const DependentSizedArrayType *DSAT 4300 = dyn_cast<DependentSizedArrayType>(ATy)) 4301 return cast<ArrayType>( 4302 getDependentSizedArrayType(NewEltTy, 4303 DSAT->getSizeExpr(), 4304 DSAT->getSizeModifier(), 4305 DSAT->getIndexTypeCVRQualifiers(), 4306 DSAT->getBracketsRange())); 4307 4308 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 4309 return cast<ArrayType>(getVariableArrayType(NewEltTy, 4310 VAT->getSizeExpr(), 4311 VAT->getSizeModifier(), 4312 VAT->getIndexTypeCVRQualifiers(), 4313 VAT->getBracketsRange())); 4314} 4315 4316QualType ASTContext::getAdjustedParameterType(QualType T) const { 4317 if (T->isArrayType() || T->isFunctionType()) 4318 return getDecayedType(T); 4319 return T; 4320} 4321 4322QualType ASTContext::getSignatureParameterType(QualType T) const { 4323 T = getVariableArrayDecayedType(T); 4324 T = getAdjustedParameterType(T); 4325 return T.getUnqualifiedType(); 4326} 4327 4328/// getArrayDecayedType - Return the properly qualified result of decaying the 4329/// specified array type to a pointer. This operation is non-trivial when 4330/// handling typedefs etc. The canonical type of "T" must be an array type, 4331/// this returns a pointer to a properly qualified element of the array. 4332/// 4333/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 4334QualType ASTContext::getArrayDecayedType(QualType Ty) const { 4335 // Get the element type with 'getAsArrayType' so that we don't lose any 4336 // typedefs in the element type of the array. This also handles propagation 4337 // of type qualifiers from the array type into the element type if present 4338 // (C99 6.7.3p8). 4339 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 4340 assert(PrettyArrayType && "Not an array type!"); 4341 4342 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 4343 4344 // int x[restrict 4] -> int *restrict 4345 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 4346} 4347 4348QualType ASTContext::getBaseElementType(const ArrayType *array) const { 4349 return getBaseElementType(array->getElementType()); 4350} 4351 4352QualType ASTContext::getBaseElementType(QualType type) const { 4353 Qualifiers qs; 4354 while (true) { 4355 SplitQualType split = type.getSplitDesugaredType(); 4356 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 4357 if (!array) break; 4358 4359 type = array->getElementType(); 4360 qs.addConsistentQualifiers(split.Quals); 4361 } 4362 4363 return getQualifiedType(type, qs); 4364} 4365 4366/// getConstantArrayElementCount - Returns number of constant array elements. 4367uint64_t 4368ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 4369 uint64_t ElementCount = 1; 4370 do { 4371 ElementCount *= CA->getSize().getZExtValue(); 4372 CA = dyn_cast_or_null<ConstantArrayType>( 4373 CA->getElementType()->getAsArrayTypeUnsafe()); 4374 } while (CA); 4375 return ElementCount; 4376} 4377 4378/// getFloatingRank - Return a relative rank for floating point types. 4379/// This routine will assert if passed a built-in type that isn't a float. 4380static FloatingRank getFloatingRank(QualType T) { 4381 if (const ComplexType *CT = T->getAs<ComplexType>()) 4382 return getFloatingRank(CT->getElementType()); 4383 4384 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 4385 switch (T->getAs<BuiltinType>()->getKind()) { 4386 default: llvm_unreachable("getFloatingRank(): not a floating type"); 4387 case BuiltinType::Half: return HalfRank; 4388 case BuiltinType::Float: return FloatRank; 4389 case BuiltinType::Double: return DoubleRank; 4390 case BuiltinType::LongDouble: return LongDoubleRank; 4391 } 4392} 4393 4394/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 4395/// point or a complex type (based on typeDomain/typeSize). 4396/// 'typeDomain' is a real floating point or complex type. 4397/// 'typeSize' is a real floating point or complex type. 4398QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 4399 QualType Domain) const { 4400 FloatingRank EltRank = getFloatingRank(Size); 4401 if (Domain->isComplexType()) { 4402 switch (EltRank) { 4403 case HalfRank: llvm_unreachable("Complex half is not supported"); 4404 case FloatRank: return FloatComplexTy; 4405 case DoubleRank: return DoubleComplexTy; 4406 case LongDoubleRank: return LongDoubleComplexTy; 4407 } 4408 } 4409 4410 assert(Domain->isRealFloatingType() && "Unknown domain!"); 4411 switch (EltRank) { 4412 case HalfRank: return HalfTy; 4413 case FloatRank: return FloatTy; 4414 case DoubleRank: return DoubleTy; 4415 case LongDoubleRank: return LongDoubleTy; 4416 } 4417 llvm_unreachable("getFloatingRank(): illegal value for rank"); 4418} 4419 4420/// getFloatingTypeOrder - Compare the rank of the two specified floating 4421/// point types, ignoring the domain of the type (i.e. 'double' == 4422/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 4423/// LHS < RHS, return -1. 4424int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 4425 FloatingRank LHSR = getFloatingRank(LHS); 4426 FloatingRank RHSR = getFloatingRank(RHS); 4427 4428 if (LHSR == RHSR) 4429 return 0; 4430 if (LHSR > RHSR) 4431 return 1; 4432 return -1; 4433} 4434 4435/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 4436/// routine will assert if passed a built-in type that isn't an integer or enum, 4437/// or if it is not canonicalized. 4438unsigned ASTContext::getIntegerRank(const Type *T) const { 4439 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 4440 4441 switch (cast<BuiltinType>(T)->getKind()) { 4442 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 4443 case BuiltinType::Bool: 4444 return 1 + (getIntWidth(BoolTy) << 3); 4445 case BuiltinType::Char_S: 4446 case BuiltinType::Char_U: 4447 case BuiltinType::SChar: 4448 case BuiltinType::UChar: 4449 return 2 + (getIntWidth(CharTy) << 3); 4450 case BuiltinType::Short: 4451 case BuiltinType::UShort: 4452 return 3 + (getIntWidth(ShortTy) << 3); 4453 case BuiltinType::Int: 4454 case BuiltinType::UInt: 4455 return 4 + (getIntWidth(IntTy) << 3); 4456 case BuiltinType::Long: 4457 case BuiltinType::ULong: 4458 return 5 + (getIntWidth(LongTy) << 3); 4459 case BuiltinType::LongLong: 4460 case BuiltinType::ULongLong: 4461 return 6 + (getIntWidth(LongLongTy) << 3); 4462 case BuiltinType::Int128: 4463 case BuiltinType::UInt128: 4464 return 7 + (getIntWidth(Int128Ty) << 3); 4465 } 4466} 4467 4468/// \brief Whether this is a promotable bitfield reference according 4469/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 4470/// 4471/// \returns the type this bit-field will promote to, or NULL if no 4472/// promotion occurs. 4473QualType ASTContext::isPromotableBitField(Expr *E) const { 4474 if (E->isTypeDependent() || E->isValueDependent()) 4475 return QualType(); 4476 4477 // FIXME: We should not do this unless E->refersToBitField() is true. This 4478 // matters in C where getSourceBitField() will find bit-fields for various 4479 // cases where the source expression is not a bit-field designator. 4480 4481 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields? 4482 if (!Field) 4483 return QualType(); 4484 4485 QualType FT = Field->getType(); 4486 4487 uint64_t BitWidth = Field->getBitWidthValue(*this); 4488 uint64_t IntSize = getTypeSize(IntTy); 4489 // C++ [conv.prom]p5: 4490 // A prvalue for an integral bit-field can be converted to a prvalue of type 4491 // int if int can represent all the values of the bit-field; otherwise, it 4492 // can be converted to unsigned int if unsigned int can represent all the 4493 // values of the bit-field. If the bit-field is larger yet, no integral 4494 // promotion applies to it. 4495 // C11 6.3.1.1/2: 4496 // [For a bit-field of type _Bool, int, signed int, or unsigned int:] 4497 // If an int can represent all values of the original type (as restricted by 4498 // the width, for a bit-field), the value is converted to an int; otherwise, 4499 // it is converted to an unsigned int. 4500 // 4501 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int. 4502 // We perform that promotion here to match GCC and C++. 4503 if (BitWidth < IntSize) 4504 return IntTy; 4505 4506 if (BitWidth == IntSize) 4507 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 4508 4509 // Types bigger than int are not subject to promotions, and therefore act 4510 // like the base type. GCC has some weird bugs in this area that we 4511 // deliberately do not follow (GCC follows a pre-standard resolution to 4512 // C's DR315 which treats bit-width as being part of the type, and this leaks 4513 // into their semantics in some cases). 4514 return QualType(); 4515} 4516 4517/// getPromotedIntegerType - Returns the type that Promotable will 4518/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 4519/// integer type. 4520QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 4521 assert(!Promotable.isNull()); 4522 assert(Promotable->isPromotableIntegerType()); 4523 if (const EnumType *ET = Promotable->getAs<EnumType>()) 4524 return ET->getDecl()->getPromotionType(); 4525 4526 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 4527 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 4528 // (3.9.1) can be converted to a prvalue of the first of the following 4529 // types that can represent all the values of its underlying type: 4530 // int, unsigned int, long int, unsigned long int, long long int, or 4531 // unsigned long long int [...] 4532 // FIXME: Is there some better way to compute this? 4533 if (BT->getKind() == BuiltinType::WChar_S || 4534 BT->getKind() == BuiltinType::WChar_U || 4535 BT->getKind() == BuiltinType::Char16 || 4536 BT->getKind() == BuiltinType::Char32) { 4537 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 4538 uint64_t FromSize = getTypeSize(BT); 4539 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 4540 LongLongTy, UnsignedLongLongTy }; 4541 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 4542 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 4543 if (FromSize < ToSize || 4544 (FromSize == ToSize && 4545 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 4546 return PromoteTypes[Idx]; 4547 } 4548 llvm_unreachable("char type should fit into long long"); 4549 } 4550 } 4551 4552 // At this point, we should have a signed or unsigned integer type. 4553 if (Promotable->isSignedIntegerType()) 4554 return IntTy; 4555 uint64_t PromotableSize = getIntWidth(Promotable); 4556 uint64_t IntSize = getIntWidth(IntTy); 4557 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 4558 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 4559} 4560 4561/// \brief Recurses in pointer/array types until it finds an objc retainable 4562/// type and returns its ownership. 4563Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 4564 while (!T.isNull()) { 4565 if (T.getObjCLifetime() != Qualifiers::OCL_None) 4566 return T.getObjCLifetime(); 4567 if (T->isArrayType()) 4568 T = getBaseElementType(T); 4569 else if (const PointerType *PT = T->getAs<PointerType>()) 4570 T = PT->getPointeeType(); 4571 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4572 T = RT->getPointeeType(); 4573 else 4574 break; 4575 } 4576 4577 return Qualifiers::OCL_None; 4578} 4579 4580static const Type *getIntegerTypeForEnum(const EnumType *ET) { 4581 // Incomplete enum types are not treated as integer types. 4582 // FIXME: In C++, enum types are never integer types. 4583 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped()) 4584 return ET->getDecl()->getIntegerType().getTypePtr(); 4585 return nullptr; 4586} 4587 4588/// getIntegerTypeOrder - Returns the highest ranked integer type: 4589/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 4590/// LHS < RHS, return -1. 4591int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 4592 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 4593 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 4594 4595 // Unwrap enums to their underlying type. 4596 if (const EnumType *ET = dyn_cast<EnumType>(LHSC)) 4597 LHSC = getIntegerTypeForEnum(ET); 4598 if (const EnumType *ET = dyn_cast<EnumType>(RHSC)) 4599 RHSC = getIntegerTypeForEnum(ET); 4600 4601 if (LHSC == RHSC) return 0; 4602 4603 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 4604 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 4605 4606 unsigned LHSRank = getIntegerRank(LHSC); 4607 unsigned RHSRank = getIntegerRank(RHSC); 4608 4609 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 4610 if (LHSRank == RHSRank) return 0; 4611 return LHSRank > RHSRank ? 1 : -1; 4612 } 4613 4614 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 4615 if (LHSUnsigned) { 4616 // If the unsigned [LHS] type is larger, return it. 4617 if (LHSRank >= RHSRank) 4618 return 1; 4619 4620 // If the signed type can represent all values of the unsigned type, it 4621 // wins. Because we are dealing with 2's complement and types that are 4622 // powers of two larger than each other, this is always safe. 4623 return -1; 4624 } 4625 4626 // If the unsigned [RHS] type is larger, return it. 4627 if (RHSRank >= LHSRank) 4628 return -1; 4629 4630 // If the signed type can represent all values of the unsigned type, it 4631 // wins. Because we are dealing with 2's complement and types that are 4632 // powers of two larger than each other, this is always safe. 4633 return 1; 4634} 4635 4636// getCFConstantStringType - Return the type used for constant CFStrings. 4637QualType ASTContext::getCFConstantStringType() const { 4638 if (!CFConstantStringTypeDecl) { 4639 CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString"); 4640 CFConstantStringTypeDecl->startDefinition(); 4641 4642 QualType FieldTypes[4]; 4643 4644 // const int *isa; 4645 FieldTypes[0] = getPointerType(IntTy.withConst()); 4646 // int flags; 4647 FieldTypes[1] = IntTy; 4648 // const char *str; 4649 FieldTypes[2] = getPointerType(CharTy.withConst()); 4650 // long length; 4651 FieldTypes[3] = LongTy; 4652 4653 // Create fields 4654 for (unsigned i = 0; i < 4; ++i) { 4655 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 4656 SourceLocation(), 4657 SourceLocation(), nullptr, 4658 FieldTypes[i], /*TInfo=*/nullptr, 4659 /*BitWidth=*/nullptr, 4660 /*Mutable=*/false, 4661 ICIS_NoInit); 4662 Field->setAccess(AS_public); 4663 CFConstantStringTypeDecl->addDecl(Field); 4664 } 4665 4666 CFConstantStringTypeDecl->completeDefinition(); 4667 } 4668 4669 return getTagDeclType(CFConstantStringTypeDecl); 4670} 4671 4672QualType ASTContext::getObjCSuperType() const { 4673 if (ObjCSuperType.isNull()) { 4674 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super"); 4675 TUDecl->addDecl(ObjCSuperTypeDecl); 4676 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl); 4677 } 4678 return ObjCSuperType; 4679} 4680 4681void ASTContext::setCFConstantStringType(QualType T) { 4682 const RecordType *Rec = T->getAs<RecordType>(); 4683 assert(Rec && "Invalid CFConstantStringType"); 4684 CFConstantStringTypeDecl = Rec->getDecl(); 4685} 4686 4687QualType ASTContext::getBlockDescriptorType() const { 4688 if (BlockDescriptorType) 4689 return getTagDeclType(BlockDescriptorType); 4690 4691 RecordDecl *RD; 4692 // FIXME: Needs the FlagAppleBlock bit. 4693 RD = buildImplicitRecord("__block_descriptor"); 4694 RD->startDefinition(); 4695 4696 QualType FieldTypes[] = { 4697 UnsignedLongTy, 4698 UnsignedLongTy, 4699 }; 4700 4701 static const char *const FieldNames[] = { 4702 "reserved", 4703 "Size" 4704 }; 4705 4706 for (size_t i = 0; i < 2; ++i) { 4707 FieldDecl *Field = FieldDecl::Create( 4708 *this, RD, SourceLocation(), SourceLocation(), 4709 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 4710 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit); 4711 Field->setAccess(AS_public); 4712 RD->addDecl(Field); 4713 } 4714 4715 RD->completeDefinition(); 4716 4717 BlockDescriptorType = RD; 4718 4719 return getTagDeclType(BlockDescriptorType); 4720} 4721 4722QualType ASTContext::getBlockDescriptorExtendedType() const { 4723 if (BlockDescriptorExtendedType) 4724 return getTagDeclType(BlockDescriptorExtendedType); 4725 4726 RecordDecl *RD; 4727 // FIXME: Needs the FlagAppleBlock bit. 4728 RD = buildImplicitRecord("__block_descriptor_withcopydispose"); 4729 RD->startDefinition(); 4730 4731 QualType FieldTypes[] = { 4732 UnsignedLongTy, 4733 UnsignedLongTy, 4734 getPointerType(VoidPtrTy), 4735 getPointerType(VoidPtrTy) 4736 }; 4737 4738 static const char *const FieldNames[] = { 4739 "reserved", 4740 "Size", 4741 "CopyFuncPtr", 4742 "DestroyFuncPtr" 4743 }; 4744 4745 for (size_t i = 0; i < 4; ++i) { 4746 FieldDecl *Field = FieldDecl::Create( 4747 *this, RD, SourceLocation(), SourceLocation(), 4748 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr, 4749 /*BitWidth=*/nullptr, 4750 /*Mutable=*/false, ICIS_NoInit); 4751 Field->setAccess(AS_public); 4752 RD->addDecl(Field); 4753 } 4754 4755 RD->completeDefinition(); 4756 4757 BlockDescriptorExtendedType = RD; 4758 return getTagDeclType(BlockDescriptorExtendedType); 4759} 4760 4761/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty" 4762/// requires copy/dispose. Note that this must match the logic 4763/// in buildByrefHelpers. 4764bool ASTContext::BlockRequiresCopying(QualType Ty, 4765 const VarDecl *D) { 4766 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) { 4767 const Expr *copyExpr = getBlockVarCopyInits(D); 4768 if (!copyExpr && record->hasTrivialDestructor()) return false; 4769 4770 return true; 4771 } 4772 4773 if (!Ty->isObjCRetainableType()) return false; 4774 4775 Qualifiers qs = Ty.getQualifiers(); 4776 4777 // If we have lifetime, that dominates. 4778 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) { 4779 assert(getLangOpts().ObjCAutoRefCount); 4780 4781 switch (lifetime) { 4782 case Qualifiers::OCL_None: llvm_unreachable("impossible"); 4783 4784 // These are just bits as far as the runtime is concerned. 4785 case Qualifiers::OCL_ExplicitNone: 4786 case Qualifiers::OCL_Autoreleasing: 4787 return false; 4788 4789 // Tell the runtime that this is ARC __weak, called by the 4790 // byref routines. 4791 case Qualifiers::OCL_Weak: 4792 // ARC __strong __block variables need to be retained. 4793 case Qualifiers::OCL_Strong: 4794 return true; 4795 } 4796 llvm_unreachable("fell out of lifetime switch!"); 4797 } 4798 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) || 4799 Ty->isObjCObjectPointerType()); 4800} 4801 4802bool ASTContext::getByrefLifetime(QualType Ty, 4803 Qualifiers::ObjCLifetime &LifeTime, 4804 bool &HasByrefExtendedLayout) const { 4805 4806 if (!getLangOpts().ObjC1 || 4807 getLangOpts().getGC() != LangOptions::NonGC) 4808 return false; 4809 4810 HasByrefExtendedLayout = false; 4811 if (Ty->isRecordType()) { 4812 HasByrefExtendedLayout = true; 4813 LifeTime = Qualifiers::OCL_None; 4814 } 4815 else if (getLangOpts().ObjCAutoRefCount) 4816 LifeTime = Ty.getObjCLifetime(); 4817 // MRR. 4818 else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 4819 LifeTime = Qualifiers::OCL_ExplicitNone; 4820 else 4821 LifeTime = Qualifiers::OCL_None; 4822 return true; 4823} 4824 4825TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 4826 if (!ObjCInstanceTypeDecl) 4827 ObjCInstanceTypeDecl = 4828 buildImplicitTypedef(getObjCIdType(), "instancetype"); 4829 return ObjCInstanceTypeDecl; 4830} 4831 4832// This returns true if a type has been typedefed to BOOL: 4833// typedef <type> BOOL; 4834static bool isTypeTypedefedAsBOOL(QualType T) { 4835 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 4836 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 4837 return II->isStr("BOOL"); 4838 4839 return false; 4840} 4841 4842/// getObjCEncodingTypeSize returns size of type for objective-c encoding 4843/// purpose. 4844CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 4845 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4846 return CharUnits::Zero(); 4847 4848 CharUnits sz = getTypeSizeInChars(type); 4849 4850 // Make all integer and enum types at least as large as an int 4851 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4852 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4853 // Treat arrays as pointers, since that's how they're passed in. 4854 else if (type->isArrayType()) 4855 sz = getTypeSizeInChars(VoidPtrTy); 4856 return sz; 4857} 4858 4859bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const { 4860 return getLangOpts().MSVCCompat && VD->isStaticDataMember() && 4861 VD->getType()->isIntegralOrEnumerationType() && 4862 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit(); 4863} 4864 4865static inline 4866std::string charUnitsToString(const CharUnits &CU) { 4867 return llvm::itostr(CU.getQuantity()); 4868} 4869 4870/// getObjCEncodingForBlock - Return the encoded type for this block 4871/// declaration. 4872std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4873 std::string S; 4874 4875 const BlockDecl *Decl = Expr->getBlockDecl(); 4876 QualType BlockTy = 4877 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4878 // Encode result type. 4879 if (getLangOpts().EncodeExtendedBlockSig) 4880 getObjCEncodingForMethodParameter( 4881 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S, 4882 true /*Extended*/); 4883 else 4884 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S); 4885 // Compute size of all parameters. 4886 // Start with computing size of a pointer in number of bytes. 4887 // FIXME: There might(should) be a better way of doing this computation! 4888 SourceLocation Loc; 4889 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4890 CharUnits ParmOffset = PtrSize; 4891 for (auto PI : Decl->params()) { 4892 QualType PType = PI->getType(); 4893 CharUnits sz = getObjCEncodingTypeSize(PType); 4894 if (sz.isZero()) 4895 continue; 4896 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4897 ParmOffset += sz; 4898 } 4899 // Size of the argument frame 4900 S += charUnitsToString(ParmOffset); 4901 // Block pointer and offset. 4902 S += "@?0"; 4903 4904 // Argument types. 4905 ParmOffset = PtrSize; 4906 for (auto PVDecl : Decl->params()) { 4907 QualType PType = PVDecl->getOriginalType(); 4908 if (const ArrayType *AT = 4909 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4910 // Use array's original type only if it has known number of 4911 // elements. 4912 if (!isa<ConstantArrayType>(AT)) 4913 PType = PVDecl->getType(); 4914 } else if (PType->isFunctionType()) 4915 PType = PVDecl->getType(); 4916 if (getLangOpts().EncodeExtendedBlockSig) 4917 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType, 4918 S, true /*Extended*/); 4919 else 4920 getObjCEncodingForType(PType, S); 4921 S += charUnitsToString(ParmOffset); 4922 ParmOffset += getObjCEncodingTypeSize(PType); 4923 } 4924 4925 return S; 4926} 4927 4928bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4929 std::string& S) { 4930 // Encode result type. 4931 getObjCEncodingForType(Decl->getReturnType(), S); 4932 CharUnits ParmOffset; 4933 // Compute size of all parameters. 4934 for (auto PI : Decl->params()) { 4935 QualType PType = PI->getType(); 4936 CharUnits sz = getObjCEncodingTypeSize(PType); 4937 if (sz.isZero()) 4938 continue; 4939 4940 assert (sz.isPositive() && 4941 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4942 ParmOffset += sz; 4943 } 4944 S += charUnitsToString(ParmOffset); 4945 ParmOffset = CharUnits::Zero(); 4946 4947 // Argument types. 4948 for (auto PVDecl : Decl->params()) { 4949 QualType PType = PVDecl->getOriginalType(); 4950 if (const ArrayType *AT = 4951 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4952 // Use array's original type only if it has known number of 4953 // elements. 4954 if (!isa<ConstantArrayType>(AT)) 4955 PType = PVDecl->getType(); 4956 } else if (PType->isFunctionType()) 4957 PType = PVDecl->getType(); 4958 getObjCEncodingForType(PType, S); 4959 S += charUnitsToString(ParmOffset); 4960 ParmOffset += getObjCEncodingTypeSize(PType); 4961 } 4962 4963 return false; 4964} 4965 4966/// getObjCEncodingForMethodParameter - Return the encoded type for a single 4967/// method parameter or return type. If Extended, include class names and 4968/// block object types. 4969void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4970 QualType T, std::string& S, 4971 bool Extended) const { 4972 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4973 getObjCEncodingForTypeQualifier(QT, S); 4974 // Encode parameter type. 4975 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 4976 true /*OutermostType*/, 4977 false /*EncodingProperty*/, 4978 false /*StructField*/, 4979 Extended /*EncodeBlockParameters*/, 4980 Extended /*EncodeClassNames*/); 4981} 4982 4983/// getObjCEncodingForMethodDecl - Return the encoded type for this method 4984/// declaration. 4985bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4986 std::string& S, 4987 bool Extended) const { 4988 // FIXME: This is not very efficient. 4989 // Encode return type. 4990 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4991 Decl->getReturnType(), S, Extended); 4992 // Compute size of all parameters. 4993 // Start with computing size of a pointer in number of bytes. 4994 // FIXME: There might(should) be a better way of doing this computation! 4995 SourceLocation Loc; 4996 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4997 // The first two arguments (self and _cmd) are pointers; account for 4998 // their size. 4999 CharUnits ParmOffset = 2 * PtrSize; 5000 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 5001 E = Decl->sel_param_end(); PI != E; ++PI) { 5002 QualType PType = (*PI)->getType(); 5003 CharUnits sz = getObjCEncodingTypeSize(PType); 5004 if (sz.isZero()) 5005 continue; 5006 5007 assert (sz.isPositive() && 5008 "getObjCEncodingForMethodDecl - Incomplete param type"); 5009 ParmOffset += sz; 5010 } 5011 S += charUnitsToString(ParmOffset); 5012 S += "@0:"; 5013 S += charUnitsToString(PtrSize); 5014 5015 // Argument types. 5016 ParmOffset = 2 * PtrSize; 5017 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 5018 E = Decl->sel_param_end(); PI != E; ++PI) { 5019 const ParmVarDecl *PVDecl = *PI; 5020 QualType PType = PVDecl->getOriginalType(); 5021 if (const ArrayType *AT = 5022 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 5023 // Use array's original type only if it has known number of 5024 // elements. 5025 if (!isa<ConstantArrayType>(AT)) 5026 PType = PVDecl->getType(); 5027 } else if (PType->isFunctionType()) 5028 PType = PVDecl->getType(); 5029 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 5030 PType, S, Extended); 5031 S += charUnitsToString(ParmOffset); 5032 ParmOffset += getObjCEncodingTypeSize(PType); 5033 } 5034 5035 return false; 5036} 5037 5038ObjCPropertyImplDecl * 5039ASTContext::getObjCPropertyImplDeclForPropertyDecl( 5040 const ObjCPropertyDecl *PD, 5041 const Decl *Container) const { 5042 if (!Container) 5043 return nullptr; 5044 if (const ObjCCategoryImplDecl *CID = 5045 dyn_cast<ObjCCategoryImplDecl>(Container)) { 5046 for (auto *PID : CID->property_impls()) 5047 if (PID->getPropertyDecl() == PD) 5048 return PID; 5049 } else { 5050 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 5051 for (auto *PID : OID->property_impls()) 5052 if (PID->getPropertyDecl() == PD) 5053 return PID; 5054 } 5055 return nullptr; 5056} 5057 5058/// getObjCEncodingForPropertyDecl - Return the encoded type for this 5059/// property declaration. If non-NULL, Container must be either an 5060/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 5061/// NULL when getting encodings for protocol properties. 5062/// Property attributes are stored as a comma-delimited C string. The simple 5063/// attributes readonly and bycopy are encoded as single characters. The 5064/// parametrized attributes, getter=name, setter=name, and ivar=name, are 5065/// encoded as single characters, followed by an identifier. Property types 5066/// are also encoded as a parametrized attribute. The characters used to encode 5067/// these attributes are defined by the following enumeration: 5068/// @code 5069/// enum PropertyAttributes { 5070/// kPropertyReadOnly = 'R', // property is read-only. 5071/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 5072/// kPropertyByref = '&', // property is a reference to the value last assigned 5073/// kPropertyDynamic = 'D', // property is dynamic 5074/// kPropertyGetter = 'G', // followed by getter selector name 5075/// kPropertySetter = 'S', // followed by setter selector name 5076/// kPropertyInstanceVariable = 'V' // followed by instance variable name 5077/// kPropertyType = 'T' // followed by old-style type encoding. 5078/// kPropertyWeak = 'W' // 'weak' property 5079/// kPropertyStrong = 'P' // property GC'able 5080/// kPropertyNonAtomic = 'N' // property non-atomic 5081/// }; 5082/// @endcode 5083void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 5084 const Decl *Container, 5085 std::string& S) const { 5086 // Collect information from the property implementation decl(s). 5087 bool Dynamic = false; 5088 ObjCPropertyImplDecl *SynthesizePID = nullptr; 5089 5090 if (ObjCPropertyImplDecl *PropertyImpDecl = 5091 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) { 5092 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 5093 Dynamic = true; 5094 else 5095 SynthesizePID = PropertyImpDecl; 5096 } 5097 5098 // FIXME: This is not very efficient. 5099 S = "T"; 5100 5101 // Encode result type. 5102 // GCC has some special rules regarding encoding of properties which 5103 // closely resembles encoding of ivars. 5104 getObjCEncodingForPropertyType(PD->getType(), S); 5105 5106 if (PD->isReadOnly()) { 5107 S += ",R"; 5108 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy) 5109 S += ",C"; 5110 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain) 5111 S += ",&"; 5112 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 5113 S += ",W"; 5114 } else { 5115 switch (PD->getSetterKind()) { 5116 case ObjCPropertyDecl::Assign: break; 5117 case ObjCPropertyDecl::Copy: S += ",C"; break; 5118 case ObjCPropertyDecl::Retain: S += ",&"; break; 5119 case ObjCPropertyDecl::Weak: S += ",W"; break; 5120 } 5121 } 5122 5123 // It really isn't clear at all what this means, since properties 5124 // are "dynamic by default". 5125 if (Dynamic) 5126 S += ",D"; 5127 5128 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 5129 S += ",N"; 5130 5131 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 5132 S += ",G"; 5133 S += PD->getGetterName().getAsString(); 5134 } 5135 5136 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 5137 S += ",S"; 5138 S += PD->getSetterName().getAsString(); 5139 } 5140 5141 if (SynthesizePID) { 5142 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 5143 S += ",V"; 5144 S += OID->getNameAsString(); 5145 } 5146 5147 // FIXME: OBJCGC: weak & strong 5148} 5149 5150/// getLegacyIntegralTypeEncoding - 5151/// Another legacy compatibility encoding: 32-bit longs are encoded as 5152/// 'l' or 'L' , but not always. For typedefs, we need to use 5153/// 'i' or 'I' instead if encoding a struct field, or a pointer! 5154/// 5155void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 5156 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 5157 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 5158 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 5159 PointeeTy = UnsignedIntTy; 5160 else 5161 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 5162 PointeeTy = IntTy; 5163 } 5164 } 5165} 5166 5167void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 5168 const FieldDecl *Field, 5169 QualType *NotEncodedT) const { 5170 // We follow the behavior of gcc, expanding structures which are 5171 // directly pointed to, and expanding embedded structures. Note that 5172 // these rules are sufficient to prevent recursive encoding of the 5173 // same type. 5174 getObjCEncodingForTypeImpl(T, S, true, true, Field, 5175 true /* outermost type */, false, false, 5176 false, false, false, NotEncodedT); 5177} 5178 5179void ASTContext::getObjCEncodingForPropertyType(QualType T, 5180 std::string& S) const { 5181 // Encode result type. 5182 // GCC has some special rules regarding encoding of properties which 5183 // closely resembles encoding of ivars. 5184 getObjCEncodingForTypeImpl(T, S, true, true, nullptr, 5185 true /* outermost type */, 5186 true /* encoding property */); 5187} 5188 5189static char getObjCEncodingForPrimitiveKind(const ASTContext *C, 5190 BuiltinType::Kind kind) { 5191 switch (kind) { 5192 case BuiltinType::Void: return 'v'; 5193 case BuiltinType::Bool: return 'B'; 5194 case BuiltinType::Char_U: 5195 case BuiltinType::UChar: return 'C'; 5196 case BuiltinType::Char16: 5197 case BuiltinType::UShort: return 'S'; 5198 case BuiltinType::Char32: 5199 case BuiltinType::UInt: return 'I'; 5200 case BuiltinType::ULong: 5201 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q'; 5202 case BuiltinType::UInt128: return 'T'; 5203 case BuiltinType::ULongLong: return 'Q'; 5204 case BuiltinType::Char_S: 5205 case BuiltinType::SChar: return 'c'; 5206 case BuiltinType::Short: return 's'; 5207 case BuiltinType::WChar_S: 5208 case BuiltinType::WChar_U: 5209 case BuiltinType::Int: return 'i'; 5210 case BuiltinType::Long: 5211 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q'; 5212 case BuiltinType::LongLong: return 'q'; 5213 case BuiltinType::Int128: return 't'; 5214 case BuiltinType::Float: return 'f'; 5215 case BuiltinType::Double: return 'd'; 5216 case BuiltinType::LongDouble: return 'D'; 5217 case BuiltinType::NullPtr: return '*'; // like char* 5218 5219 case BuiltinType::Half: 5220 // FIXME: potentially need @encodes for these! 5221 return ' '; 5222 5223 case BuiltinType::ObjCId: 5224 case BuiltinType::ObjCClass: 5225 case BuiltinType::ObjCSel: 5226 llvm_unreachable("@encoding ObjC primitive type"); 5227 5228 // OpenCL and placeholder types don't need @encodings. 5229 case BuiltinType::OCLImage1d: 5230 case BuiltinType::OCLImage1dArray: 5231 case BuiltinType::OCLImage1dBuffer: 5232 case BuiltinType::OCLImage2d: 5233 case BuiltinType::OCLImage2dArray: 5234 case BuiltinType::OCLImage3d: 5235 case BuiltinType::OCLEvent: 5236 case BuiltinType::OCLSampler: 5237 case BuiltinType::Dependent: 5238#define BUILTIN_TYPE(KIND, ID) 5239#define PLACEHOLDER_TYPE(KIND, ID) \ 5240 case BuiltinType::KIND: 5241#include "clang/AST/BuiltinTypes.def" 5242 llvm_unreachable("invalid builtin type for @encode"); 5243 } 5244 llvm_unreachable("invalid BuiltinType::Kind value"); 5245} 5246 5247static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 5248 EnumDecl *Enum = ET->getDecl(); 5249 5250 // The encoding of an non-fixed enum type is always 'i', regardless of size. 5251 if (!Enum->isFixed()) 5252 return 'i'; 5253 5254 // The encoding of a fixed enum type matches its fixed underlying type. 5255 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>(); 5256 return getObjCEncodingForPrimitiveKind(C, BT->getKind()); 5257} 5258 5259static void EncodeBitField(const ASTContext *Ctx, std::string& S, 5260 QualType T, const FieldDecl *FD) { 5261 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 5262 S += 'b'; 5263 // The NeXT runtime encodes bit fields as b followed by the number of bits. 5264 // The GNU runtime requires more information; bitfields are encoded as b, 5265 // then the offset (in bits) of the first element, then the type of the 5266 // bitfield, then the size in bits. For example, in this structure: 5267 // 5268 // struct 5269 // { 5270 // int integer; 5271 // int flags:2; 5272 // }; 5273 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 5274 // runtime, but b32i2 for the GNU runtime. The reason for this extra 5275 // information is not especially sensible, but we're stuck with it for 5276 // compatibility with GCC, although providing it breaks anything that 5277 // actually uses runtime introspection and wants to work on both runtimes... 5278 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 5279 const RecordDecl *RD = FD->getParent(); 5280 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 5281 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 5282 if (const EnumType *ET = T->getAs<EnumType>()) 5283 S += ObjCEncodingForEnumType(Ctx, ET); 5284 else { 5285 const BuiltinType *BT = T->castAs<BuiltinType>(); 5286 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind()); 5287 } 5288 } 5289 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 5290} 5291 5292// FIXME: Use SmallString for accumulating string. 5293void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 5294 bool ExpandPointedToStructures, 5295 bool ExpandStructures, 5296 const FieldDecl *FD, 5297 bool OutermostType, 5298 bool EncodingProperty, 5299 bool StructField, 5300 bool EncodeBlockParameters, 5301 bool EncodeClassNames, 5302 bool EncodePointerToObjCTypedef, 5303 QualType *NotEncodedT) const { 5304 CanQualType CT = getCanonicalType(T); 5305 switch (CT->getTypeClass()) { 5306 case Type::Builtin: 5307 case Type::Enum: 5308 if (FD && FD->isBitField()) 5309 return EncodeBitField(this, S, T, FD); 5310 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT)) 5311 S += getObjCEncodingForPrimitiveKind(this, BT->getKind()); 5312 else 5313 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT)); 5314 return; 5315 5316 case Type::Complex: { 5317 const ComplexType *CT = T->castAs<ComplexType>(); 5318 S += 'j'; 5319 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr); 5320 return; 5321 } 5322 5323 case Type::Atomic: { 5324 const AtomicType *AT = T->castAs<AtomicType>(); 5325 S += 'A'; 5326 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr); 5327 return; 5328 } 5329 5330 // encoding for pointer or reference types. 5331 case Type::Pointer: 5332 case Type::LValueReference: 5333 case Type::RValueReference: { 5334 QualType PointeeTy; 5335 if (isa<PointerType>(CT)) { 5336 const PointerType *PT = T->castAs<PointerType>(); 5337 if (PT->isObjCSelType()) { 5338 S += ':'; 5339 return; 5340 } 5341 PointeeTy = PT->getPointeeType(); 5342 } else { 5343 PointeeTy = T->castAs<ReferenceType>()->getPointeeType(); 5344 } 5345 5346 bool isReadOnly = false; 5347 // For historical/compatibility reasons, the read-only qualifier of the 5348 // pointee gets emitted _before_ the '^'. The read-only qualifier of 5349 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 5350 // Also, do not emit the 'r' for anything but the outermost type! 5351 if (isa<TypedefType>(T.getTypePtr())) { 5352 if (OutermostType && T.isConstQualified()) { 5353 isReadOnly = true; 5354 S += 'r'; 5355 } 5356 } else if (OutermostType) { 5357 QualType P = PointeeTy; 5358 while (P->getAs<PointerType>()) 5359 P = P->getAs<PointerType>()->getPointeeType(); 5360 if (P.isConstQualified()) { 5361 isReadOnly = true; 5362 S += 'r'; 5363 } 5364 } 5365 if (isReadOnly) { 5366 // Another legacy compatibility encoding. Some ObjC qualifier and type 5367 // combinations need to be rearranged. 5368 // Rewrite "in const" from "nr" to "rn" 5369 if (StringRef(S).endswith("nr")) 5370 S.replace(S.end()-2, S.end(), "rn"); 5371 } 5372 5373 if (PointeeTy->isCharType()) { 5374 // char pointer types should be encoded as '*' unless it is a 5375 // type that has been typedef'd to 'BOOL'. 5376 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 5377 S += '*'; 5378 return; 5379 } 5380 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 5381 // GCC binary compat: Need to convert "struct objc_class *" to "#". 5382 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 5383 S += '#'; 5384 return; 5385 } 5386 // GCC binary compat: Need to convert "struct objc_object *" to "@". 5387 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 5388 S += '@'; 5389 return; 5390 } 5391 // fall through... 5392 } 5393 S += '^'; 5394 getLegacyIntegralTypeEncoding(PointeeTy); 5395 5396 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 5397 nullptr, false, false, false, false, false, false, 5398 NotEncodedT); 5399 return; 5400 } 5401 5402 case Type::ConstantArray: 5403 case Type::IncompleteArray: 5404 case Type::VariableArray: { 5405 const ArrayType *AT = cast<ArrayType>(CT); 5406 5407 if (isa<IncompleteArrayType>(AT) && !StructField) { 5408 // Incomplete arrays are encoded as a pointer to the array element. 5409 S += '^'; 5410 5411 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5412 false, ExpandStructures, FD); 5413 } else { 5414 S += '['; 5415 5416 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 5417 S += llvm::utostr(CAT->getSize().getZExtValue()); 5418 else { 5419 //Variable length arrays are encoded as a regular array with 0 elements. 5420 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 5421 "Unknown array type!"); 5422 S += '0'; 5423 } 5424 5425 getObjCEncodingForTypeImpl(AT->getElementType(), S, 5426 false, ExpandStructures, FD, 5427 false, false, false, false, false, false, 5428 NotEncodedT); 5429 S += ']'; 5430 } 5431 return; 5432 } 5433 5434 case Type::FunctionNoProto: 5435 case Type::FunctionProto: 5436 S += '?'; 5437 return; 5438 5439 case Type::Record: { 5440 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl(); 5441 S += RDecl->isUnion() ? '(' : '{'; 5442 // Anonymous structures print as '?' 5443 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 5444 S += II->getName(); 5445 if (ClassTemplateSpecializationDecl *Spec 5446 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 5447 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 5448 llvm::raw_string_ostream OS(S); 5449 TemplateSpecializationType::PrintTemplateArgumentList(OS, 5450 TemplateArgs.data(), 5451 TemplateArgs.size(), 5452 (*this).getPrintingPolicy()); 5453 } 5454 } else { 5455 S += '?'; 5456 } 5457 if (ExpandStructures) { 5458 S += '='; 5459 if (!RDecl->isUnion()) { 5460 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT); 5461 } else { 5462 for (const auto *Field : RDecl->fields()) { 5463 if (FD) { 5464 S += '"'; 5465 S += Field->getNameAsString(); 5466 S += '"'; 5467 } 5468 5469 // Special case bit-fields. 5470 if (Field->isBitField()) { 5471 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 5472 Field); 5473 } else { 5474 QualType qt = Field->getType(); 5475 getLegacyIntegralTypeEncoding(qt); 5476 getObjCEncodingForTypeImpl(qt, S, false, true, 5477 FD, /*OutermostType*/false, 5478 /*EncodingProperty*/false, 5479 /*StructField*/true, 5480 false, false, false, NotEncodedT); 5481 } 5482 } 5483 } 5484 } 5485 S += RDecl->isUnion() ? ')' : '}'; 5486 return; 5487 } 5488 5489 case Type::BlockPointer: { 5490 const BlockPointerType *BT = T->castAs<BlockPointerType>(); 5491 S += "@?"; // Unlike a pointer-to-function, which is "^?". 5492 if (EncodeBlockParameters) { 5493 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>(); 5494 5495 S += '<'; 5496 // Block return type 5497 getObjCEncodingForTypeImpl( 5498 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures, 5499 FD, false /* OutermostType */, EncodingProperty, 5500 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false, 5501 NotEncodedT); 5502 // Block self 5503 S += "@?"; 5504 // Block parameters 5505 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 5506 for (const auto &I : FPT->param_types()) 5507 getObjCEncodingForTypeImpl( 5508 I, S, ExpandPointedToStructures, ExpandStructures, FD, 5509 false /* OutermostType */, EncodingProperty, 5510 false /* StructField */, EncodeBlockParameters, EncodeClassNames, 5511 false, NotEncodedT); 5512 } 5513 S += '>'; 5514 } 5515 return; 5516 } 5517 5518 case Type::ObjCObject: { 5519 // hack to match legacy encoding of *id and *Class 5520 QualType Ty = getObjCObjectPointerType(CT); 5521 if (Ty->isObjCIdType()) { 5522 S += "{objc_object=}"; 5523 return; 5524 } 5525 else if (Ty->isObjCClassType()) { 5526 S += "{objc_class=}"; 5527 return; 5528 } 5529 } 5530 5531 case Type::ObjCInterface: { 5532 // Ignore protocol qualifiers when mangling at this level. 5533 T = T->castAs<ObjCObjectType>()->getBaseType(); 5534 5535 // The assumption seems to be that this assert will succeed 5536 // because nested levels will have filtered out 'id' and 'Class'. 5537 const ObjCInterfaceType *OIT = T->castAs<ObjCInterfaceType>(); 5538 // @encode(class_name) 5539 ObjCInterfaceDecl *OI = OIT->getDecl(); 5540 S += '{'; 5541 const IdentifierInfo *II = OI->getIdentifier(); 5542 S += II->getName(); 5543 S += '='; 5544 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5545 DeepCollectObjCIvars(OI, true, Ivars); 5546 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 5547 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 5548 if (Field->isBitField()) 5549 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 5550 else 5551 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD, 5552 false, false, false, false, false, 5553 EncodePointerToObjCTypedef, 5554 NotEncodedT); 5555 } 5556 S += '}'; 5557 return; 5558 } 5559 5560 case Type::ObjCObjectPointer: { 5561 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>(); 5562 if (OPT->isObjCIdType()) { 5563 S += '@'; 5564 return; 5565 } 5566 5567 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 5568 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 5569 // Since this is a binary compatibility issue, need to consult with runtime 5570 // folks. Fortunately, this is a *very* obsure construct. 5571 S += '#'; 5572 return; 5573 } 5574 5575 if (OPT->isObjCQualifiedIdType()) { 5576 getObjCEncodingForTypeImpl(getObjCIdType(), S, 5577 ExpandPointedToStructures, 5578 ExpandStructures, FD); 5579 if (FD || EncodingProperty || EncodeClassNames) { 5580 // Note that we do extended encoding of protocol qualifer list 5581 // Only when doing ivar or property encoding. 5582 S += '"'; 5583 for (const auto *I : OPT->quals()) { 5584 S += '<'; 5585 S += I->getNameAsString(); 5586 S += '>'; 5587 } 5588 S += '"'; 5589 } 5590 return; 5591 } 5592 5593 QualType PointeeTy = OPT->getPointeeType(); 5594 if (!EncodingProperty && 5595 isa<TypedefType>(PointeeTy.getTypePtr()) && 5596 !EncodePointerToObjCTypedef) { 5597 // Another historical/compatibility reason. 5598 // We encode the underlying type which comes out as 5599 // {...}; 5600 S += '^'; 5601 if (FD && OPT->getInterfaceDecl()) { 5602 // Prevent recursive encoding of fields in some rare cases. 5603 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl(); 5604 SmallVector<const ObjCIvarDecl*, 32> Ivars; 5605 DeepCollectObjCIvars(OI, true, Ivars); 5606 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 5607 if (cast<FieldDecl>(Ivars[i]) == FD) { 5608 S += '{'; 5609 S += OI->getIdentifier()->getName(); 5610 S += '}'; 5611 return; 5612 } 5613 } 5614 } 5615 getObjCEncodingForTypeImpl(PointeeTy, S, 5616 false, ExpandPointedToStructures, 5617 nullptr, 5618 false, false, false, false, false, 5619 /*EncodePointerToObjCTypedef*/true); 5620 return; 5621 } 5622 5623 S += '@'; 5624 if (OPT->getInterfaceDecl() && 5625 (FD || EncodingProperty || EncodeClassNames)) { 5626 S += '"'; 5627 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 5628 for (const auto *I : OPT->quals()) { 5629 S += '<'; 5630 S += I->getNameAsString(); 5631 S += '>'; 5632 } 5633 S += '"'; 5634 } 5635 return; 5636 } 5637 5638 // gcc just blithely ignores member pointers. 5639 // FIXME: we shoul do better than that. 'M' is available. 5640 case Type::MemberPointer: 5641 // This matches gcc's encoding, even though technically it is insufficient. 5642 //FIXME. We should do a better job than gcc. 5643 case Type::Vector: 5644 case Type::ExtVector: 5645 // Until we have a coherent encoding of these three types, issue warning. 5646 { if (NotEncodedT) 5647 *NotEncodedT = T; 5648 return; 5649 } 5650 5651 // We could see an undeduced auto type here during error recovery. 5652 // Just ignore it. 5653 case Type::Auto: 5654 return; 5655 5656 5657#define ABSTRACT_TYPE(KIND, BASE) 5658#define TYPE(KIND, BASE) 5659#define DEPENDENT_TYPE(KIND, BASE) \ 5660 case Type::KIND: 5661#define NON_CANONICAL_TYPE(KIND, BASE) \ 5662 case Type::KIND: 5663#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \ 5664 case Type::KIND: 5665#include "clang/AST/TypeNodes.def" 5666 llvm_unreachable("@encode for dependent type!"); 5667 } 5668 llvm_unreachable("bad type kind!"); 5669} 5670 5671void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 5672 std::string &S, 5673 const FieldDecl *FD, 5674 bool includeVBases, 5675 QualType *NotEncodedT) const { 5676 assert(RDecl && "Expected non-null RecordDecl"); 5677 assert(!RDecl->isUnion() && "Should not be called for unions"); 5678 if (!RDecl->getDefinition()) 5679 return; 5680 5681 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 5682 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 5683 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 5684 5685 if (CXXRec) { 5686 for (const auto &BI : CXXRec->bases()) { 5687 if (!BI.isVirtual()) { 5688 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 5689 if (base->isEmpty()) 5690 continue; 5691 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 5692 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5693 std::make_pair(offs, base)); 5694 } 5695 } 5696 } 5697 5698 unsigned i = 0; 5699 for (auto *Field : RDecl->fields()) { 5700 uint64_t offs = layout.getFieldOffset(i); 5701 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5702 std::make_pair(offs, Field)); 5703 ++i; 5704 } 5705 5706 if (CXXRec && includeVBases) { 5707 for (const auto &BI : CXXRec->vbases()) { 5708 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl(); 5709 if (base->isEmpty()) 5710 continue; 5711 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 5712 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) && 5713 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 5714 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 5715 std::make_pair(offs, base)); 5716 } 5717 } 5718 5719 CharUnits size; 5720 if (CXXRec) { 5721 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 5722 } else { 5723 size = layout.getSize(); 5724 } 5725 5726#ifndef NDEBUG 5727 uint64_t CurOffs = 0; 5728#endif 5729 std::multimap<uint64_t, NamedDecl *>::iterator 5730 CurLayObj = FieldOrBaseOffsets.begin(); 5731 5732 if (CXXRec && CXXRec->isDynamicClass() && 5733 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 5734 if (FD) { 5735 S += "\"_vptr$"; 5736 std::string recname = CXXRec->getNameAsString(); 5737 if (recname.empty()) recname = "?"; 5738 S += recname; 5739 S += '"'; 5740 } 5741 S += "^^?"; 5742#ifndef NDEBUG 5743 CurOffs += getTypeSize(VoidPtrTy); 5744#endif 5745 } 5746 5747 if (!RDecl->hasFlexibleArrayMember()) { 5748 // Mark the end of the structure. 5749 uint64_t offs = toBits(size); 5750 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5751 std::make_pair(offs, nullptr)); 5752 } 5753 5754 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 5755#ifndef NDEBUG 5756 assert(CurOffs <= CurLayObj->first); 5757 if (CurOffs < CurLayObj->first) { 5758 uint64_t padding = CurLayObj->first - CurOffs; 5759 // FIXME: There doesn't seem to be a way to indicate in the encoding that 5760 // packing/alignment of members is different that normal, in which case 5761 // the encoding will be out-of-sync with the real layout. 5762 // If the runtime switches to just consider the size of types without 5763 // taking into account alignment, we could make padding explicit in the 5764 // encoding (e.g. using arrays of chars). The encoding strings would be 5765 // longer then though. 5766 CurOffs += padding; 5767 } 5768#endif 5769 5770 NamedDecl *dcl = CurLayObj->second; 5771 if (!dcl) 5772 break; // reached end of structure. 5773 5774 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 5775 // We expand the bases without their virtual bases since those are going 5776 // in the initial structure. Note that this differs from gcc which 5777 // expands virtual bases each time one is encountered in the hierarchy, 5778 // making the encoding type bigger than it really is. 5779 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false, 5780 NotEncodedT); 5781 assert(!base->isEmpty()); 5782#ifndef NDEBUG 5783 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 5784#endif 5785 } else { 5786 FieldDecl *field = cast<FieldDecl>(dcl); 5787 if (FD) { 5788 S += '"'; 5789 S += field->getNameAsString(); 5790 S += '"'; 5791 } 5792 5793 if (field->isBitField()) { 5794 EncodeBitField(this, S, field->getType(), field); 5795#ifndef NDEBUG 5796 CurOffs += field->getBitWidthValue(*this); 5797#endif 5798 } else { 5799 QualType qt = field->getType(); 5800 getLegacyIntegralTypeEncoding(qt); 5801 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 5802 /*OutermostType*/false, 5803 /*EncodingProperty*/false, 5804 /*StructField*/true, 5805 false, false, false, NotEncodedT); 5806#ifndef NDEBUG 5807 CurOffs += getTypeSize(field->getType()); 5808#endif 5809 } 5810 } 5811 } 5812} 5813 5814void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 5815 std::string& S) const { 5816 if (QT & Decl::OBJC_TQ_In) 5817 S += 'n'; 5818 if (QT & Decl::OBJC_TQ_Inout) 5819 S += 'N'; 5820 if (QT & Decl::OBJC_TQ_Out) 5821 S += 'o'; 5822 if (QT & Decl::OBJC_TQ_Bycopy) 5823 S += 'O'; 5824 if (QT & Decl::OBJC_TQ_Byref) 5825 S += 'R'; 5826 if (QT & Decl::OBJC_TQ_Oneway) 5827 S += 'V'; 5828} 5829 5830TypedefDecl *ASTContext::getObjCIdDecl() const { 5831 if (!ObjCIdDecl) { 5832 QualType T = getObjCObjectType(ObjCBuiltinIdTy, nullptr, 0); 5833 T = getObjCObjectPointerType(T); 5834 ObjCIdDecl = buildImplicitTypedef(T, "id"); 5835 } 5836 return ObjCIdDecl; 5837} 5838 5839TypedefDecl *ASTContext::getObjCSelDecl() const { 5840 if (!ObjCSelDecl) { 5841 QualType T = getPointerType(ObjCBuiltinSelTy); 5842 ObjCSelDecl = buildImplicitTypedef(T, "SEL"); 5843 } 5844 return ObjCSelDecl; 5845} 5846 5847TypedefDecl *ASTContext::getObjCClassDecl() const { 5848 if (!ObjCClassDecl) { 5849 QualType T = getObjCObjectType(ObjCBuiltinClassTy, nullptr, 0); 5850 T = getObjCObjectPointerType(T); 5851 ObjCClassDecl = buildImplicitTypedef(T, "Class"); 5852 } 5853 return ObjCClassDecl; 5854} 5855 5856ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 5857 if (!ObjCProtocolClassDecl) { 5858 ObjCProtocolClassDecl 5859 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 5860 SourceLocation(), 5861 &Idents.get("Protocol"), 5862 /*PrevDecl=*/nullptr, 5863 SourceLocation(), true); 5864 } 5865 5866 return ObjCProtocolClassDecl; 5867} 5868 5869//===----------------------------------------------------------------------===// 5870// __builtin_va_list Construction Functions 5871//===----------------------------------------------------------------------===// 5872 5873static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 5874 // typedef char* __builtin_va_list; 5875 QualType T = Context->getPointerType(Context->CharTy); 5876 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 5877} 5878 5879static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 5880 // typedef void* __builtin_va_list; 5881 QualType T = Context->getPointerType(Context->VoidTy); 5882 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 5883} 5884 5885static TypedefDecl * 5886CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) { 5887 // struct __va_list 5888 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list"); 5889 if (Context->getLangOpts().CPlusPlus) { 5890 // namespace std { struct __va_list { 5891 NamespaceDecl *NS; 5892 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 5893 Context->getTranslationUnitDecl(), 5894 /*Inline*/ false, SourceLocation(), 5895 SourceLocation(), &Context->Idents.get("std"), 5896 /*PrevDecl*/ nullptr); 5897 NS->setImplicit(); 5898 VaListTagDecl->setDeclContext(NS); 5899 } 5900 5901 VaListTagDecl->startDefinition(); 5902 5903 const size_t NumFields = 5; 5904 QualType FieldTypes[NumFields]; 5905 const char *FieldNames[NumFields]; 5906 5907 // void *__stack; 5908 FieldTypes[0] = Context->getPointerType(Context->VoidTy); 5909 FieldNames[0] = "__stack"; 5910 5911 // void *__gr_top; 5912 FieldTypes[1] = Context->getPointerType(Context->VoidTy); 5913 FieldNames[1] = "__gr_top"; 5914 5915 // void *__vr_top; 5916 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 5917 FieldNames[2] = "__vr_top"; 5918 5919 // int __gr_offs; 5920 FieldTypes[3] = Context->IntTy; 5921 FieldNames[3] = "__gr_offs"; 5922 5923 // int __vr_offs; 5924 FieldTypes[4] = Context->IntTy; 5925 FieldNames[4] = "__vr_offs"; 5926 5927 // Create fields 5928 for (unsigned i = 0; i < NumFields; ++i) { 5929 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 5930 VaListTagDecl, 5931 SourceLocation(), 5932 SourceLocation(), 5933 &Context->Idents.get(FieldNames[i]), 5934 FieldTypes[i], /*TInfo=*/nullptr, 5935 /*BitWidth=*/nullptr, 5936 /*Mutable=*/false, 5937 ICIS_NoInit); 5938 Field->setAccess(AS_public); 5939 VaListTagDecl->addDecl(Field); 5940 } 5941 VaListTagDecl->completeDefinition(); 5942 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5943 Context->VaListTagTy = VaListTagType; 5944 5945 // } __builtin_va_list; 5946 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list"); 5947} 5948 5949static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 5950 // typedef struct __va_list_tag { 5951 RecordDecl *VaListTagDecl; 5952 5953 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 5954 VaListTagDecl->startDefinition(); 5955 5956 const size_t NumFields = 5; 5957 QualType FieldTypes[NumFields]; 5958 const char *FieldNames[NumFields]; 5959 5960 // unsigned char gpr; 5961 FieldTypes[0] = Context->UnsignedCharTy; 5962 FieldNames[0] = "gpr"; 5963 5964 // unsigned char fpr; 5965 FieldTypes[1] = Context->UnsignedCharTy; 5966 FieldNames[1] = "fpr"; 5967 5968 // unsigned short reserved; 5969 FieldTypes[2] = Context->UnsignedShortTy; 5970 FieldNames[2] = "reserved"; 5971 5972 // void* overflow_arg_area; 5973 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5974 FieldNames[3] = "overflow_arg_area"; 5975 5976 // void* reg_save_area; 5977 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 5978 FieldNames[4] = "reg_save_area"; 5979 5980 // Create fields 5981 for (unsigned i = 0; i < NumFields; ++i) { 5982 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 5983 SourceLocation(), 5984 SourceLocation(), 5985 &Context->Idents.get(FieldNames[i]), 5986 FieldTypes[i], /*TInfo=*/nullptr, 5987 /*BitWidth=*/nullptr, 5988 /*Mutable=*/false, 5989 ICIS_NoInit); 5990 Field->setAccess(AS_public); 5991 VaListTagDecl->addDecl(Field); 5992 } 5993 VaListTagDecl->completeDefinition(); 5994 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5995 Context->VaListTagTy = VaListTagType; 5996 5997 // } __va_list_tag; 5998 TypedefDecl *VaListTagTypedefDecl = 5999 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6000 6001 QualType VaListTagTypedefType = 6002 Context->getTypedefType(VaListTagTypedefDecl); 6003 6004 // typedef __va_list_tag __builtin_va_list[1]; 6005 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6006 QualType VaListTagArrayType 6007 = Context->getConstantArrayType(VaListTagTypedefType, 6008 Size, ArrayType::Normal, 0); 6009 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6010} 6011 6012static TypedefDecl * 6013CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 6014 // typedef struct __va_list_tag { 6015 RecordDecl *VaListTagDecl; 6016 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6017 VaListTagDecl->startDefinition(); 6018 6019 const size_t NumFields = 4; 6020 QualType FieldTypes[NumFields]; 6021 const char *FieldNames[NumFields]; 6022 6023 // unsigned gp_offset; 6024 FieldTypes[0] = Context->UnsignedIntTy; 6025 FieldNames[0] = "gp_offset"; 6026 6027 // unsigned fp_offset; 6028 FieldTypes[1] = Context->UnsignedIntTy; 6029 FieldNames[1] = "fp_offset"; 6030 6031 // void* overflow_arg_area; 6032 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6033 FieldNames[2] = "overflow_arg_area"; 6034 6035 // void* reg_save_area; 6036 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6037 FieldNames[3] = "reg_save_area"; 6038 6039 // Create fields 6040 for (unsigned i = 0; i < NumFields; ++i) { 6041 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6042 VaListTagDecl, 6043 SourceLocation(), 6044 SourceLocation(), 6045 &Context->Idents.get(FieldNames[i]), 6046 FieldTypes[i], /*TInfo=*/nullptr, 6047 /*BitWidth=*/nullptr, 6048 /*Mutable=*/false, 6049 ICIS_NoInit); 6050 Field->setAccess(AS_public); 6051 VaListTagDecl->addDecl(Field); 6052 } 6053 VaListTagDecl->completeDefinition(); 6054 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6055 Context->VaListTagTy = VaListTagType; 6056 6057 // } __va_list_tag; 6058 TypedefDecl *VaListTagTypedefDecl = 6059 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6060 6061 QualType VaListTagTypedefType = 6062 Context->getTypedefType(VaListTagTypedefDecl); 6063 6064 // typedef __va_list_tag __builtin_va_list[1]; 6065 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6066 QualType VaListTagArrayType 6067 = Context->getConstantArrayType(VaListTagTypedefType, 6068 Size, ArrayType::Normal,0); 6069 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6070} 6071 6072static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 6073 // typedef int __builtin_va_list[4]; 6074 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 6075 QualType IntArrayType 6076 = Context->getConstantArrayType(Context->IntTy, 6077 Size, ArrayType::Normal, 0); 6078 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list"); 6079} 6080 6081static TypedefDecl * 6082CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) { 6083 // struct __va_list 6084 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list"); 6085 if (Context->getLangOpts().CPlusPlus) { 6086 // namespace std { struct __va_list { 6087 NamespaceDecl *NS; 6088 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context), 6089 Context->getTranslationUnitDecl(), 6090 /*Inline*/false, SourceLocation(), 6091 SourceLocation(), &Context->Idents.get("std"), 6092 /*PrevDecl*/ nullptr); 6093 NS->setImplicit(); 6094 VaListDecl->setDeclContext(NS); 6095 } 6096 6097 VaListDecl->startDefinition(); 6098 6099 // void * __ap; 6100 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6101 VaListDecl, 6102 SourceLocation(), 6103 SourceLocation(), 6104 &Context->Idents.get("__ap"), 6105 Context->getPointerType(Context->VoidTy), 6106 /*TInfo=*/nullptr, 6107 /*BitWidth=*/nullptr, 6108 /*Mutable=*/false, 6109 ICIS_NoInit); 6110 Field->setAccess(AS_public); 6111 VaListDecl->addDecl(Field); 6112 6113 // }; 6114 VaListDecl->completeDefinition(); 6115 6116 // typedef struct __va_list __builtin_va_list; 6117 QualType T = Context->getRecordType(VaListDecl); 6118 return Context->buildImplicitTypedef(T, "__builtin_va_list"); 6119} 6120 6121static TypedefDecl * 6122CreateSystemZBuiltinVaListDecl(const ASTContext *Context) { 6123 // typedef struct __va_list_tag { 6124 RecordDecl *VaListTagDecl; 6125 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag"); 6126 VaListTagDecl->startDefinition(); 6127 6128 const size_t NumFields = 4; 6129 QualType FieldTypes[NumFields]; 6130 const char *FieldNames[NumFields]; 6131 6132 // long __gpr; 6133 FieldTypes[0] = Context->LongTy; 6134 FieldNames[0] = "__gpr"; 6135 6136 // long __fpr; 6137 FieldTypes[1] = Context->LongTy; 6138 FieldNames[1] = "__fpr"; 6139 6140 // void *__overflow_arg_area; 6141 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 6142 FieldNames[2] = "__overflow_arg_area"; 6143 6144 // void *__reg_save_area; 6145 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 6146 FieldNames[3] = "__reg_save_area"; 6147 6148 // Create fields 6149 for (unsigned i = 0; i < NumFields; ++i) { 6150 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 6151 VaListTagDecl, 6152 SourceLocation(), 6153 SourceLocation(), 6154 &Context->Idents.get(FieldNames[i]), 6155 FieldTypes[i], /*TInfo=*/nullptr, 6156 /*BitWidth=*/nullptr, 6157 /*Mutable=*/false, 6158 ICIS_NoInit); 6159 Field->setAccess(AS_public); 6160 VaListTagDecl->addDecl(Field); 6161 } 6162 VaListTagDecl->completeDefinition(); 6163 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 6164 Context->VaListTagTy = VaListTagType; 6165 6166 // } __va_list_tag; 6167 TypedefDecl *VaListTagTypedefDecl = 6168 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag"); 6169 QualType VaListTagTypedefType = 6170 Context->getTypedefType(VaListTagTypedefDecl); 6171 6172 // typedef __va_list_tag __builtin_va_list[1]; 6173 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 6174 QualType VaListTagArrayType 6175 = Context->getConstantArrayType(VaListTagTypedefType, 6176 Size, ArrayType::Normal,0); 6177 6178 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list"); 6179} 6180 6181static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 6182 TargetInfo::BuiltinVaListKind Kind) { 6183 switch (Kind) { 6184 case TargetInfo::CharPtrBuiltinVaList: 6185 return CreateCharPtrBuiltinVaListDecl(Context); 6186 case TargetInfo::VoidPtrBuiltinVaList: 6187 return CreateVoidPtrBuiltinVaListDecl(Context); 6188 case TargetInfo::AArch64ABIBuiltinVaList: 6189 return CreateAArch64ABIBuiltinVaListDecl(Context); 6190 case TargetInfo::PowerABIBuiltinVaList: 6191 return CreatePowerABIBuiltinVaListDecl(Context); 6192 case TargetInfo::X86_64ABIBuiltinVaList: 6193 return CreateX86_64ABIBuiltinVaListDecl(Context); 6194 case TargetInfo::PNaClABIBuiltinVaList: 6195 return CreatePNaClABIBuiltinVaListDecl(Context); 6196 case TargetInfo::AAPCSABIBuiltinVaList: 6197 return CreateAAPCSABIBuiltinVaListDecl(Context); 6198 case TargetInfo::SystemZBuiltinVaList: 6199 return CreateSystemZBuiltinVaListDecl(Context); 6200 } 6201 6202 llvm_unreachable("Unhandled __builtin_va_list type kind"); 6203} 6204 6205TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 6206 if (!BuiltinVaListDecl) { 6207 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 6208 assert(BuiltinVaListDecl->isImplicit()); 6209 } 6210 6211 return BuiltinVaListDecl; 6212} 6213 6214QualType ASTContext::getVaListTagType() const { 6215 // Force the creation of VaListTagTy by building the __builtin_va_list 6216 // declaration. 6217 if (VaListTagTy.isNull()) 6218 (void) getBuiltinVaListDecl(); 6219 6220 return VaListTagTy; 6221} 6222 6223void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 6224 assert(ObjCConstantStringType.isNull() && 6225 "'NSConstantString' type already set!"); 6226 6227 ObjCConstantStringType = getObjCInterfaceType(Decl); 6228} 6229 6230/// \brief Retrieve the template name that corresponds to a non-empty 6231/// lookup. 6232TemplateName 6233ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 6234 UnresolvedSetIterator End) const { 6235 unsigned size = End - Begin; 6236 assert(size > 1 && "set is not overloaded!"); 6237 6238 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 6239 size * sizeof(FunctionTemplateDecl*)); 6240 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 6241 6242 NamedDecl **Storage = OT->getStorage(); 6243 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 6244 NamedDecl *D = *I; 6245 assert(isa<FunctionTemplateDecl>(D) || 6246 (isa<UsingShadowDecl>(D) && 6247 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 6248 *Storage++ = D; 6249 } 6250 6251 return TemplateName(OT); 6252} 6253 6254/// \brief Retrieve the template name that represents a qualified 6255/// template name such as \c std::vector. 6256TemplateName 6257ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 6258 bool TemplateKeyword, 6259 TemplateDecl *Template) const { 6260 assert(NNS && "Missing nested-name-specifier in qualified template name"); 6261 6262 // FIXME: Canonicalization? 6263 llvm::FoldingSetNodeID ID; 6264 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 6265 6266 void *InsertPos = nullptr; 6267 QualifiedTemplateName *QTN = 6268 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6269 if (!QTN) { 6270 QTN = new (*this, llvm::alignOf<QualifiedTemplateName>()) 6271 QualifiedTemplateName(NNS, TemplateKeyword, Template); 6272 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 6273 } 6274 6275 return TemplateName(QTN); 6276} 6277 6278/// \brief Retrieve the template name that represents a dependent 6279/// template name such as \c MetaFun::template apply. 6280TemplateName 6281ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 6282 const IdentifierInfo *Name) const { 6283 assert((!NNS || NNS->isDependent()) && 6284 "Nested name specifier must be dependent"); 6285 6286 llvm::FoldingSetNodeID ID; 6287 DependentTemplateName::Profile(ID, NNS, Name); 6288 6289 void *InsertPos = nullptr; 6290 DependentTemplateName *QTN = 6291 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6292 6293 if (QTN) 6294 return TemplateName(QTN); 6295 6296 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 6297 if (CanonNNS == NNS) { 6298 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6299 DependentTemplateName(NNS, Name); 6300 } else { 6301 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 6302 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6303 DependentTemplateName(NNS, Name, Canon); 6304 DependentTemplateName *CheckQTN = 6305 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6306 assert(!CheckQTN && "Dependent type name canonicalization broken"); 6307 (void)CheckQTN; 6308 } 6309 6310 DependentTemplateNames.InsertNode(QTN, InsertPos); 6311 return TemplateName(QTN); 6312} 6313 6314/// \brief Retrieve the template name that represents a dependent 6315/// template name such as \c MetaFun::template operator+. 6316TemplateName 6317ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 6318 OverloadedOperatorKind Operator) const { 6319 assert((!NNS || NNS->isDependent()) && 6320 "Nested name specifier must be dependent"); 6321 6322 llvm::FoldingSetNodeID ID; 6323 DependentTemplateName::Profile(ID, NNS, Operator); 6324 6325 void *InsertPos = nullptr; 6326 DependentTemplateName *QTN 6327 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6328 6329 if (QTN) 6330 return TemplateName(QTN); 6331 6332 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 6333 if (CanonNNS == NNS) { 6334 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6335 DependentTemplateName(NNS, Operator); 6336 } else { 6337 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 6338 QTN = new (*this, llvm::alignOf<DependentTemplateName>()) 6339 DependentTemplateName(NNS, Operator, Canon); 6340 6341 DependentTemplateName *CheckQTN 6342 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 6343 assert(!CheckQTN && "Dependent template name canonicalization broken"); 6344 (void)CheckQTN; 6345 } 6346 6347 DependentTemplateNames.InsertNode(QTN, InsertPos); 6348 return TemplateName(QTN); 6349} 6350 6351TemplateName 6352ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 6353 TemplateName replacement) const { 6354 llvm::FoldingSetNodeID ID; 6355 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 6356 6357 void *insertPos = nullptr; 6358 SubstTemplateTemplateParmStorage *subst 6359 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 6360 6361 if (!subst) { 6362 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 6363 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 6364 } 6365 6366 return TemplateName(subst); 6367} 6368 6369TemplateName 6370ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 6371 const TemplateArgument &ArgPack) const { 6372 ASTContext &Self = const_cast<ASTContext &>(*this); 6373 llvm::FoldingSetNodeID ID; 6374 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 6375 6376 void *InsertPos = nullptr; 6377 SubstTemplateTemplateParmPackStorage *Subst 6378 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 6379 6380 if (!Subst) { 6381 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 6382 ArgPack.pack_size(), 6383 ArgPack.pack_begin()); 6384 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 6385 } 6386 6387 return TemplateName(Subst); 6388} 6389 6390/// getFromTargetType - Given one of the integer types provided by 6391/// TargetInfo, produce the corresponding type. The unsigned @p Type 6392/// is actually a value of type @c TargetInfo::IntType. 6393CanQualType ASTContext::getFromTargetType(unsigned Type) const { 6394 switch (Type) { 6395 case TargetInfo::NoInt: return CanQualType(); 6396 case TargetInfo::SignedChar: return SignedCharTy; 6397 case TargetInfo::UnsignedChar: return UnsignedCharTy; 6398 case TargetInfo::SignedShort: return ShortTy; 6399 case TargetInfo::UnsignedShort: return UnsignedShortTy; 6400 case TargetInfo::SignedInt: return IntTy; 6401 case TargetInfo::UnsignedInt: return UnsignedIntTy; 6402 case TargetInfo::SignedLong: return LongTy; 6403 case TargetInfo::UnsignedLong: return UnsignedLongTy; 6404 case TargetInfo::SignedLongLong: return LongLongTy; 6405 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 6406 } 6407 6408 llvm_unreachable("Unhandled TargetInfo::IntType value"); 6409} 6410 6411//===----------------------------------------------------------------------===// 6412// Type Predicates. 6413//===----------------------------------------------------------------------===// 6414 6415/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 6416/// garbage collection attribute. 6417/// 6418Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 6419 if (getLangOpts().getGC() == LangOptions::NonGC) 6420 return Qualifiers::GCNone; 6421 6422 assert(getLangOpts().ObjC1); 6423 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 6424 6425 // Default behaviour under objective-C's gc is for ObjC pointers 6426 // (or pointers to them) be treated as though they were declared 6427 // as __strong. 6428 if (GCAttrs == Qualifiers::GCNone) { 6429 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 6430 return Qualifiers::Strong; 6431 else if (Ty->isPointerType()) 6432 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 6433 } else { 6434 // It's not valid to set GC attributes on anything that isn't a 6435 // pointer. 6436#ifndef NDEBUG 6437 QualType CT = Ty->getCanonicalTypeInternal(); 6438 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 6439 CT = AT->getElementType(); 6440 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 6441#endif 6442 } 6443 return GCAttrs; 6444} 6445 6446//===----------------------------------------------------------------------===// 6447// Type Compatibility Testing 6448//===----------------------------------------------------------------------===// 6449 6450/// areCompatVectorTypes - Return true if the two specified vector types are 6451/// compatible. 6452static bool areCompatVectorTypes(const VectorType *LHS, 6453 const VectorType *RHS) { 6454 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 6455 return LHS->getElementType() == RHS->getElementType() && 6456 LHS->getNumElements() == RHS->getNumElements(); 6457} 6458 6459bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 6460 QualType SecondVec) { 6461 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 6462 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 6463 6464 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 6465 return true; 6466 6467 // Treat Neon vector types and most AltiVec vector types as if they are the 6468 // equivalent GCC vector types. 6469 const VectorType *First = FirstVec->getAs<VectorType>(); 6470 const VectorType *Second = SecondVec->getAs<VectorType>(); 6471 if (First->getNumElements() == Second->getNumElements() && 6472 hasSameType(First->getElementType(), Second->getElementType()) && 6473 First->getVectorKind() != VectorType::AltiVecPixel && 6474 First->getVectorKind() != VectorType::AltiVecBool && 6475 Second->getVectorKind() != VectorType::AltiVecPixel && 6476 Second->getVectorKind() != VectorType::AltiVecBool) 6477 return true; 6478 6479 return false; 6480} 6481 6482//===----------------------------------------------------------------------===// 6483// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 6484//===----------------------------------------------------------------------===// 6485 6486/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 6487/// inheritance hierarchy of 'rProto'. 6488bool 6489ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 6490 ObjCProtocolDecl *rProto) const { 6491 if (declaresSameEntity(lProto, rProto)) 6492 return true; 6493 for (auto *PI : rProto->protocols()) 6494 if (ProtocolCompatibleWithProtocol(lProto, PI)) 6495 return true; 6496 return false; 6497} 6498 6499/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and 6500/// Class<pr1, ...>. 6501bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 6502 QualType rhs) { 6503 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 6504 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 6505 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 6506 6507 for (auto *lhsProto : lhsQID->quals()) { 6508 bool match = false; 6509 for (auto *rhsProto : rhsOPT->quals()) { 6510 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 6511 match = true; 6512 break; 6513 } 6514 } 6515 if (!match) 6516 return false; 6517 } 6518 return true; 6519} 6520 6521/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 6522/// ObjCQualifiedIDType. 6523bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 6524 bool compare) { 6525 // Allow id<P..> and an 'id' or void* type in all cases. 6526 if (lhs->isVoidPointerType() || 6527 lhs->isObjCIdType() || lhs->isObjCClassType()) 6528 return true; 6529 else if (rhs->isVoidPointerType() || 6530 rhs->isObjCIdType() || rhs->isObjCClassType()) 6531 return true; 6532 6533 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 6534 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 6535 6536 if (!rhsOPT) return false; 6537 6538 if (rhsOPT->qual_empty()) { 6539 // If the RHS is a unqualified interface pointer "NSString*", 6540 // make sure we check the class hierarchy. 6541 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 6542 for (auto *I : lhsQID->quals()) { 6543 // when comparing an id<P> on lhs with a static type on rhs, 6544 // see if static class implements all of id's protocols, directly or 6545 // through its super class and categories. 6546 if (!rhsID->ClassImplementsProtocol(I, true)) 6547 return false; 6548 } 6549 } 6550 // If there are no qualifiers and no interface, we have an 'id'. 6551 return true; 6552 } 6553 // Both the right and left sides have qualifiers. 6554 for (auto *lhsProto : lhsQID->quals()) { 6555 bool match = false; 6556 6557 // when comparing an id<P> on lhs with a static type on rhs, 6558 // see if static class implements all of id's protocols, directly or 6559 // through its super class and categories. 6560 for (auto *rhsProto : rhsOPT->quals()) { 6561 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6562 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6563 match = true; 6564 break; 6565 } 6566 } 6567 // If the RHS is a qualified interface pointer "NSString<P>*", 6568 // make sure we check the class hierarchy. 6569 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 6570 for (auto *I : lhsQID->quals()) { 6571 // when comparing an id<P> on lhs with a static type on rhs, 6572 // see if static class implements all of id's protocols, directly or 6573 // through its super class and categories. 6574 if (rhsID->ClassImplementsProtocol(I, true)) { 6575 match = true; 6576 break; 6577 } 6578 } 6579 } 6580 if (!match) 6581 return false; 6582 } 6583 6584 return true; 6585 } 6586 6587 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 6588 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 6589 6590 if (const ObjCObjectPointerType *lhsOPT = 6591 lhs->getAsObjCInterfacePointerType()) { 6592 // If both the right and left sides have qualifiers. 6593 for (auto *lhsProto : lhsOPT->quals()) { 6594 bool match = false; 6595 6596 // when comparing an id<P> on rhs with a static type on lhs, 6597 // see if static class implements all of id's protocols, directly or 6598 // through its super class and categories. 6599 // First, lhs protocols in the qualifier list must be found, direct 6600 // or indirect in rhs's qualifier list or it is a mismatch. 6601 for (auto *rhsProto : rhsQID->quals()) { 6602 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6603 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6604 match = true; 6605 break; 6606 } 6607 } 6608 if (!match) 6609 return false; 6610 } 6611 6612 // Static class's protocols, or its super class or category protocols 6613 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 6614 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 6615 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 6616 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 6617 // This is rather dubious but matches gcc's behavior. If lhs has 6618 // no type qualifier and its class has no static protocol(s) 6619 // assume that it is mismatch. 6620 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 6621 return false; 6622 for (auto *lhsProto : LHSInheritedProtocols) { 6623 bool match = false; 6624 for (auto *rhsProto : rhsQID->quals()) { 6625 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 6626 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 6627 match = true; 6628 break; 6629 } 6630 } 6631 if (!match) 6632 return false; 6633 } 6634 } 6635 return true; 6636 } 6637 return false; 6638} 6639 6640/// canAssignObjCInterfaces - Return true if the two interface types are 6641/// compatible for assignment from RHS to LHS. This handles validation of any 6642/// protocol qualifiers on the LHS or RHS. 6643/// 6644bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 6645 const ObjCObjectPointerType *RHSOPT) { 6646 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 6647 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 6648 6649 // If either type represents the built-in 'id' or 'Class' types, return true. 6650 if (LHS->isObjCUnqualifiedIdOrClass() || 6651 RHS->isObjCUnqualifiedIdOrClass()) 6652 return true; 6653 6654 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 6655 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 6656 QualType(RHSOPT,0), 6657 false); 6658 6659 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 6660 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 6661 QualType(RHSOPT,0)); 6662 6663 // If we have 2 user-defined types, fall into that path. 6664 if (LHS->getInterface() && RHS->getInterface()) 6665 return canAssignObjCInterfaces(LHS, RHS); 6666 6667 return false; 6668} 6669 6670/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 6671/// for providing type-safety for objective-c pointers used to pass/return 6672/// arguments in block literals. When passed as arguments, passing 'A*' where 6673/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 6674/// not OK. For the return type, the opposite is not OK. 6675bool ASTContext::canAssignObjCInterfacesInBlockPointer( 6676 const ObjCObjectPointerType *LHSOPT, 6677 const ObjCObjectPointerType *RHSOPT, 6678 bool BlockReturnType) { 6679 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 6680 return true; 6681 6682 if (LHSOPT->isObjCBuiltinType()) { 6683 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 6684 } 6685 6686 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 6687 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 6688 QualType(RHSOPT,0), 6689 false); 6690 6691 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 6692 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 6693 if (LHS && RHS) { // We have 2 user-defined types. 6694 if (LHS != RHS) { 6695 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 6696 return BlockReturnType; 6697 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 6698 return !BlockReturnType; 6699 } 6700 else 6701 return true; 6702 } 6703 return false; 6704} 6705 6706/// getIntersectionOfProtocols - This routine finds the intersection of set 6707/// of protocols inherited from two distinct objective-c pointer objects. 6708/// It is used to build composite qualifier list of the composite type of 6709/// the conditional expression involving two objective-c pointer objects. 6710static 6711void getIntersectionOfProtocols(ASTContext &Context, 6712 const ObjCObjectPointerType *LHSOPT, 6713 const ObjCObjectPointerType *RHSOPT, 6714 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 6715 6716 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 6717 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 6718 assert(LHS->getInterface() && "LHS must have an interface base"); 6719 assert(RHS->getInterface() && "RHS must have an interface base"); 6720 6721 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 6722 unsigned LHSNumProtocols = LHS->getNumProtocols(); 6723 if (LHSNumProtocols > 0) 6724 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 6725 else { 6726 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 6727 Context.CollectInheritedProtocols(LHS->getInterface(), 6728 LHSInheritedProtocols); 6729 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 6730 LHSInheritedProtocols.end()); 6731 } 6732 6733 unsigned RHSNumProtocols = RHS->getNumProtocols(); 6734 if (RHSNumProtocols > 0) { 6735 ObjCProtocolDecl **RHSProtocols = 6736 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 6737 for (unsigned i = 0; i < RHSNumProtocols; ++i) 6738 if (InheritedProtocolSet.count(RHSProtocols[i])) 6739 IntersectionOfProtocols.push_back(RHSProtocols[i]); 6740 } else { 6741 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 6742 Context.CollectInheritedProtocols(RHS->getInterface(), 6743 RHSInheritedProtocols); 6744 for (ObjCProtocolDecl *ProtDecl : RHSInheritedProtocols) 6745 if (InheritedProtocolSet.count(ProtDecl)) 6746 IntersectionOfProtocols.push_back(ProtDecl); 6747 } 6748} 6749 6750/// areCommonBaseCompatible - Returns common base class of the two classes if 6751/// one found. Note that this is O'2 algorithm. But it will be called as the 6752/// last type comparison in a ?-exp of ObjC pointer types before a 6753/// warning is issued. So, its invokation is extremely rare. 6754QualType ASTContext::areCommonBaseCompatible( 6755 const ObjCObjectPointerType *Lptr, 6756 const ObjCObjectPointerType *Rptr) { 6757 const ObjCObjectType *LHS = Lptr->getObjectType(); 6758 const ObjCObjectType *RHS = Rptr->getObjectType(); 6759 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 6760 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 6761 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl))) 6762 return QualType(); 6763 6764 do { 6765 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 6766 if (canAssignObjCInterfaces(LHS, RHS)) { 6767 SmallVector<ObjCProtocolDecl *, 8> Protocols; 6768 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 6769 6770 QualType Result = QualType(LHS, 0); 6771 if (!Protocols.empty()) 6772 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 6773 Result = getObjCObjectPointerType(Result); 6774 return Result; 6775 } 6776 } while ((LDecl = LDecl->getSuperClass())); 6777 6778 return QualType(); 6779} 6780 6781bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 6782 const ObjCObjectType *RHS) { 6783 assert(LHS->getInterface() && "LHS is not an interface type"); 6784 assert(RHS->getInterface() && "RHS is not an interface type"); 6785 6786 // Verify that the base decls are compatible: the RHS must be a subclass of 6787 // the LHS. 6788 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 6789 return false; 6790 6791 // RHS must have a superset of the protocols in the LHS. If the LHS is not 6792 // protocol qualified at all, then we are good. 6793 if (LHS->getNumProtocols() == 0) 6794 return true; 6795 6796 // Okay, we know the LHS has protocol qualifiers. But RHS may or may not. 6797 // More detailed analysis is required. 6798 // OK, if LHS is same or a superclass of RHS *and* 6799 // this LHS, or as RHS's super class is assignment compatible with LHS. 6800 bool IsSuperClass = 6801 LHS->getInterface()->isSuperClassOf(RHS->getInterface()); 6802 if (IsSuperClass) { 6803 // OK if conversion of LHS to SuperClass results in narrowing of types 6804 // ; i.e., SuperClass may implement at least one of the protocols 6805 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 6806 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 6807 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 6808 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 6809 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's 6810 // qualifiers. 6811 for (auto *RHSPI : RHS->quals()) 6812 SuperClassInheritedProtocols.insert(RHSPI->getCanonicalDecl()); 6813 // If there is no protocols associated with RHS, it is not a match. 6814 if (SuperClassInheritedProtocols.empty()) 6815 return false; 6816 6817 for (const auto *LHSProto : LHS->quals()) { 6818 bool SuperImplementsProtocol = false; 6819 for (auto *SuperClassProto : SuperClassInheritedProtocols) 6820 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 6821 SuperImplementsProtocol = true; 6822 break; 6823 } 6824 if (!SuperImplementsProtocol) 6825 return false; 6826 } 6827 return true; 6828 } 6829 return false; 6830} 6831 6832bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 6833 // get the "pointed to" types 6834 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 6835 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 6836 6837 if (!LHSOPT || !RHSOPT) 6838 return false; 6839 6840 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 6841 canAssignObjCInterfaces(RHSOPT, LHSOPT); 6842} 6843 6844bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 6845 return canAssignObjCInterfaces( 6846 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 6847 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 6848} 6849 6850/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 6851/// both shall have the identically qualified version of a compatible type. 6852/// C99 6.2.7p1: Two types have compatible types if their types are the 6853/// same. See 6.7.[2,3,5] for additional rules. 6854bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 6855 bool CompareUnqualified) { 6856 if (getLangOpts().CPlusPlus) 6857 return hasSameType(LHS, RHS); 6858 6859 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 6860} 6861 6862bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 6863 return typesAreCompatible(LHS, RHS); 6864} 6865 6866bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 6867 return !mergeTypes(LHS, RHS, true).isNull(); 6868} 6869 6870/// mergeTransparentUnionType - if T is a transparent union type and a member 6871/// of T is compatible with SubType, return the merged type, else return 6872/// QualType() 6873QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 6874 bool OfBlockPointer, 6875 bool Unqualified) { 6876 if (const RecordType *UT = T->getAsUnionType()) { 6877 RecordDecl *UD = UT->getDecl(); 6878 if (UD->hasAttr<TransparentUnionAttr>()) { 6879 for (const auto *I : UD->fields()) { 6880 QualType ET = I->getType().getUnqualifiedType(); 6881 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 6882 if (!MT.isNull()) 6883 return MT; 6884 } 6885 } 6886 } 6887 6888 return QualType(); 6889} 6890 6891/// mergeFunctionParameterTypes - merge two types which appear as function 6892/// parameter types 6893QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs, 6894 bool OfBlockPointer, 6895 bool Unqualified) { 6896 // GNU extension: two types are compatible if they appear as a function 6897 // argument, one of the types is a transparent union type and the other 6898 // type is compatible with a union member 6899 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 6900 Unqualified); 6901 if (!lmerge.isNull()) 6902 return lmerge; 6903 6904 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 6905 Unqualified); 6906 if (!rmerge.isNull()) 6907 return rmerge; 6908 6909 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 6910} 6911 6912QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 6913 bool OfBlockPointer, 6914 bool Unqualified) { 6915 const FunctionType *lbase = lhs->getAs<FunctionType>(); 6916 const FunctionType *rbase = rhs->getAs<FunctionType>(); 6917 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 6918 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 6919 bool allLTypes = true; 6920 bool allRTypes = true; 6921 6922 // Check return type 6923 QualType retType; 6924 if (OfBlockPointer) { 6925 QualType RHS = rbase->getReturnType(); 6926 QualType LHS = lbase->getReturnType(); 6927 bool UnqualifiedResult = Unqualified; 6928 if (!UnqualifiedResult) 6929 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 6930 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 6931 } 6932 else 6933 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false, 6934 Unqualified); 6935 if (retType.isNull()) return QualType(); 6936 6937 if (Unqualified) 6938 retType = retType.getUnqualifiedType(); 6939 6940 CanQualType LRetType = getCanonicalType(lbase->getReturnType()); 6941 CanQualType RRetType = getCanonicalType(rbase->getReturnType()); 6942 if (Unqualified) { 6943 LRetType = LRetType.getUnqualifiedType(); 6944 RRetType = RRetType.getUnqualifiedType(); 6945 } 6946 6947 if (getCanonicalType(retType) != LRetType) 6948 allLTypes = false; 6949 if (getCanonicalType(retType) != RRetType) 6950 allRTypes = false; 6951 6952 // FIXME: double check this 6953 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 6954 // rbase->getRegParmAttr() != 0 && 6955 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 6956 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 6957 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 6958 6959 // Compatible functions must have compatible calling conventions 6960 if (lbaseInfo.getCC() != rbaseInfo.getCC()) 6961 return QualType(); 6962 6963 // Regparm is part of the calling convention. 6964 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 6965 return QualType(); 6966 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 6967 return QualType(); 6968 6969 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 6970 return QualType(); 6971 6972 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 6973 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 6974 6975 if (lbaseInfo.getNoReturn() != NoReturn) 6976 allLTypes = false; 6977 if (rbaseInfo.getNoReturn() != NoReturn) 6978 allRTypes = false; 6979 6980 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 6981 6982 if (lproto && rproto) { // two C99 style function prototypes 6983 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 6984 "C++ shouldn't be here"); 6985 // Compatible functions must have the same number of parameters 6986 if (lproto->getNumParams() != rproto->getNumParams()) 6987 return QualType(); 6988 6989 // Variadic and non-variadic functions aren't compatible 6990 if (lproto->isVariadic() != rproto->isVariadic()) 6991 return QualType(); 6992 6993 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 6994 return QualType(); 6995 6996 if (LangOpts.ObjCAutoRefCount && 6997 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto)) 6998 return QualType(); 6999 7000 // Check parameter type compatibility 7001 SmallVector<QualType, 10> types; 7002 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) { 7003 QualType lParamType = lproto->getParamType(i).getUnqualifiedType(); 7004 QualType rParamType = rproto->getParamType(i).getUnqualifiedType(); 7005 QualType paramType = mergeFunctionParameterTypes( 7006 lParamType, rParamType, OfBlockPointer, Unqualified); 7007 if (paramType.isNull()) 7008 return QualType(); 7009 7010 if (Unqualified) 7011 paramType = paramType.getUnqualifiedType(); 7012 7013 types.push_back(paramType); 7014 if (Unqualified) { 7015 lParamType = lParamType.getUnqualifiedType(); 7016 rParamType = rParamType.getUnqualifiedType(); 7017 } 7018 7019 if (getCanonicalType(paramType) != getCanonicalType(lParamType)) 7020 allLTypes = false; 7021 if (getCanonicalType(paramType) != getCanonicalType(rParamType)) 7022 allRTypes = false; 7023 } 7024 7025 if (allLTypes) return lhs; 7026 if (allRTypes) return rhs; 7027 7028 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 7029 EPI.ExtInfo = einfo; 7030 return getFunctionType(retType, types, EPI); 7031 } 7032 7033 if (lproto) allRTypes = false; 7034 if (rproto) allLTypes = false; 7035 7036 const FunctionProtoType *proto = lproto ? lproto : rproto; 7037 if (proto) { 7038 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 7039 if (proto->isVariadic()) return QualType(); 7040 // Check that the types are compatible with the types that 7041 // would result from default argument promotions (C99 6.7.5.3p15). 7042 // The only types actually affected are promotable integer 7043 // types and floats, which would be passed as a different 7044 // type depending on whether the prototype is visible. 7045 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) { 7046 QualType paramTy = proto->getParamType(i); 7047 7048 // Look at the converted type of enum types, since that is the type used 7049 // to pass enum values. 7050 if (const EnumType *Enum = paramTy->getAs<EnumType>()) { 7051 paramTy = Enum->getDecl()->getIntegerType(); 7052 if (paramTy.isNull()) 7053 return QualType(); 7054 } 7055 7056 if (paramTy->isPromotableIntegerType() || 7057 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy) 7058 return QualType(); 7059 } 7060 7061 if (allLTypes) return lhs; 7062 if (allRTypes) return rhs; 7063 7064 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 7065 EPI.ExtInfo = einfo; 7066 return getFunctionType(retType, proto->getParamTypes(), EPI); 7067 } 7068 7069 if (allLTypes) return lhs; 7070 if (allRTypes) return rhs; 7071 return getFunctionNoProtoType(retType, einfo); 7072} 7073 7074/// Given that we have an enum type and a non-enum type, try to merge them. 7075static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET, 7076 QualType other, bool isBlockReturnType) { 7077 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 7078 // a signed integer type, or an unsigned integer type. 7079 // Compatibility is based on the underlying type, not the promotion 7080 // type. 7081 QualType underlyingType = ET->getDecl()->getIntegerType(); 7082 if (underlyingType.isNull()) return QualType(); 7083 if (Context.hasSameType(underlyingType, other)) 7084 return other; 7085 7086 // In block return types, we're more permissive and accept any 7087 // integral type of the same size. 7088 if (isBlockReturnType && other->isIntegerType() && 7089 Context.getTypeSize(underlyingType) == Context.getTypeSize(other)) 7090 return other; 7091 7092 return QualType(); 7093} 7094 7095QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 7096 bool OfBlockPointer, 7097 bool Unqualified, bool BlockReturnType) { 7098 // C++ [expr]: If an expression initially has the type "reference to T", the 7099 // type is adjusted to "T" prior to any further analysis, the expression 7100 // designates the object or function denoted by the reference, and the 7101 // expression is an lvalue unless the reference is an rvalue reference and 7102 // the expression is a function call (possibly inside parentheses). 7103 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 7104 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 7105 7106 if (Unqualified) { 7107 LHS = LHS.getUnqualifiedType(); 7108 RHS = RHS.getUnqualifiedType(); 7109 } 7110 7111 QualType LHSCan = getCanonicalType(LHS), 7112 RHSCan = getCanonicalType(RHS); 7113 7114 // If two types are identical, they are compatible. 7115 if (LHSCan == RHSCan) 7116 return LHS; 7117 7118 // If the qualifiers are different, the types aren't compatible... mostly. 7119 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 7120 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 7121 if (LQuals != RQuals) { 7122 // If any of these qualifiers are different, we have a type 7123 // mismatch. 7124 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 7125 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 7126 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 7127 return QualType(); 7128 7129 // Exactly one GC qualifier difference is allowed: __strong is 7130 // okay if the other type has no GC qualifier but is an Objective 7131 // C object pointer (i.e. implicitly strong by default). We fix 7132 // this by pretending that the unqualified type was actually 7133 // qualified __strong. 7134 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 7135 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 7136 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 7137 7138 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 7139 return QualType(); 7140 7141 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 7142 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 7143 } 7144 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 7145 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 7146 } 7147 return QualType(); 7148 } 7149 7150 // Okay, qualifiers are equal. 7151 7152 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 7153 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 7154 7155 // We want to consider the two function types to be the same for these 7156 // comparisons, just force one to the other. 7157 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 7158 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 7159 7160 // Same as above for arrays 7161 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 7162 LHSClass = Type::ConstantArray; 7163 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 7164 RHSClass = Type::ConstantArray; 7165 7166 // ObjCInterfaces are just specialized ObjCObjects. 7167 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 7168 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 7169 7170 // Canonicalize ExtVector -> Vector. 7171 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 7172 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 7173 7174 // If the canonical type classes don't match. 7175 if (LHSClass != RHSClass) { 7176 // Note that we only have special rules for turning block enum 7177 // returns into block int returns, not vice-versa. 7178 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 7179 return mergeEnumWithInteger(*this, ETy, RHS, false); 7180 } 7181 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 7182 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType); 7183 } 7184 // allow block pointer type to match an 'id' type. 7185 if (OfBlockPointer && !BlockReturnType) { 7186 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 7187 return LHS; 7188 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 7189 return RHS; 7190 } 7191 7192 return QualType(); 7193 } 7194 7195 // The canonical type classes match. 7196 switch (LHSClass) { 7197#define TYPE(Class, Base) 7198#define ABSTRACT_TYPE(Class, Base) 7199#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 7200#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 7201#define DEPENDENT_TYPE(Class, Base) case Type::Class: 7202#include "clang/AST/TypeNodes.def" 7203 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 7204 7205 case Type::Auto: 7206 case Type::LValueReference: 7207 case Type::RValueReference: 7208 case Type::MemberPointer: 7209 llvm_unreachable("C++ should never be in mergeTypes"); 7210 7211 case Type::ObjCInterface: 7212 case Type::IncompleteArray: 7213 case Type::VariableArray: 7214 case Type::FunctionProto: 7215 case Type::ExtVector: 7216 llvm_unreachable("Types are eliminated above"); 7217 7218 case Type::Pointer: 7219 { 7220 // Merge two pointer types, while trying to preserve typedef info 7221 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 7222 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 7223 if (Unqualified) { 7224 LHSPointee = LHSPointee.getUnqualifiedType(); 7225 RHSPointee = RHSPointee.getUnqualifiedType(); 7226 } 7227 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 7228 Unqualified); 7229 if (ResultType.isNull()) return QualType(); 7230 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 7231 return LHS; 7232 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 7233 return RHS; 7234 return getPointerType(ResultType); 7235 } 7236 case Type::BlockPointer: 7237 { 7238 // Merge two block pointer types, while trying to preserve typedef info 7239 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 7240 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 7241 if (Unqualified) { 7242 LHSPointee = LHSPointee.getUnqualifiedType(); 7243 RHSPointee = RHSPointee.getUnqualifiedType(); 7244 } 7245 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 7246 Unqualified); 7247 if (ResultType.isNull()) return QualType(); 7248 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 7249 return LHS; 7250 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 7251 return RHS; 7252 return getBlockPointerType(ResultType); 7253 } 7254 case Type::Atomic: 7255 { 7256 // Merge two pointer types, while trying to preserve typedef info 7257 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 7258 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 7259 if (Unqualified) { 7260 LHSValue = LHSValue.getUnqualifiedType(); 7261 RHSValue = RHSValue.getUnqualifiedType(); 7262 } 7263 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 7264 Unqualified); 7265 if (ResultType.isNull()) return QualType(); 7266 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 7267 return LHS; 7268 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 7269 return RHS; 7270 return getAtomicType(ResultType); 7271 } 7272 case Type::ConstantArray: 7273 { 7274 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 7275 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 7276 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 7277 return QualType(); 7278 7279 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 7280 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 7281 if (Unqualified) { 7282 LHSElem = LHSElem.getUnqualifiedType(); 7283 RHSElem = RHSElem.getUnqualifiedType(); 7284 } 7285 7286 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 7287 if (ResultType.isNull()) return QualType(); 7288 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 7289 return LHS; 7290 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 7291 return RHS; 7292 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 7293 ArrayType::ArraySizeModifier(), 0); 7294 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 7295 ArrayType::ArraySizeModifier(), 0); 7296 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 7297 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 7298 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 7299 return LHS; 7300 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 7301 return RHS; 7302 if (LVAT) { 7303 // FIXME: This isn't correct! But tricky to implement because 7304 // the array's size has to be the size of LHS, but the type 7305 // has to be different. 7306 return LHS; 7307 } 7308 if (RVAT) { 7309 // FIXME: This isn't correct! But tricky to implement because 7310 // the array's size has to be the size of RHS, but the type 7311 // has to be different. 7312 return RHS; 7313 } 7314 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 7315 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 7316 return getIncompleteArrayType(ResultType, 7317 ArrayType::ArraySizeModifier(), 0); 7318 } 7319 case Type::FunctionNoProto: 7320 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 7321 case Type::Record: 7322 case Type::Enum: 7323 return QualType(); 7324 case Type::Builtin: 7325 // Only exactly equal builtin types are compatible, which is tested above. 7326 return QualType(); 7327 case Type::Complex: 7328 // Distinct complex types are incompatible. 7329 return QualType(); 7330 case Type::Vector: 7331 // FIXME: The merged type should be an ExtVector! 7332 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 7333 RHSCan->getAs<VectorType>())) 7334 return LHS; 7335 return QualType(); 7336 case Type::ObjCObject: { 7337 // Check if the types are assignment compatible. 7338 // FIXME: This should be type compatibility, e.g. whether 7339 // "LHS x; RHS x;" at global scope is legal. 7340 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 7341 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 7342 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 7343 return LHS; 7344 7345 return QualType(); 7346 } 7347 case Type::ObjCObjectPointer: { 7348 if (OfBlockPointer) { 7349 if (canAssignObjCInterfacesInBlockPointer( 7350 LHS->getAs<ObjCObjectPointerType>(), 7351 RHS->getAs<ObjCObjectPointerType>(), 7352 BlockReturnType)) 7353 return LHS; 7354 return QualType(); 7355 } 7356 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 7357 RHS->getAs<ObjCObjectPointerType>())) 7358 return LHS; 7359 7360 return QualType(); 7361 } 7362 } 7363 7364 llvm_unreachable("Invalid Type::Class!"); 7365} 7366 7367bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs( 7368 const FunctionProtoType *FromFunctionType, 7369 const FunctionProtoType *ToFunctionType) { 7370 if (FromFunctionType->hasAnyConsumedParams() != 7371 ToFunctionType->hasAnyConsumedParams()) 7372 return false; 7373 FunctionProtoType::ExtProtoInfo FromEPI = 7374 FromFunctionType->getExtProtoInfo(); 7375 FunctionProtoType::ExtProtoInfo ToEPI = 7376 ToFunctionType->getExtProtoInfo(); 7377 if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters) 7378 for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) { 7379 if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i]) 7380 return false; 7381 } 7382 return true; 7383} 7384 7385/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 7386/// 'RHS' attributes and returns the merged version; including for function 7387/// return types. 7388QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 7389 QualType LHSCan = getCanonicalType(LHS), 7390 RHSCan = getCanonicalType(RHS); 7391 // If two types are identical, they are compatible. 7392 if (LHSCan == RHSCan) 7393 return LHS; 7394 if (RHSCan->isFunctionType()) { 7395 if (!LHSCan->isFunctionType()) 7396 return QualType(); 7397 QualType OldReturnType = 7398 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType(); 7399 QualType NewReturnType = 7400 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType(); 7401 QualType ResReturnType = 7402 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 7403 if (ResReturnType.isNull()) 7404 return QualType(); 7405 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 7406 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 7407 // In either case, use OldReturnType to build the new function type. 7408 const FunctionType *F = LHS->getAs<FunctionType>(); 7409 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 7410 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7411 EPI.ExtInfo = getFunctionExtInfo(LHS); 7412 QualType ResultType = 7413 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI); 7414 return ResultType; 7415 } 7416 } 7417 return QualType(); 7418 } 7419 7420 // If the qualifiers are different, the types can still be merged. 7421 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 7422 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 7423 if (LQuals != RQuals) { 7424 // If any of these qualifiers are different, we have a type mismatch. 7425 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 7426 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 7427 return QualType(); 7428 7429 // Exactly one GC qualifier difference is allowed: __strong is 7430 // okay if the other type has no GC qualifier but is an Objective 7431 // C object pointer (i.e. implicitly strong by default). We fix 7432 // this by pretending that the unqualified type was actually 7433 // qualified __strong. 7434 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 7435 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 7436 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 7437 7438 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 7439 return QualType(); 7440 7441 if (GC_L == Qualifiers::Strong) 7442 return LHS; 7443 if (GC_R == Qualifiers::Strong) 7444 return RHS; 7445 return QualType(); 7446 } 7447 7448 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 7449 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 7450 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 7451 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 7452 if (ResQT == LHSBaseQT) 7453 return LHS; 7454 if (ResQT == RHSBaseQT) 7455 return RHS; 7456 } 7457 return QualType(); 7458} 7459 7460//===----------------------------------------------------------------------===// 7461// Integer Predicates 7462//===----------------------------------------------------------------------===// 7463 7464unsigned ASTContext::getIntWidth(QualType T) const { 7465 if (const EnumType *ET = T->getAs<EnumType>()) 7466 T = ET->getDecl()->getIntegerType(); 7467 if (T->isBooleanType()) 7468 return 1; 7469 // For builtin types, just use the standard type sizing method 7470 return (unsigned)getTypeSize(T); 7471} 7472 7473QualType ASTContext::getCorrespondingUnsignedType(QualType T) const { 7474 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 7475 7476 // Turn <4 x signed int> -> <4 x unsigned int> 7477 if (const VectorType *VTy = T->getAs<VectorType>()) 7478 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 7479 VTy->getNumElements(), VTy->getVectorKind()); 7480 7481 // For enums, we return the unsigned version of the base type. 7482 if (const EnumType *ETy = T->getAs<EnumType>()) 7483 T = ETy->getDecl()->getIntegerType(); 7484 7485 const BuiltinType *BTy = T->getAs<BuiltinType>(); 7486 assert(BTy && "Unexpected signed integer type"); 7487 switch (BTy->getKind()) { 7488 case BuiltinType::Char_S: 7489 case BuiltinType::SChar: 7490 return UnsignedCharTy; 7491 case BuiltinType::Short: 7492 return UnsignedShortTy; 7493 case BuiltinType::Int: 7494 return UnsignedIntTy; 7495 case BuiltinType::Long: 7496 return UnsignedLongTy; 7497 case BuiltinType::LongLong: 7498 return UnsignedLongLongTy; 7499 case BuiltinType::Int128: 7500 return UnsignedInt128Ty; 7501 default: 7502 llvm_unreachable("Unexpected signed integer type"); 7503 } 7504} 7505 7506ASTMutationListener::~ASTMutationListener() { } 7507 7508void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD, 7509 QualType ReturnType) {} 7510 7511//===----------------------------------------------------------------------===// 7512// Builtin Type Computation 7513//===----------------------------------------------------------------------===// 7514 7515/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 7516/// pointer over the consumed characters. This returns the resultant type. If 7517/// AllowTypeModifiers is false then modifier like * are not parsed, just basic 7518/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 7519/// a vector of "i*". 7520/// 7521/// RequiresICE is filled in on return to indicate whether the value is required 7522/// to be an Integer Constant Expression. 7523static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 7524 ASTContext::GetBuiltinTypeError &Error, 7525 bool &RequiresICE, 7526 bool AllowTypeModifiers) { 7527 // Modifiers. 7528 int HowLong = 0; 7529 bool Signed = false, Unsigned = false; 7530 RequiresICE = false; 7531 7532 // Read the prefixed modifiers first. 7533 bool Done = false; 7534 while (!Done) { 7535 switch (*Str++) { 7536 default: Done = true; --Str; break; 7537 case 'I': 7538 RequiresICE = true; 7539 break; 7540 case 'S': 7541 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 7542 assert(!Signed && "Can't use 'S' modifier multiple times!"); 7543 Signed = true; 7544 break; 7545 case 'U': 7546 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 7547 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 7548 Unsigned = true; 7549 break; 7550 case 'L': 7551 assert(HowLong <= 2 && "Can't have LLLL modifier"); 7552 ++HowLong; 7553 break; 7554 case 'W': 7555 // This modifier represents int64 type. 7556 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!"); 7557 switch (Context.getTargetInfo().getInt64Type()) { 7558 default: 7559 llvm_unreachable("Unexpected integer type"); 7560 case TargetInfo::SignedLong: 7561 HowLong = 1; 7562 break; 7563 case TargetInfo::SignedLongLong: 7564 HowLong = 2; 7565 break; 7566 } 7567 } 7568 } 7569 7570 QualType Type; 7571 7572 // Read the base type. 7573 switch (*Str++) { 7574 default: llvm_unreachable("Unknown builtin type letter!"); 7575 case 'v': 7576 assert(HowLong == 0 && !Signed && !Unsigned && 7577 "Bad modifiers used with 'v'!"); 7578 Type = Context.VoidTy; 7579 break; 7580 case 'h': 7581 assert(HowLong == 0 && !Signed && !Unsigned && 7582 "Bad modifiers used with 'f'!"); 7583 Type = Context.HalfTy; 7584 break; 7585 case 'f': 7586 assert(HowLong == 0 && !Signed && !Unsigned && 7587 "Bad modifiers used with 'f'!"); 7588 Type = Context.FloatTy; 7589 break; 7590 case 'd': 7591 assert(HowLong < 2 && !Signed && !Unsigned && 7592 "Bad modifiers used with 'd'!"); 7593 if (HowLong) 7594 Type = Context.LongDoubleTy; 7595 else 7596 Type = Context.DoubleTy; 7597 break; 7598 case 's': 7599 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 7600 if (Unsigned) 7601 Type = Context.UnsignedShortTy; 7602 else 7603 Type = Context.ShortTy; 7604 break; 7605 case 'i': 7606 if (HowLong == 3) 7607 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 7608 else if (HowLong == 2) 7609 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 7610 else if (HowLong == 1) 7611 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 7612 else 7613 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 7614 break; 7615 case 'c': 7616 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 7617 if (Signed) 7618 Type = Context.SignedCharTy; 7619 else if (Unsigned) 7620 Type = Context.UnsignedCharTy; 7621 else 7622 Type = Context.CharTy; 7623 break; 7624 case 'b': // boolean 7625 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 7626 Type = Context.BoolTy; 7627 break; 7628 case 'z': // size_t. 7629 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 7630 Type = Context.getSizeType(); 7631 break; 7632 case 'F': 7633 Type = Context.getCFConstantStringType(); 7634 break; 7635 case 'G': 7636 Type = Context.getObjCIdType(); 7637 break; 7638 case 'H': 7639 Type = Context.getObjCSelType(); 7640 break; 7641 case 'M': 7642 Type = Context.getObjCSuperType(); 7643 break; 7644 case 'a': 7645 Type = Context.getBuiltinVaListType(); 7646 assert(!Type.isNull() && "builtin va list type not initialized!"); 7647 break; 7648 case 'A': 7649 // This is a "reference" to a va_list; however, what exactly 7650 // this means depends on how va_list is defined. There are two 7651 // different kinds of va_list: ones passed by value, and ones 7652 // passed by reference. An example of a by-value va_list is 7653 // x86, where va_list is a char*. An example of by-ref va_list 7654 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 7655 // we want this argument to be a char*&; for x86-64, we want 7656 // it to be a __va_list_tag*. 7657 Type = Context.getBuiltinVaListType(); 7658 assert(!Type.isNull() && "builtin va list type not initialized!"); 7659 if (Type->isArrayType()) 7660 Type = Context.getArrayDecayedType(Type); 7661 else 7662 Type = Context.getLValueReferenceType(Type); 7663 break; 7664 case 'V': { 7665 char *End; 7666 unsigned NumElements = strtoul(Str, &End, 10); 7667 assert(End != Str && "Missing vector size"); 7668 Str = End; 7669 7670 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 7671 RequiresICE, false); 7672 assert(!RequiresICE && "Can't require vector ICE"); 7673 7674 // TODO: No way to make AltiVec vectors in builtins yet. 7675 Type = Context.getVectorType(ElementType, NumElements, 7676 VectorType::GenericVector); 7677 break; 7678 } 7679 case 'E': { 7680 char *End; 7681 7682 unsigned NumElements = strtoul(Str, &End, 10); 7683 assert(End != Str && "Missing vector size"); 7684 7685 Str = End; 7686 7687 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 7688 false); 7689 Type = Context.getExtVectorType(ElementType, NumElements); 7690 break; 7691 } 7692 case 'X': { 7693 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 7694 false); 7695 assert(!RequiresICE && "Can't require complex ICE"); 7696 Type = Context.getComplexType(ElementType); 7697 break; 7698 } 7699 case 'Y' : { 7700 Type = Context.getPointerDiffType(); 7701 break; 7702 } 7703 case 'P': 7704 Type = Context.getFILEType(); 7705 if (Type.isNull()) { 7706 Error = ASTContext::GE_Missing_stdio; 7707 return QualType(); 7708 } 7709 break; 7710 case 'J': 7711 if (Signed) 7712 Type = Context.getsigjmp_bufType(); 7713 else 7714 Type = Context.getjmp_bufType(); 7715 7716 if (Type.isNull()) { 7717 Error = ASTContext::GE_Missing_setjmp; 7718 return QualType(); 7719 } 7720 break; 7721 case 'K': 7722 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 7723 Type = Context.getucontext_tType(); 7724 7725 if (Type.isNull()) { 7726 Error = ASTContext::GE_Missing_ucontext; 7727 return QualType(); 7728 } 7729 break; 7730 case 'p': 7731 Type = Context.getProcessIDType(); 7732 break; 7733 } 7734 7735 // If there are modifiers and if we're allowed to parse them, go for it. 7736 Done = !AllowTypeModifiers; 7737 while (!Done) { 7738 switch (char c = *Str++) { 7739 default: Done = true; --Str; break; 7740 case '*': 7741 case '&': { 7742 // Both pointers and references can have their pointee types 7743 // qualified with an address space. 7744 char *End; 7745 unsigned AddrSpace = strtoul(Str, &End, 10); 7746 if (End != Str && AddrSpace != 0) { 7747 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 7748 Str = End; 7749 } 7750 if (c == '*') 7751 Type = Context.getPointerType(Type); 7752 else 7753 Type = Context.getLValueReferenceType(Type); 7754 break; 7755 } 7756 // FIXME: There's no way to have a built-in with an rvalue ref arg. 7757 case 'C': 7758 Type = Type.withConst(); 7759 break; 7760 case 'D': 7761 Type = Context.getVolatileType(Type); 7762 break; 7763 case 'R': 7764 Type = Type.withRestrict(); 7765 break; 7766 } 7767 } 7768 7769 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 7770 "Integer constant 'I' type must be an integer"); 7771 7772 return Type; 7773} 7774 7775/// GetBuiltinType - Return the type for the specified builtin. 7776QualType ASTContext::GetBuiltinType(unsigned Id, 7777 GetBuiltinTypeError &Error, 7778 unsigned *IntegerConstantArgs) const { 7779 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 7780 7781 SmallVector<QualType, 8> ArgTypes; 7782 7783 bool RequiresICE = false; 7784 Error = GE_None; 7785 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 7786 RequiresICE, true); 7787 if (Error != GE_None) 7788 return QualType(); 7789 7790 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 7791 7792 while (TypeStr[0] && TypeStr[0] != '.') { 7793 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 7794 if (Error != GE_None) 7795 return QualType(); 7796 7797 // If this argument is required to be an IntegerConstantExpression and the 7798 // caller cares, fill in the bitmask we return. 7799 if (RequiresICE && IntegerConstantArgs) 7800 *IntegerConstantArgs |= 1 << ArgTypes.size(); 7801 7802 // Do array -> pointer decay. The builtin should use the decayed type. 7803 if (Ty->isArrayType()) 7804 Ty = getArrayDecayedType(Ty); 7805 7806 ArgTypes.push_back(Ty); 7807 } 7808 7809 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 7810 "'.' should only occur at end of builtin type list!"); 7811 7812 FunctionType::ExtInfo EI(CC_C); 7813 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 7814 7815 bool Variadic = (TypeStr[0] == '.'); 7816 7817 // We really shouldn't be making a no-proto type here, especially in C++. 7818 if (ArgTypes.empty() && Variadic) 7819 return getFunctionNoProtoType(ResType, EI); 7820 7821 FunctionProtoType::ExtProtoInfo EPI; 7822 EPI.ExtInfo = EI; 7823 EPI.Variadic = Variadic; 7824 7825 return getFunctionType(ResType, ArgTypes, EPI); 7826} 7827 7828static GVALinkage basicGVALinkageForFunction(const ASTContext &Context, 7829 const FunctionDecl *FD) { 7830 if (!FD->isExternallyVisible()) 7831 return GVA_Internal; 7832 7833 GVALinkage External = GVA_StrongExternal; 7834 switch (FD->getTemplateSpecializationKind()) { 7835 case TSK_Undeclared: 7836 case TSK_ExplicitSpecialization: 7837 External = GVA_StrongExternal; 7838 break; 7839 7840 case TSK_ExplicitInstantiationDefinition: 7841 return GVA_StrongODR; 7842 7843 // C++11 [temp.explicit]p10: 7844 // [ Note: The intent is that an inline function that is the subject of 7845 // an explicit instantiation declaration will still be implicitly 7846 // instantiated when used so that the body can be considered for 7847 // inlining, but that no out-of-line copy of the inline function would be 7848 // generated in the translation unit. -- end note ] 7849 case TSK_ExplicitInstantiationDeclaration: 7850 return GVA_AvailableExternally; 7851 7852 case TSK_ImplicitInstantiation: 7853 External = GVA_DiscardableODR; 7854 break; 7855 } 7856 7857 if (!FD->isInlined()) 7858 return External; 7859 7860 if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat && 7861 !FD->hasAttr<DLLExportAttr>()) || 7862 FD->hasAttr<GNUInlineAttr>()) { 7863 // FIXME: This doesn't match gcc's behavior for dllexport inline functions. 7864 7865 // GNU or C99 inline semantics. Determine whether this symbol should be 7866 // externally visible. 7867 if (FD->isInlineDefinitionExternallyVisible()) 7868 return External; 7869 7870 // C99 inline semantics, where the symbol is not externally visible. 7871 return GVA_AvailableExternally; 7872 } 7873 7874 // Functions specified with extern and inline in -fms-compatibility mode 7875 // forcibly get emitted. While the body of the function cannot be later 7876 // replaced, the function definition cannot be discarded.
|