1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTContext interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CharUnits.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExternalASTSource.h"
23 #include "clang/AST/ASTMutationListener.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/Mangle.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/raw_ostream.h"
36 using namespace clang;
38 unsigned ASTContext::NumImplicitDefaultConstructors;
39 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
40 unsigned ASTContext::NumImplicitCopyConstructors;
41 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
42 unsigned ASTContext::NumImplicitMoveConstructors;
43 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
44 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
45 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
46 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
47 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
48 unsigned ASTContext::NumImplicitDestructors;
49 unsigned ASTContext::NumImplicitDestructorsDeclared;
52 FloatRank, DoubleRank, LongDoubleRank
56 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
57 TemplateTemplateParmDecl *Parm) {
58 ID.AddInteger(Parm->getDepth());
59 ID.AddInteger(Parm->getPosition());
60 ID.AddBoolean(Parm->isParameterPack());
62 TemplateParameterList *Params = Parm->getTemplateParameters();
63 ID.AddInteger(Params->size());
64 for (TemplateParameterList::const_iterator P = Params->begin(),
67 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddBoolean(TTP->isParameterPack());
73 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddBoolean(NTTP->isParameterPack());
76 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
77 if (NTTP->isExpandedParameterPack()) {
79 ID.AddInteger(NTTP->getNumExpansionTypes());
80 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
81 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
87 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
93 TemplateTemplateParmDecl *
94 ASTContext::getCanonicalTemplateTemplateParmDecl(
95 TemplateTemplateParmDecl *TTP) const {
96 // Check if we already have a canonical template template parameter.
97 llvm::FoldingSetNodeID ID;
98 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 CanonicalTemplateTemplateParm *Canonical
101 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 return Canonical->getParam();
105 // Build a canonical template parameter list.
106 TemplateParameterList *Params = TTP->getTemplateParameters();
107 llvm::SmallVector<NamedDecl *, 4> CanonParams;
108 CanonParams.reserve(Params->size());
109 for (TemplateParameterList::const_iterator P = Params->begin(),
110 PEnd = Params->end();
112 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
113 CanonParams.push_back(
114 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
118 TTP->getIndex(), 0, false,
119 TTP->isParameterPack()));
120 else if (NonTypeTemplateParmDecl *NTTP
121 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
122 QualType T = getCanonicalType(NTTP->getType());
123 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
124 NonTypeTemplateParmDecl *Param;
125 if (NTTP->isExpandedParameterPack()) {
126 llvm::SmallVector<QualType, 2> ExpandedTypes;
127 llvm::SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
128 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
129 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
130 ExpandedTInfos.push_back(
131 getTrivialTypeSourceInfo(ExpandedTypes.back()));
134 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
138 NTTP->getPosition(), 0,
141 ExpandedTypes.data(),
142 ExpandedTypes.size(),
143 ExpandedTInfos.data());
145 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
149 NTTP->getPosition(), 0,
151 NTTP->isParameterPack(),
154 CanonParams.push_back(Param);
157 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
158 cast<TemplateTemplateParmDecl>(*P)));
161 TemplateTemplateParmDecl *CanonTTP
162 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
163 SourceLocation(), TTP->getDepth(),
165 TTP->isParameterPack(),
167 TemplateParameterList::Create(*this, SourceLocation(),
173 // Get the new insert position for the node we care about.
174 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
175 assert(Canonical == 0 && "Shouldn't be in the map!");
178 // Create the canonical template template parameter entry.
179 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
180 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
184 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
185 if (!LangOpts.CPlusPlus) return 0;
187 switch (T.getCXXABI()) {
189 return CreateARMCXXABI(*this);
191 return CreateItaniumCXXABI(*this);
192 case CXXABI_Microsoft:
193 return CreateMicrosoftCXXABI(*this);
198 static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
199 const LangOptions &LOpts) {
200 if (LOpts.FakeAddressSpaceMap) {
201 // The fake address space map must have a distinct entry for each
202 // language-specific address space.
203 static const unsigned FakeAddrSpaceMap[] = {
208 return FakeAddrSpaceMap;
210 return T.getAddressSpaceMap();
214 ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
216 IdentifierTable &idents, SelectorTable &sels,
217 Builtin::Context &builtins,
218 unsigned size_reserve) :
219 FunctionProtoTypes(this_()),
220 TemplateSpecializationTypes(this_()),
221 DependentTemplateSpecializationTypes(this_()),
222 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
223 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0),
224 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
225 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
226 cudaConfigureCallDecl(0),
227 NullTypeSourceInfo(QualType()),
228 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
229 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
230 Idents(idents), Selectors(sels),
231 BuiltinInfo(builtins),
232 DeclarationNames(*this),
233 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
235 UniqueBlockByRefTypeID(0) {
236 ObjCIdRedefinitionType = QualType();
237 ObjCClassRedefinitionType = QualType();
238 ObjCSelRedefinitionType = QualType();
239 if (size_reserve > 0) Types.reserve(size_reserve);
240 TUDecl = TranslationUnitDecl::Create(*this);
244 ASTContext::~ASTContext() {
245 // Release the DenseMaps associated with DeclContext objects.
246 // FIXME: Is this the ideal solution?
247 ReleaseDeclContextMaps();
249 // Call all of the deallocation functions.
250 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
251 Deallocations[I].first(Deallocations[I].second);
253 // Release all of the memory associated with overridden C++ methods.
254 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
255 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
257 OM->second.Destroy();
259 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
260 // because they can contain DenseMaps.
261 for (llvm::DenseMap<const ObjCContainerDecl*,
262 const ASTRecordLayout*>::iterator
263 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
264 // Increment in loop to prevent using deallocated memory.
265 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
268 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
269 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
270 // Increment in loop to prevent using deallocated memory.
271 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
275 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
276 AEnd = DeclAttrs.end();
278 A->second->~AttrVec();
281 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
282 Deallocations.push_back(std::make_pair(Callback, Data));
286 ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
287 ExternalSource.reset(Source.take());
290 void ASTContext::PrintStats() const {
291 fprintf(stderr, "*** AST Context Stats:\n");
292 fprintf(stderr, " %d types total.\n", (int)Types.size());
294 unsigned counts[] = {
295 #define TYPE(Name, Parent) 0,
296 #define ABSTRACT_TYPE(Name, Parent)
297 #include "clang/AST/TypeNodes.def"
301 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
303 counts[(unsigned)T->getTypeClass()]++;
307 unsigned TotalBytes = 0;
308 #define TYPE(Name, Parent) \
310 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \
311 TotalBytes += counts[Idx] * sizeof(Name##Type); \
313 #define ABSTRACT_TYPE(Name, Parent)
314 #include "clang/AST/TypeNodes.def"
316 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
318 // Implicit special member functions.
319 fprintf(stderr, " %u/%u implicit default constructors created\n",
320 NumImplicitDefaultConstructorsDeclared,
321 NumImplicitDefaultConstructors);
322 fprintf(stderr, " %u/%u implicit copy constructors created\n",
323 NumImplicitCopyConstructorsDeclared,
324 NumImplicitCopyConstructors);
325 if (getLangOptions().CPlusPlus)
326 fprintf(stderr, " %u/%u implicit move constructors created\n",
327 NumImplicitMoveConstructorsDeclared,
328 NumImplicitMoveConstructors);
329 fprintf(stderr, " %u/%u implicit copy assignment operators created\n",
330 NumImplicitCopyAssignmentOperatorsDeclared,
331 NumImplicitCopyAssignmentOperators);
332 if (getLangOptions().CPlusPlus)
333 fprintf(stderr, " %u/%u implicit move assignment operators created\n",
334 NumImplicitMoveAssignmentOperatorsDeclared,
335 NumImplicitMoveAssignmentOperators);
336 fprintf(stderr, " %u/%u implicit destructors created\n",
337 NumImplicitDestructorsDeclared, NumImplicitDestructors);
339 if (ExternalSource.get()) {
340 fprintf(stderr, "\n");
341 ExternalSource->PrintStats();
344 BumpAlloc.PrintStats();
348 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
349 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
350 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
354 void ASTContext::InitBuiltinTypes() {
355 assert(VoidTy.isNull() && "Context reinitialized?");
358 InitBuiltinType(VoidTy, BuiltinType::Void);
361 InitBuiltinType(BoolTy, BuiltinType::Bool);
363 if (LangOpts.CharIsSigned)
364 InitBuiltinType(CharTy, BuiltinType::Char_S);
366 InitBuiltinType(CharTy, BuiltinType::Char_U);
368 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
369 InitBuiltinType(ShortTy, BuiltinType::Short);
370 InitBuiltinType(IntTy, BuiltinType::Int);
371 InitBuiltinType(LongTy, BuiltinType::Long);
372 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
375 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
376 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
377 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
378 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
379 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
382 InitBuiltinType(FloatTy, BuiltinType::Float);
383 InitBuiltinType(DoubleTy, BuiltinType::Double);
384 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
386 // GNU extension, 128-bit integers.
387 InitBuiltinType(Int128Ty, BuiltinType::Int128);
388 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
390 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
391 if (TargetInfo::isTypeSigned(Target.getWCharType()))
392 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
393 else // -fshort-wchar makes wchar_t be unsigned.
394 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
396 WCharTy = getFromTargetType(Target.getWCharType());
398 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
399 InitBuiltinType(Char16Ty, BuiltinType::Char16);
401 Char16Ty = getFromTargetType(Target.getChar16Type());
403 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
404 InitBuiltinType(Char32Ty, BuiltinType::Char32);
406 Char32Ty = getFromTargetType(Target.getChar32Type());
408 // Placeholder type for type-dependent expressions whose type is
409 // completely unknown. No code should ever check a type against
410 // DependentTy and users should never see it; however, it is here to
411 // help diagnose failures to properly check for type-dependent
413 InitBuiltinType(DependentTy, BuiltinType::Dependent);
415 // Placeholder type for functions.
416 InitBuiltinType(OverloadTy, BuiltinType::Overload);
418 // Placeholder type for bound members.
419 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
421 // "any" type; useful for debugger-like clients.
422 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
425 FloatComplexTy = getComplexType(FloatTy);
426 DoubleComplexTy = getComplexType(DoubleTy);
427 LongDoubleComplexTy = getComplexType(LongDoubleTy);
429 BuiltinVaListType = QualType();
431 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
432 ObjCIdTypedefType = QualType();
433 ObjCClassTypedefType = QualType();
434 ObjCSelTypedefType = QualType();
436 // Builtin types for 'id', 'Class', and 'SEL'.
437 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
438 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
439 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
441 ObjCConstantStringType = QualType();
444 VoidPtrTy = getPointerType(VoidTy);
446 // nullptr type (C++0x 2.14.7)
447 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
450 Diagnostic &ASTContext::getDiagnostics() const {
451 return SourceMgr.getDiagnostics();
454 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
455 AttrVec *&Result = DeclAttrs[D];
457 void *Mem = Allocate(sizeof(AttrVec));
458 Result = new (Mem) AttrVec;
464 /// \brief Erase the attributes corresponding to the given declaration.
465 void ASTContext::eraseDeclAttrs(const Decl *D) {
466 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
467 if (Pos != DeclAttrs.end()) {
468 Pos->second->~AttrVec();
469 DeclAttrs.erase(Pos);
473 MemberSpecializationInfo *
474 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
475 assert(Var->isStaticDataMember() && "Not a static data member");
476 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
477 = InstantiatedFromStaticDataMember.find(Var);
478 if (Pos == InstantiatedFromStaticDataMember.end())
485 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
486 TemplateSpecializationKind TSK,
487 SourceLocation PointOfInstantiation) {
488 assert(Inst->isStaticDataMember() && "Not a static data member");
489 assert(Tmpl->isStaticDataMember() && "Not a static data member");
490 assert(!InstantiatedFromStaticDataMember[Inst] &&
491 "Already noted what static data member was instantiated from");
492 InstantiatedFromStaticDataMember[Inst]
493 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
497 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
498 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
499 = InstantiatedFromUsingDecl.find(UUD);
500 if (Pos == InstantiatedFromUsingDecl.end())
507 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
508 assert((isa<UsingDecl>(Pattern) ||
509 isa<UnresolvedUsingValueDecl>(Pattern) ||
510 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
511 "pattern decl is not a using decl");
512 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
513 InstantiatedFromUsingDecl[Inst] = Pattern;
517 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
518 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
519 = InstantiatedFromUsingShadowDecl.find(Inst);
520 if (Pos == InstantiatedFromUsingShadowDecl.end())
527 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
528 UsingShadowDecl *Pattern) {
529 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
530 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
533 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
534 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
535 = InstantiatedFromUnnamedFieldDecl.find(Field);
536 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
542 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
544 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
545 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
546 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
547 "Already noted what unnamed field was instantiated from");
549 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
552 bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
553 const FieldDecl *LastFD) const {
554 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
555 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0);
559 bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
560 const FieldDecl *LastFD) const {
561 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
562 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() == 0 &&
563 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() != 0);
567 bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
568 const FieldDecl *LastFD) const {
569 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
570 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue() &&
571 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
574 bool ASTContext::NoneBitfieldFollowsBitfield(const FieldDecl *FD,
575 const FieldDecl *LastFD) const {
576 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
577 LastFD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
580 bool ASTContext::BitfieldFollowsNoneBitfield(const FieldDecl *FD,
581 const FieldDecl *LastFD) const {
582 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
583 FD->getBitWidth()-> EvaluateAsInt(*this).getZExtValue());
586 ASTContext::overridden_cxx_method_iterator
587 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
588 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
589 = OverriddenMethods.find(Method);
590 if (Pos == OverriddenMethods.end())
593 return Pos->second.begin();
596 ASTContext::overridden_cxx_method_iterator
597 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
598 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
599 = OverriddenMethods.find(Method);
600 if (Pos == OverriddenMethods.end())
603 return Pos->second.end();
607 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
608 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
609 = OverriddenMethods.find(Method);
610 if (Pos == OverriddenMethods.end())
613 return Pos->second.size();
616 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
617 const CXXMethodDecl *Overridden) {
618 OverriddenMethods[Method].push_back(Overridden);
621 //===----------------------------------------------------------------------===//
622 // Type Sizing and Analysis
623 //===----------------------------------------------------------------------===//
625 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
626 /// scalar floating point type.
627 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
628 const BuiltinType *BT = T->getAs<BuiltinType>();
629 assert(BT && "Not a floating point type!");
630 switch (BT->getKind()) {
631 default: assert(0 && "Not a floating point type!");
632 case BuiltinType::Float: return Target.getFloatFormat();
633 case BuiltinType::Double: return Target.getDoubleFormat();
634 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
638 /// getDeclAlign - Return a conservative estimate of the alignment of the
639 /// specified decl. Note that bitfields do not have a valid alignment, so
640 /// this method will assert on them.
641 /// If @p RefAsPointee, references are treated like their underlying type
642 /// (for alignof), else they're treated like pointers (for CodeGen).
643 CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
644 unsigned Align = Target.getCharWidth();
646 bool UseAlignAttrOnly = false;
647 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
648 Align = AlignFromAttr;
650 // __attribute__((aligned)) can increase or decrease alignment
651 // *except* on a struct or struct member, where it only increases
652 // alignment unless 'packed' is also specified.
654 // It is an error for [[align]] to decrease alignment, so we can
655 // ignore that possibility; Sema should diagnose it.
656 if (isa<FieldDecl>(D)) {
657 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
658 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
660 UseAlignAttrOnly = true;
663 else if (isa<FieldDecl>(D))
665 D->hasAttr<PackedAttr>() ||
666 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
668 // If we're using the align attribute only, just ignore everything
669 // else about the declaration and its type.
670 if (UseAlignAttrOnly) {
673 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
674 QualType T = VD->getType();
675 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
677 T = RT->getPointeeType();
679 T = getPointerType(RT->getPointeeType());
681 if (!T->isIncompleteType() && !T->isFunctionType()) {
682 // Adjust alignments of declarations with array type by the
683 // large-array alignment on the target.
684 unsigned MinWidth = Target.getLargeArrayMinWidth();
685 const ArrayType *arrayType;
686 if (MinWidth && (arrayType = getAsArrayType(T))) {
687 if (isa<VariableArrayType>(arrayType))
688 Align = std::max(Align, Target.getLargeArrayAlign());
689 else if (isa<ConstantArrayType>(arrayType) &&
690 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
691 Align = std::max(Align, Target.getLargeArrayAlign());
693 // Walk through any array types while we're at it.
694 T = getBaseElementType(arrayType);
696 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
699 // Fields can be subject to extra alignment constraints, like if
700 // the field is packed, the struct is packed, or the struct has a
701 // a max-field-alignment constraint (#pragma pack). So calculate
702 // the actual alignment of the field within the struct, and then
703 // (as we're expected to) constrain that by the alignment of the type.
704 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
705 // So calculate the alignment of the field.
706 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
708 // Start with the record's overall alignment.
709 unsigned fieldAlign = toBits(layout.getAlignment());
711 // Use the GCD of that and the offset within the record.
712 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
714 // Alignment is always a power of 2, so the GCD will be a power of 2,
715 // which means we get to do this crazy thing instead of Euclid's.
716 uint64_t lowBitOfOffset = offset & (~offset + 1);
717 if (lowBitOfOffset < fieldAlign)
718 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
721 Align = std::min(Align, fieldAlign);
725 return toCharUnitsFromBits(Align);
728 std::pair<CharUnits, CharUnits>
729 ASTContext::getTypeInfoInChars(const Type *T) const {
730 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
731 return std::make_pair(toCharUnitsFromBits(Info.first),
732 toCharUnitsFromBits(Info.second));
735 std::pair<CharUnits, CharUnits>
736 ASTContext::getTypeInfoInChars(QualType T) const {
737 return getTypeInfoInChars(T.getTypePtr());
740 /// getTypeSize - Return the size of the specified type, in bits. This method
741 /// does not work on incomplete types.
743 /// FIXME: Pointers into different addr spaces could have different sizes and
744 /// alignment requirements: getPointerInfo should take an AddrSpace, this
745 /// should take a QualType, &c.
746 std::pair<uint64_t, unsigned>
747 ASTContext::getTypeInfo(const Type *T) const {
750 switch (T->getTypeClass()) {
751 #define TYPE(Class, Base)
752 #define ABSTRACT_TYPE(Class, Base)
753 #define NON_CANONICAL_TYPE(Class, Base)
754 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
755 #include "clang/AST/TypeNodes.def"
756 assert(false && "Should not see dependent types");
759 case Type::FunctionNoProto:
760 case Type::FunctionProto:
761 // GCC extension: alignof(function) = 32 bits
766 case Type::IncompleteArray:
767 case Type::VariableArray:
769 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
772 case Type::ConstantArray: {
773 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
775 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
776 Width = EltInfo.first*CAT->getSize().getZExtValue();
777 Align = EltInfo.second;
778 Width = llvm::RoundUpToAlignment(Width, Align);
781 case Type::ExtVector:
783 const VectorType *VT = cast<VectorType>(T);
784 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
785 Width = EltInfo.first*VT->getNumElements();
787 // If the alignment is not a power of 2, round up to the next power of 2.
788 // This happens for non-power-of-2 length vectors.
789 if (Align & (Align-1)) {
790 Align = llvm::NextPowerOf2(Align);
791 Width = llvm::RoundUpToAlignment(Width, Align);
797 switch (cast<BuiltinType>(T)->getKind()) {
798 default: assert(0 && "Unknown builtin type!");
799 case BuiltinType::Void:
800 // GCC extension: alignof(void) = 8 bits.
805 case BuiltinType::Bool:
806 Width = Target.getBoolWidth();
807 Align = Target.getBoolAlign();
809 case BuiltinType::Char_S:
810 case BuiltinType::Char_U:
811 case BuiltinType::UChar:
812 case BuiltinType::SChar:
813 Width = Target.getCharWidth();
814 Align = Target.getCharAlign();
816 case BuiltinType::WChar_S:
817 case BuiltinType::WChar_U:
818 Width = Target.getWCharWidth();
819 Align = Target.getWCharAlign();
821 case BuiltinType::Char16:
822 Width = Target.getChar16Width();
823 Align = Target.getChar16Align();
825 case BuiltinType::Char32:
826 Width = Target.getChar32Width();
827 Align = Target.getChar32Align();
829 case BuiltinType::UShort:
830 case BuiltinType::Short:
831 Width = Target.getShortWidth();
832 Align = Target.getShortAlign();
834 case BuiltinType::UInt:
835 case BuiltinType::Int:
836 Width = Target.getIntWidth();
837 Align = Target.getIntAlign();
839 case BuiltinType::ULong:
840 case BuiltinType::Long:
841 Width = Target.getLongWidth();
842 Align = Target.getLongAlign();
844 case BuiltinType::ULongLong:
845 case BuiltinType::LongLong:
846 Width = Target.getLongLongWidth();
847 Align = Target.getLongLongAlign();
849 case BuiltinType::Int128:
850 case BuiltinType::UInt128:
852 Align = 128; // int128_t is 128-bit aligned on all targets.
854 case BuiltinType::Float:
855 Width = Target.getFloatWidth();
856 Align = Target.getFloatAlign();
858 case BuiltinType::Double:
859 Width = Target.getDoubleWidth();
860 Align = Target.getDoubleAlign();
862 case BuiltinType::LongDouble:
863 Width = Target.getLongDoubleWidth();
864 Align = Target.getLongDoubleAlign();
866 case BuiltinType::NullPtr:
867 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
868 Align = Target.getPointerAlign(0); // == sizeof(void*)
870 case BuiltinType::ObjCId:
871 case BuiltinType::ObjCClass:
872 case BuiltinType::ObjCSel:
873 Width = Target.getPointerWidth(0);
874 Align = Target.getPointerAlign(0);
878 case Type::ObjCObjectPointer:
879 Width = Target.getPointerWidth(0);
880 Align = Target.getPointerAlign(0);
882 case Type::BlockPointer: {
883 unsigned AS = getTargetAddressSpace(
884 cast<BlockPointerType>(T)->getPointeeType());
885 Width = Target.getPointerWidth(AS);
886 Align = Target.getPointerAlign(AS);
889 case Type::LValueReference:
890 case Type::RValueReference: {
891 // alignof and sizeof should never enter this code path here, so we go
892 // the pointer route.
893 unsigned AS = getTargetAddressSpace(
894 cast<ReferenceType>(T)->getPointeeType());
895 Width = Target.getPointerWidth(AS);
896 Align = Target.getPointerAlign(AS);
899 case Type::Pointer: {
900 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
901 Width = Target.getPointerWidth(AS);
902 Align = Target.getPointerAlign(AS);
905 case Type::MemberPointer: {
906 const MemberPointerType *MPT = cast<MemberPointerType>(T);
907 std::pair<uint64_t, unsigned> PtrDiffInfo =
908 getTypeInfo(getPointerDiffType());
909 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
910 Align = PtrDiffInfo.second;
913 case Type::Complex: {
914 // Complex types have the same alignment as their elements, but twice the
916 std::pair<uint64_t, unsigned> EltInfo =
917 getTypeInfo(cast<ComplexType>(T)->getElementType());
918 Width = EltInfo.first*2;
919 Align = EltInfo.second;
922 case Type::ObjCObject:
923 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
924 case Type::ObjCInterface: {
925 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
926 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
927 Width = toBits(Layout.getSize());
928 Align = toBits(Layout.getAlignment());
933 const TagType *TT = cast<TagType>(T);
935 if (TT->getDecl()->isInvalidDecl()) {
941 if (const EnumType *ET = dyn_cast<EnumType>(TT))
942 return getTypeInfo(ET->getDecl()->getIntegerType());
944 const RecordType *RT = cast<RecordType>(TT);
945 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
946 Width = toBits(Layout.getSize());
947 Align = toBits(Layout.getAlignment());
951 case Type::SubstTemplateTypeParm:
952 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
953 getReplacementType().getTypePtr());
956 const AutoType *A = cast<AutoType>(T);
957 assert(A->isDeduced() && "Cannot request the size of a dependent type");
958 return getTypeInfo(A->getDeducedType().getTypePtr());
962 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
964 case Type::Typedef: {
965 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
966 std::pair<uint64_t, unsigned> Info
967 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
968 // If the typedef has an aligned attribute on it, it overrides any computed
969 // alignment we have. This violates the GCC documentation (which says that
970 // attribute(aligned) can only round up) but matches its implementation.
971 if (unsigned AttrAlign = Typedef->getMaxAlignment())
979 case Type::TypeOfExpr:
980 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
984 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
987 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
990 case Type::UnaryTransform:
991 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
993 case Type::Elaborated:
994 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
996 case Type::Attributed:
998 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1000 case Type::TemplateSpecialization: {
1001 assert(getCanonicalType(T) != T &&
1002 "Cannot request the size of a dependent type");
1003 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1004 // A type alias template specialization may refer to a typedef with the
1005 // aligned attribute on it.
1006 if (TST->isTypeAlias())
1007 return getTypeInfo(TST->getAliasedType().getTypePtr());
1009 return getTypeInfo(getCanonicalType(T));
1014 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
1015 return std::make_pair(Width, Align);
1018 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1019 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1020 return CharUnits::fromQuantity(BitSize / getCharWidth());
1023 /// toBits - Convert a size in characters to a size in characters.
1024 int64_t ASTContext::toBits(CharUnits CharSize) const {
1025 return CharSize.getQuantity() * getCharWidth();
1028 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1029 /// This method does not work on incomplete types.
1030 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1031 return toCharUnitsFromBits(getTypeSize(T));
1033 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1034 return toCharUnitsFromBits(getTypeSize(T));
1037 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1038 /// characters. This method does not work on incomplete types.
1039 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1040 return toCharUnitsFromBits(getTypeAlign(T));
1042 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1043 return toCharUnitsFromBits(getTypeAlign(T));
1046 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1047 /// type for the current target in bits. This can be different than the ABI
1048 /// alignment in cases where it is beneficial for performance to overalign
1050 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1051 unsigned ABIAlign = getTypeAlign(T);
1053 // Double and long long should be naturally aligned if possible.
1054 if (const ComplexType* CT = T->getAs<ComplexType>())
1055 T = CT->getElementType().getTypePtr();
1056 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1057 T->isSpecificBuiltinType(BuiltinType::LongLong))
1058 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1063 /// ShallowCollectObjCIvars -
1064 /// Collect all ivars, including those synthesized, in the current class.
1066 void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
1067 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
1068 // FIXME. This need be removed but there are two many places which
1069 // assume const-ness of ObjCInterfaceDecl
1070 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1071 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1072 Iv= Iv->getNextIvar())
1073 Ivars.push_back(Iv);
1076 /// DeepCollectObjCIvars -
1077 /// This routine first collects all declared, but not synthesized, ivars in
1078 /// super class and then collects all ivars, including those synthesized for
1079 /// current class. This routine is used for implementation of current class
1080 /// when all ivars, declared and synthesized are known.
1082 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1084 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) const {
1085 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1086 DeepCollectObjCIvars(SuperClass, false, Ivars);
1088 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1089 E = OI->ivar_end(); I != E; ++I)
1090 Ivars.push_back(*I);
1093 ShallowCollectObjCIvars(OI, Ivars);
1096 /// CollectInheritedProtocols - Collect all protocols in current class and
1097 /// those inherited by it.
1098 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1099 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1100 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1101 // We can use protocol_iterator here instead of
1102 // all_referenced_protocol_iterator since we are walking all categories.
1103 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1104 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1105 ObjCProtocolDecl *Proto = (*P);
1106 Protocols.insert(Proto);
1107 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1108 PE = Proto->protocol_end(); P != PE; ++P) {
1109 Protocols.insert(*P);
1110 CollectInheritedProtocols(*P, Protocols);
1114 // Categories of this Interface.
1115 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1116 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1117 CollectInheritedProtocols(CDeclChain, Protocols);
1118 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1120 CollectInheritedProtocols(SD, Protocols);
1121 SD = SD->getSuperClass();
1123 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1124 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1125 PE = OC->protocol_end(); P != PE; ++P) {
1126 ObjCProtocolDecl *Proto = (*P);
1127 Protocols.insert(Proto);
1128 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1129 PE = Proto->protocol_end(); P != PE; ++P)
1130 CollectInheritedProtocols(*P, Protocols);
1132 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1133 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1134 PE = OP->protocol_end(); P != PE; ++P) {
1135 ObjCProtocolDecl *Proto = (*P);
1136 Protocols.insert(Proto);
1137 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1138 PE = Proto->protocol_end(); P != PE; ++P)
1139 CollectInheritedProtocols(*P, Protocols);
1144 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1146 // Count ivars declared in class extension.
1147 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1148 CDecl = CDecl->getNextClassExtension())
1149 count += CDecl->ivar_size();
1151 // Count ivar defined in this class's implementation. This
1152 // includes synthesized ivars.
1153 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1154 count += ImplDecl->ivar_size();
1159 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1160 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1161 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1162 I = ObjCImpls.find(D);
1163 if (I != ObjCImpls.end())
1164 return cast<ObjCImplementationDecl>(I->second);
1167 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1168 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1169 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1170 I = ObjCImpls.find(D);
1171 if (I != ObjCImpls.end())
1172 return cast<ObjCCategoryImplDecl>(I->second);
1176 /// \brief Set the implementation of ObjCInterfaceDecl.
1177 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1178 ObjCImplementationDecl *ImplD) {
1179 assert(IFaceD && ImplD && "Passed null params");
1180 ObjCImpls[IFaceD] = ImplD;
1182 /// \brief Set the implementation of ObjCCategoryDecl.
1183 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1184 ObjCCategoryImplDecl *ImplD) {
1185 assert(CatD && ImplD && "Passed null params");
1186 ObjCImpls[CatD] = ImplD;
1189 /// \brief Get the copy initialization expression of VarDecl,or NULL if
1191 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1192 assert(VD && "Passed null params");
1193 assert(VD->hasAttr<BlocksAttr>() &&
1194 "getBlockVarCopyInits - not __block var");
1195 llvm::DenseMap<const VarDecl*, Expr*>::iterator
1196 I = BlockVarCopyInits.find(VD);
1197 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1200 /// \brief Set the copy inialization expression of a block var decl.
1201 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1202 assert(VD && Init && "Passed null params");
1203 assert(VD->hasAttr<BlocksAttr>() &&
1204 "setBlockVarCopyInits - not __block var");
1205 BlockVarCopyInits[VD] = Init;
1208 /// \brief Allocate an uninitialized TypeSourceInfo.
1210 /// The caller should initialize the memory held by TypeSourceInfo using
1211 /// the TypeLoc wrappers.
1213 /// \param T the type that will be the basis for type source info. This type
1214 /// should refer to how the declarator was written in source code, not to
1215 /// what type semantic analysis resolved the declarator to.
1216 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1217 unsigned DataSize) const {
1219 DataSize = TypeLoc::getFullDataSizeForType(T);
1221 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1222 "incorrect data size provided to CreateTypeSourceInfo!");
1224 TypeSourceInfo *TInfo =
1225 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1226 new (TInfo) TypeSourceInfo(T);
1230 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1231 SourceLocation L) const {
1232 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1233 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1237 const ASTRecordLayout &
1238 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1239 return getObjCLayout(D, 0);
1242 const ASTRecordLayout &
1243 ASTContext::getASTObjCImplementationLayout(
1244 const ObjCImplementationDecl *D) const {
1245 return getObjCLayout(D->getClassInterface(), D);
1248 //===----------------------------------------------------------------------===//
1249 // Type creation/memoization methods
1250 //===----------------------------------------------------------------------===//
1253 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1254 unsigned fastQuals = quals.getFastQualifiers();
1255 quals.removeFastQualifiers();
1257 // Check if we've already instantiated this type.
1258 llvm::FoldingSetNodeID ID;
1259 ExtQuals::Profile(ID, baseType, quals);
1260 void *insertPos = 0;
1261 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1262 assert(eq->getQualifiers() == quals);
1263 return QualType(eq, fastQuals);
1266 // If the base type is not canonical, make the appropriate canonical type.
1268 if (!baseType->isCanonicalUnqualified()) {
1269 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1270 canonSplit.second.addConsistentQualifiers(quals);
1271 canon = getExtQualType(canonSplit.first, canonSplit.second);
1273 // Re-find the insert position.
1274 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1277 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1278 ExtQualNodes.InsertNode(eq, insertPos);
1279 return QualType(eq, fastQuals);
1283 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1284 QualType CanT = getCanonicalType(T);
1285 if (CanT.getAddressSpace() == AddressSpace)
1288 // If we are composing extended qualifiers together, merge together
1289 // into one ExtQuals node.
1290 QualifierCollector Quals;
1291 const Type *TypeNode = Quals.strip(T);
1293 // If this type already has an address space specified, it cannot get
1295 assert(!Quals.hasAddressSpace() &&
1296 "Type cannot be in multiple addr spaces!");
1297 Quals.addAddressSpace(AddressSpace);
1299 return getExtQualType(TypeNode, Quals);
1302 QualType ASTContext::getObjCGCQualType(QualType T,
1303 Qualifiers::GC GCAttr) const {
1304 QualType CanT = getCanonicalType(T);
1305 if (CanT.getObjCGCAttr() == GCAttr)
1308 if (const PointerType *ptr = T->getAs<PointerType>()) {
1309 QualType Pointee = ptr->getPointeeType();
1310 if (Pointee->isAnyPointerType()) {
1311 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1312 return getPointerType(ResultType);
1316 // If we are composing extended qualifiers together, merge together
1317 // into one ExtQuals node.
1318 QualifierCollector Quals;
1319 const Type *TypeNode = Quals.strip(T);
1321 // If this type already has an ObjCGC specified, it cannot get
1323 assert(!Quals.hasObjCGCAttr() &&
1324 "Type cannot have multiple ObjCGCs!");
1325 Quals.addObjCGCAttr(GCAttr);
1327 return getExtQualType(TypeNode, Quals);
1330 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1331 FunctionType::ExtInfo Info) {
1332 if (T->getExtInfo() == Info)
1336 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1337 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1339 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1340 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1342 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1343 FPT->getNumArgs(), EPI);
1346 return cast<FunctionType>(Result.getTypePtr());
1349 /// getComplexType - Return the uniqued reference to the type for a complex
1350 /// number with the specified element type.
1351 QualType ASTContext::getComplexType(QualType T) const {
1352 // Unique pointers, to guarantee there is only one pointer of a particular
1354 llvm::FoldingSetNodeID ID;
1355 ComplexType::Profile(ID, T);
1357 void *InsertPos = 0;
1358 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1359 return QualType(CT, 0);
1361 // If the pointee type isn't canonical, this won't be a canonical type either,
1362 // so fill in the canonical type field.
1364 if (!T.isCanonical()) {
1365 Canonical = getComplexType(getCanonicalType(T));
1367 // Get the new insert position for the node we care about.
1368 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1369 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1371 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1372 Types.push_back(New);
1373 ComplexTypes.InsertNode(New, InsertPos);
1374 return QualType(New, 0);
1377 /// getPointerType - Return the uniqued reference to the type for a pointer to
1378 /// the specified type.
1379 QualType ASTContext::getPointerType(QualType T) const {
1380 // Unique pointers, to guarantee there is only one pointer of a particular
1382 llvm::FoldingSetNodeID ID;
1383 PointerType::Profile(ID, T);
1385 void *InsertPos = 0;
1386 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1387 return QualType(PT, 0);
1389 // If the pointee type isn't canonical, this won't be a canonical type either,
1390 // so fill in the canonical type field.
1392 if (!T.isCanonical()) {
1393 Canonical = getPointerType(getCanonicalType(T));
1395 // Get the new insert position for the node we care about.
1396 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1397 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1399 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1400 Types.push_back(New);
1401 PointerTypes.InsertNode(New, InsertPos);
1402 return QualType(New, 0);
1405 /// getBlockPointerType - Return the uniqued reference to the type for
1406 /// a pointer to the specified block.
1407 QualType ASTContext::getBlockPointerType(QualType T) const {
1408 assert(T->isFunctionType() && "block of function types only");
1409 // Unique pointers, to guarantee there is only one block of a particular
1411 llvm::FoldingSetNodeID ID;
1412 BlockPointerType::Profile(ID, T);
1414 void *InsertPos = 0;
1415 if (BlockPointerType *PT =
1416 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1417 return QualType(PT, 0);
1419 // If the block pointee type isn't canonical, this won't be a canonical
1420 // type either so fill in the canonical type field.
1422 if (!T.isCanonical()) {
1423 Canonical = getBlockPointerType(getCanonicalType(T));
1425 // Get the new insert position for the node we care about.
1426 BlockPointerType *NewIP =
1427 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1428 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1430 BlockPointerType *New
1431 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1432 Types.push_back(New);
1433 BlockPointerTypes.InsertNode(New, InsertPos);
1434 return QualType(New, 0);
1437 /// getLValueReferenceType - Return the uniqued reference to the type for an
1438 /// lvalue reference to the specified type.
1440 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
1441 assert(getCanonicalType(T) != OverloadTy &&
1442 "Unresolved overloaded function type");
1444 // Unique pointers, to guarantee there is only one pointer of a particular
1446 llvm::FoldingSetNodeID ID;
1447 ReferenceType::Profile(ID, T, SpelledAsLValue);
1449 void *InsertPos = 0;
1450 if (LValueReferenceType *RT =
1451 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1452 return QualType(RT, 0);
1454 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1456 // If the referencee type isn't canonical, this won't be a canonical type
1457 // either, so fill in the canonical type field.
1459 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1460 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1461 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1463 // Get the new insert position for the node we care about.
1464 LValueReferenceType *NewIP =
1465 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1466 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1469 LValueReferenceType *New
1470 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1472 Types.push_back(New);
1473 LValueReferenceTypes.InsertNode(New, InsertPos);
1475 return QualType(New, 0);
1478 /// getRValueReferenceType - Return the uniqued reference to the type for an
1479 /// rvalue reference to the specified type.
1480 QualType ASTContext::getRValueReferenceType(QualType T) const {
1481 // Unique pointers, to guarantee there is only one pointer of a particular
1483 llvm::FoldingSetNodeID ID;
1484 ReferenceType::Profile(ID, T, false);
1486 void *InsertPos = 0;
1487 if (RValueReferenceType *RT =
1488 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1489 return QualType(RT, 0);
1491 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1493 // If the referencee type isn't canonical, this won't be a canonical type
1494 // either, so fill in the canonical type field.
1496 if (InnerRef || !T.isCanonical()) {
1497 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1498 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1500 // Get the new insert position for the node we care about.
1501 RValueReferenceType *NewIP =
1502 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1503 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1506 RValueReferenceType *New
1507 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1508 Types.push_back(New);
1509 RValueReferenceTypes.InsertNode(New, InsertPos);
1510 return QualType(New, 0);
1513 /// getMemberPointerType - Return the uniqued reference to the type for a
1514 /// member pointer to the specified type, in the specified class.
1515 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
1516 // Unique pointers, to guarantee there is only one pointer of a particular
1518 llvm::FoldingSetNodeID ID;
1519 MemberPointerType::Profile(ID, T, Cls);
1521 void *InsertPos = 0;
1522 if (MemberPointerType *PT =
1523 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1524 return QualType(PT, 0);
1526 // If the pointee or class type isn't canonical, this won't be a canonical
1527 // type either, so fill in the canonical type field.
1529 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1530 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1532 // Get the new insert position for the node we care about.
1533 MemberPointerType *NewIP =
1534 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1535 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1537 MemberPointerType *New
1538 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1539 Types.push_back(New);
1540 MemberPointerTypes.InsertNode(New, InsertPos);
1541 return QualType(New, 0);
1544 /// getConstantArrayType - Return the unique reference to the type for an
1545 /// array of the specified element type.
1546 QualType ASTContext::getConstantArrayType(QualType EltTy,
1547 const llvm::APInt &ArySizeIn,
1548 ArrayType::ArraySizeModifier ASM,
1549 unsigned IndexTypeQuals) const {
1550 assert((EltTy->isDependentType() ||
1551 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1552 "Constant array of VLAs is illegal!");
1554 // Convert the array size into a canonical width matching the pointer size for
1556 llvm::APInt ArySize(ArySizeIn);
1558 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
1560 llvm::FoldingSetNodeID ID;
1561 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
1563 void *InsertPos = 0;
1564 if (ConstantArrayType *ATP =
1565 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1566 return QualType(ATP, 0);
1568 // If the element type isn't canonical or has qualifiers, this won't
1569 // be a canonical type either, so fill in the canonical type field.
1571 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1572 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1573 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
1574 ASM, IndexTypeQuals);
1575 Canon = getQualifiedType(Canon, canonSplit.second);
1577 // Get the new insert position for the node we care about.
1578 ConstantArrayType *NewIP =
1579 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1580 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1583 ConstantArrayType *New = new(*this,TypeAlignment)
1584 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
1585 ConstantArrayTypes.InsertNode(New, InsertPos);
1586 Types.push_back(New);
1587 return QualType(New, 0);
1590 /// getVariableArrayDecayedType - Turns the given type, which may be
1591 /// variably-modified, into the corresponding type with all the known
1592 /// sizes replaced with [*].
1593 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1594 // Vastly most common case.
1595 if (!type->isVariablyModifiedType()) return type;
1599 SplitQualType split = type.getSplitDesugaredType();
1600 const Type *ty = split.first;
1601 switch (ty->getTypeClass()) {
1602 #define TYPE(Class, Base)
1603 #define ABSTRACT_TYPE(Class, Base)
1604 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1605 #include "clang/AST/TypeNodes.def"
1606 llvm_unreachable("didn't desugar past all non-canonical types?");
1608 // These types should never be variably-modified.
1612 case Type::ExtVector:
1613 case Type::DependentSizedExtVector:
1614 case Type::ObjCObject:
1615 case Type::ObjCInterface:
1616 case Type::ObjCObjectPointer:
1619 case Type::UnresolvedUsing:
1620 case Type::TypeOfExpr:
1622 case Type::Decltype:
1623 case Type::UnaryTransform:
1624 case Type::DependentName:
1625 case Type::InjectedClassName:
1626 case Type::TemplateSpecialization:
1627 case Type::DependentTemplateSpecialization:
1628 case Type::TemplateTypeParm:
1629 case Type::SubstTemplateTypeParmPack:
1631 case Type::PackExpansion:
1632 llvm_unreachable("type should never be variably-modified");
1634 // These types can be variably-modified but should never need to
1636 case Type::FunctionNoProto:
1637 case Type::FunctionProto:
1638 case Type::BlockPointer:
1639 case Type::MemberPointer:
1642 // These types can be variably-modified. All these modifications
1643 // preserve structure except as noted by comments.
1644 // TODO: if we ever care about optimizing VLAs, there are no-op
1645 // optimizations available here.
1647 result = getPointerType(getVariableArrayDecayedType(
1648 cast<PointerType>(ty)->getPointeeType()));
1651 case Type::LValueReference: {
1652 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1653 result = getLValueReferenceType(
1654 getVariableArrayDecayedType(lv->getPointeeType()),
1655 lv->isSpelledAsLValue());
1659 case Type::RValueReference: {
1660 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1661 result = getRValueReferenceType(
1662 getVariableArrayDecayedType(lv->getPointeeType()));
1666 case Type::ConstantArray: {
1667 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1668 result = getConstantArrayType(
1669 getVariableArrayDecayedType(cat->getElementType()),
1671 cat->getSizeModifier(),
1672 cat->getIndexTypeCVRQualifiers());
1676 case Type::DependentSizedArray: {
1677 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1678 result = getDependentSizedArrayType(
1679 getVariableArrayDecayedType(dat->getElementType()),
1681 dat->getSizeModifier(),
1682 dat->getIndexTypeCVRQualifiers(),
1683 dat->getBracketsRange());
1687 // Turn incomplete types into [*] types.
1688 case Type::IncompleteArray: {
1689 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1690 result = getVariableArrayType(
1691 getVariableArrayDecayedType(iat->getElementType()),
1694 iat->getIndexTypeCVRQualifiers(),
1699 // Turn VLA types into [*] types.
1700 case Type::VariableArray: {
1701 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1702 result = getVariableArrayType(
1703 getVariableArrayDecayedType(vat->getElementType()),
1706 vat->getIndexTypeCVRQualifiers(),
1707 vat->getBracketsRange());
1712 // Apply the top-level qualifiers from the original.
1713 return getQualifiedType(result, split.second);
1716 /// getVariableArrayType - Returns a non-unique reference to the type for a
1717 /// variable array of the specified element type.
1718 QualType ASTContext::getVariableArrayType(QualType EltTy,
1720 ArrayType::ArraySizeModifier ASM,
1721 unsigned IndexTypeQuals,
1722 SourceRange Brackets) const {
1723 // Since we don't unique expressions, it isn't possible to unique VLA's
1724 // that have an expression provided for their size.
1727 // Be sure to pull qualifiers off the element type.
1728 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1729 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1730 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
1731 IndexTypeQuals, Brackets);
1732 Canon = getQualifiedType(Canon, canonSplit.second);
1735 VariableArrayType *New = new(*this, TypeAlignment)
1736 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
1738 VariableArrayTypes.push_back(New);
1739 Types.push_back(New);
1740 return QualType(New, 0);
1743 /// getDependentSizedArrayType - Returns a non-unique reference to
1744 /// the type for a dependently-sized array of the specified element
1746 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1748 ArrayType::ArraySizeModifier ASM,
1749 unsigned elementTypeQuals,
1750 SourceRange brackets) const {
1751 assert((!numElements || numElements->isTypeDependent() ||
1752 numElements->isValueDependent()) &&
1753 "Size must be type- or value-dependent!");
1755 // Dependently-sized array types that do not have a specified number
1756 // of elements will have their sizes deduced from a dependent
1757 // initializer. We do no canonicalization here at all, which is okay
1758 // because they can't be used in most locations.
1760 DependentSizedArrayType *newType
1761 = new (*this, TypeAlignment)
1762 DependentSizedArrayType(*this, elementType, QualType(),
1763 numElements, ASM, elementTypeQuals,
1765 Types.push_back(newType);
1766 return QualType(newType, 0);
1769 // Otherwise, we actually build a new type every time, but we
1770 // also build a canonical type.
1772 SplitQualType canonElementType = getCanonicalType(elementType).split();
1774 void *insertPos = 0;
1775 llvm::FoldingSetNodeID ID;
1776 DependentSizedArrayType::Profile(ID, *this,
1777 QualType(canonElementType.first, 0),
1778 ASM, elementTypeQuals, numElements);
1780 // Look for an existing type with these properties.
1781 DependentSizedArrayType *canonTy =
1782 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1784 // If we don't have one, build one.
1786 canonTy = new (*this, TypeAlignment)
1787 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1788 QualType(), numElements, ASM, elementTypeQuals,
1790 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1791 Types.push_back(canonTy);
1794 // Apply qualifiers from the element type to the array.
1795 QualType canon = getQualifiedType(QualType(canonTy,0),
1796 canonElementType.second);
1798 // If we didn't need extra canonicalization for the element type,
1799 // then just use that as our result.
1800 if (QualType(canonElementType.first, 0) == elementType)
1803 // Otherwise, we need to build a type which follows the spelling
1804 // of the element type.
1805 DependentSizedArrayType *sugaredType
1806 = new (*this, TypeAlignment)
1807 DependentSizedArrayType(*this, elementType, canon, numElements,
1808 ASM, elementTypeQuals, brackets);
1809 Types.push_back(sugaredType);
1810 return QualType(sugaredType, 0);
1813 QualType ASTContext::getIncompleteArrayType(QualType elementType,
1814 ArrayType::ArraySizeModifier ASM,
1815 unsigned elementTypeQuals) const {
1816 llvm::FoldingSetNodeID ID;
1817 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
1819 void *insertPos = 0;
1820 if (IncompleteArrayType *iat =
1821 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1822 return QualType(iat, 0);
1824 // If the element type isn't canonical, this won't be a canonical type
1825 // either, so fill in the canonical type field. We also have to pull
1826 // qualifiers off the element type.
1829 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1830 SplitQualType canonSplit = getCanonicalType(elementType).split();
1831 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1832 ASM, elementTypeQuals);
1833 canon = getQualifiedType(canon, canonSplit.second);
1835 // Get the new insert position for the node we care about.
1836 IncompleteArrayType *existing =
1837 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1838 assert(!existing && "Shouldn't be in the map!"); (void) existing;
1841 IncompleteArrayType *newType = new (*this, TypeAlignment)
1842 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
1844 IncompleteArrayTypes.InsertNode(newType, insertPos);
1845 Types.push_back(newType);
1846 return QualType(newType, 0);
1849 /// getVectorType - Return the unique reference to a vector type of
1850 /// the specified element type and size. VectorType must be a built-in type.
1851 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1852 VectorType::VectorKind VecKind) const {
1853 assert(vecType->isBuiltinType());
1855 // Check if we've already instantiated a vector of this type.
1856 llvm::FoldingSetNodeID ID;
1857 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
1859 void *InsertPos = 0;
1860 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1861 return QualType(VTP, 0);
1863 // If the element type isn't canonical, this won't be a canonical type either,
1864 // so fill in the canonical type field.
1866 if (!vecType.isCanonical()) {
1867 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
1869 // Get the new insert position for the node we care about.
1870 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1871 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1873 VectorType *New = new (*this, TypeAlignment)
1874 VectorType(vecType, NumElts, Canonical, VecKind);
1875 VectorTypes.InsertNode(New, InsertPos);
1876 Types.push_back(New);
1877 return QualType(New, 0);
1880 /// getExtVectorType - Return the unique reference to an extended vector type of
1881 /// the specified element type and size. VectorType must be a built-in type.
1883 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
1884 assert(vecType->isBuiltinType());
1886 // Check if we've already instantiated a vector of this type.
1887 llvm::FoldingSetNodeID ID;
1888 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
1889 VectorType::GenericVector);
1890 void *InsertPos = 0;
1891 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1892 return QualType(VTP, 0);
1894 // If the element type isn't canonical, this won't be a canonical type either,
1895 // so fill in the canonical type field.
1897 if (!vecType.isCanonical()) {
1898 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1900 // Get the new insert position for the node we care about.
1901 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1902 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1904 ExtVectorType *New = new (*this, TypeAlignment)
1905 ExtVectorType(vecType, NumElts, Canonical);
1906 VectorTypes.InsertNode(New, InsertPos);
1907 Types.push_back(New);
1908 return QualType(New, 0);
1912 ASTContext::getDependentSizedExtVectorType(QualType vecType,
1914 SourceLocation AttrLoc) const {
1915 llvm::FoldingSetNodeID ID;
1916 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1919 void *InsertPos = 0;
1920 DependentSizedExtVectorType *Canon
1921 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1922 DependentSizedExtVectorType *New;
1924 // We already have a canonical version of this array type; use it as
1925 // the canonical type for a newly-built type.
1926 New = new (*this, TypeAlignment)
1927 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1930 QualType CanonVecTy = getCanonicalType(vecType);
1931 if (CanonVecTy == vecType) {
1932 New = new (*this, TypeAlignment)
1933 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1936 DependentSizedExtVectorType *CanonCheck
1937 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1938 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1940 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1942 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1944 New = new (*this, TypeAlignment)
1945 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1949 Types.push_back(New);
1950 return QualType(New, 0);
1953 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1956 ASTContext::getFunctionNoProtoType(QualType ResultTy,
1957 const FunctionType::ExtInfo &Info) const {
1958 const CallingConv DefaultCC = Info.getCC();
1959 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1960 CC_X86StdCall : DefaultCC;
1961 // Unique functions, to guarantee there is only one function of a particular
1963 llvm::FoldingSetNodeID ID;
1964 FunctionNoProtoType::Profile(ID, ResultTy, Info);
1966 void *InsertPos = 0;
1967 if (FunctionNoProtoType *FT =
1968 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1969 return QualType(FT, 0);
1972 if (!ResultTy.isCanonical() ||
1973 getCanonicalCallConv(CallConv) != CallConv) {
1975 getFunctionNoProtoType(getCanonicalType(ResultTy),
1976 Info.withCallingConv(getCanonicalCallConv(CallConv)));
1978 // Get the new insert position for the node we care about.
1979 FunctionNoProtoType *NewIP =
1980 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1981 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1984 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
1985 FunctionNoProtoType *New = new (*this, TypeAlignment)
1986 FunctionNoProtoType(ResultTy, Canonical, newInfo);
1987 Types.push_back(New);
1988 FunctionNoProtoTypes.InsertNode(New, InsertPos);
1989 return QualType(New, 0);
1992 /// getFunctionType - Return a normal function type with a typed argument
1993 /// list. isVariadic indicates whether the argument list includes '...'.
1995 ASTContext::getFunctionType(QualType ResultTy,
1996 const QualType *ArgArray, unsigned NumArgs,
1997 const FunctionProtoType::ExtProtoInfo &EPI) const {
1998 // Unique functions, to guarantee there is only one function of a particular
2000 llvm::FoldingSetNodeID ID;
2001 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
2003 void *InsertPos = 0;
2004 if (FunctionProtoType *FTP =
2005 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2006 return QualType(FTP, 0);
2008 // Determine whether the type being created is already canonical or not.
2009 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
2010 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2011 if (!ArgArray[i].isCanonicalAsParam())
2012 isCanonical = false;
2014 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2015 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2016 CC_X86StdCall : DefaultCC;
2018 // If this type isn't canonical, get the canonical version of it.
2019 // The exception spec is not part of the canonical type.
2021 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2022 llvm::SmallVector<QualType, 16> CanonicalArgs;
2023 CanonicalArgs.reserve(NumArgs);
2024 for (unsigned i = 0; i != NumArgs; ++i)
2025 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2027 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2028 CanonicalEPI.ExceptionSpecType = EST_None;
2029 CanonicalEPI.NumExceptions = 0;
2030 CanonicalEPI.ExtInfo
2031 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2033 Canonical = getFunctionType(getCanonicalType(ResultTy),
2034 CanonicalArgs.data(), NumArgs,
2037 // Get the new insert position for the node we care about.
2038 FunctionProtoType *NewIP =
2039 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2040 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2043 // FunctionProtoType objects are allocated with extra bytes after them
2044 // for two variable size arrays (for parameter and exception types) at the
2045 // end of them. Instead of the exception types, there could be a noexcept
2046 // expression and a context pointer.
2047 size_t Size = sizeof(FunctionProtoType) +
2048 NumArgs * sizeof(QualType);
2049 if (EPI.ExceptionSpecType == EST_Dynamic)
2050 Size += EPI.NumExceptions * sizeof(QualType);
2051 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2052 Size += sizeof(Expr*);
2054 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2055 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2056 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2057 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
2058 Types.push_back(FTP);
2059 FunctionProtoTypes.InsertNode(FTP, InsertPos);
2060 return QualType(FTP, 0);
2064 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2065 if (!isa<CXXRecordDecl>(D)) return false;
2066 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2067 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2069 if (RD->getDescribedClassTemplate() &&
2070 !isa<ClassTemplateSpecializationDecl>(RD))
2076 /// getInjectedClassNameType - Return the unique reference to the
2077 /// injected class name type for the specified templated declaration.
2078 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2079 QualType TST) const {
2080 assert(NeedsInjectedClassNameType(Decl));
2081 if (Decl->TypeForDecl) {
2082 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2083 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
2084 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2085 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2086 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2089 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2090 Decl->TypeForDecl = newType;
2091 Types.push_back(newType);
2093 return QualType(Decl->TypeForDecl, 0);
2096 /// getTypeDeclType - Return the unique reference to the type for the
2097 /// specified type declaration.
2098 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2099 assert(Decl && "Passed null for Decl param");
2100 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2102 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2103 return getTypedefType(Typedef);
2105 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2106 "Template type parameter types are always available.");
2108 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2109 assert(!Record->getPreviousDeclaration() &&
2110 "struct/union has previous declaration");
2111 assert(!NeedsInjectedClassNameType(Record));
2112 return getRecordType(Record);
2113 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2114 assert(!Enum->getPreviousDeclaration() &&
2115 "enum has previous declaration");
2116 return getEnumType(Enum);
2117 } else if (const UnresolvedUsingTypenameDecl *Using =
2118 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2119 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2120 Decl->TypeForDecl = newType;
2121 Types.push_back(newType);
2123 llvm_unreachable("TypeDecl without a type?");
2125 return QualType(Decl->TypeForDecl, 0);
2128 /// getTypedefType - Return the unique reference to the type for the
2129 /// specified typedef name decl.
2131 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2132 QualType Canonical) const {
2133 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2135 if (Canonical.isNull())
2136 Canonical = getCanonicalType(Decl->getUnderlyingType());
2137 TypedefType *newType = new(*this, TypeAlignment)
2138 TypedefType(Type::Typedef, Decl, Canonical);
2139 Decl->TypeForDecl = newType;
2140 Types.push_back(newType);
2141 return QualType(newType, 0);
2144 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2145 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2147 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2148 if (PrevDecl->TypeForDecl)
2149 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2151 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2152 Decl->TypeForDecl = newType;
2153 Types.push_back(newType);
2154 return QualType(newType, 0);
2157 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2158 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2160 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2161 if (PrevDecl->TypeForDecl)
2162 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2164 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2165 Decl->TypeForDecl = newType;
2166 Types.push_back(newType);
2167 return QualType(newType, 0);
2170 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2171 QualType modifiedType,
2172 QualType equivalentType) {
2173 llvm::FoldingSetNodeID id;
2174 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2176 void *insertPos = 0;
2177 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2178 if (type) return QualType(type, 0);
2180 QualType canon = getCanonicalType(equivalentType);
2181 type = new (*this, TypeAlignment)
2182 AttributedType(canon, attrKind, modifiedType, equivalentType);
2184 Types.push_back(type);
2185 AttributedTypes.InsertNode(type, insertPos);
2187 return QualType(type, 0);
2191 /// \brief Retrieve a substitution-result type.
2193 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2194 QualType Replacement) const {
2195 assert(Replacement.isCanonical()
2196 && "replacement types must always be canonical");
2198 llvm::FoldingSetNodeID ID;
2199 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2200 void *InsertPos = 0;
2201 SubstTemplateTypeParmType *SubstParm
2202 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2205 SubstParm = new (*this, TypeAlignment)
2206 SubstTemplateTypeParmType(Parm, Replacement);
2207 Types.push_back(SubstParm);
2208 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2211 return QualType(SubstParm, 0);
2214 /// \brief Retrieve a
2215 QualType ASTContext::getSubstTemplateTypeParmPackType(
2216 const TemplateTypeParmType *Parm,
2217 const TemplateArgument &ArgPack) {
2219 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2220 PEnd = ArgPack.pack_end();
2222 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2223 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2227 llvm::FoldingSetNodeID ID;
2228 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2229 void *InsertPos = 0;
2230 if (SubstTemplateTypeParmPackType *SubstParm
2231 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2232 return QualType(SubstParm, 0);
2235 if (!Parm->isCanonicalUnqualified()) {
2236 Canon = getCanonicalType(QualType(Parm, 0));
2237 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2239 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2242 SubstTemplateTypeParmPackType *SubstParm
2243 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2245 Types.push_back(SubstParm);
2246 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2247 return QualType(SubstParm, 0);
2250 /// \brief Retrieve the template type parameter type for a template
2251 /// parameter or parameter pack with the given depth, index, and (optionally)
2253 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2255 TemplateTypeParmDecl *TTPDecl) const {
2256 llvm::FoldingSetNodeID ID;
2257 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2258 void *InsertPos = 0;
2259 TemplateTypeParmType *TypeParm
2260 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2263 return QualType(TypeParm, 0);
2266 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2267 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2269 TemplateTypeParmType *TypeCheck
2270 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2271 assert(!TypeCheck && "Template type parameter canonical type broken");
2274 TypeParm = new (*this, TypeAlignment)
2275 TemplateTypeParmType(Depth, Index, ParameterPack);
2277 Types.push_back(TypeParm);
2278 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2280 return QualType(TypeParm, 0);
2284 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2285 SourceLocation NameLoc,
2286 const TemplateArgumentListInfo &Args,
2287 QualType Underlying) const {
2288 assert(!Name.getAsDependentTemplateName() &&
2289 "No dependent template names here!");
2290 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2292 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2293 TemplateSpecializationTypeLoc TL
2294 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2295 TL.setTemplateNameLoc(NameLoc);
2296 TL.setLAngleLoc(Args.getLAngleLoc());
2297 TL.setRAngleLoc(Args.getRAngleLoc());
2298 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2299 TL.setArgLocInfo(i, Args[i].getLocInfo());
2304 ASTContext::getTemplateSpecializationType(TemplateName Template,
2305 const TemplateArgumentListInfo &Args,
2306 QualType Underlying) const {
2307 assert(!Template.getAsDependentTemplateName() &&
2308 "No dependent template names here!");
2310 unsigned NumArgs = Args.size();
2312 llvm::SmallVector<TemplateArgument, 4> ArgVec;
2313 ArgVec.reserve(NumArgs);
2314 for (unsigned i = 0; i != NumArgs; ++i)
2315 ArgVec.push_back(Args[i].getArgument());
2317 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2322 ASTContext::getTemplateSpecializationType(TemplateName Template,
2323 const TemplateArgument *Args,
2325 QualType Underlying) const {
2326 assert(!Template.getAsDependentTemplateName() &&
2327 "No dependent template names here!");
2328 // Look through qualified template names.
2329 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2330 Template = TemplateName(QTN->getTemplateDecl());
2333 Template.getAsTemplateDecl() &&
2334 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2337 if (!Underlying.isNull())
2338 CanonType = getCanonicalType(Underlying);
2340 assert(!isTypeAlias &&
2341 "Underlying type for template alias must be computed by caller");
2342 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2346 // Allocate the (non-canonical) template specialization type, but don't
2347 // try to unique it: these types typically have location information that
2348 // we don't unique and don't want to lose.
2349 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2350 sizeof(TemplateArgument) * NumArgs +
2351 (isTypeAlias ? sizeof(QualType) : 0),
2353 TemplateSpecializationType *Spec
2354 = new (Mem) TemplateSpecializationType(Template,
2357 isTypeAlias ? Underlying : QualType());
2359 Types.push_back(Spec);
2360 return QualType(Spec, 0);
2364 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2365 const TemplateArgument *Args,
2366 unsigned NumArgs) const {
2367 assert(!Template.getAsDependentTemplateName() &&
2368 "No dependent template names here!");
2369 assert((!Template.getAsTemplateDecl() ||
2370 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2371 "Underlying type for template alias must be computed by caller");
2373 // Look through qualified template names.
2374 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2375 Template = TemplateName(QTN->getTemplateDecl());
2377 // Build the canonical template specialization type.
2378 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2379 llvm::SmallVector<TemplateArgument, 4> CanonArgs;
2380 CanonArgs.reserve(NumArgs);
2381 for (unsigned I = 0; I != NumArgs; ++I)
2382 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2384 // Determine whether this canonical template specialization type already
2386 llvm::FoldingSetNodeID ID;
2387 TemplateSpecializationType::Profile(ID, CanonTemplate,
2388 CanonArgs.data(), NumArgs, *this);
2390 void *InsertPos = 0;
2391 TemplateSpecializationType *Spec
2392 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2395 // Allocate a new canonical template specialization type.
2396 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2397 sizeof(TemplateArgument) * NumArgs),
2399 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2400 CanonArgs.data(), NumArgs,
2401 QualType(), QualType());
2402 Types.push_back(Spec);
2403 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2406 assert(Spec->isDependentType() &&
2407 "Non-dependent template-id type must have a canonical type");
2408 return QualType(Spec, 0);
2412 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2413 NestedNameSpecifier *NNS,
2414 QualType NamedType) const {
2415 llvm::FoldingSetNodeID ID;
2416 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2418 void *InsertPos = 0;
2419 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2421 return QualType(T, 0);
2423 QualType Canon = NamedType;
2424 if (!Canon.isCanonical()) {
2425 Canon = getCanonicalType(NamedType);
2426 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2427 assert(!CheckT && "Elaborated canonical type broken");
2431 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2433 ElaboratedTypes.InsertNode(T, InsertPos);
2434 return QualType(T, 0);
2438 ASTContext::getParenType(QualType InnerType) const {
2439 llvm::FoldingSetNodeID ID;
2440 ParenType::Profile(ID, InnerType);
2442 void *InsertPos = 0;
2443 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2445 return QualType(T, 0);
2447 QualType Canon = InnerType;
2448 if (!Canon.isCanonical()) {
2449 Canon = getCanonicalType(InnerType);
2450 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2451 assert(!CheckT && "Paren canonical type broken");
2455 T = new (*this) ParenType(InnerType, Canon);
2457 ParenTypes.InsertNode(T, InsertPos);
2458 return QualType(T, 0);
2461 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2462 NestedNameSpecifier *NNS,
2463 const IdentifierInfo *Name,
2464 QualType Canon) const {
2465 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2467 if (Canon.isNull()) {
2468 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2469 ElaboratedTypeKeyword CanonKeyword = Keyword;
2470 if (Keyword == ETK_None)
2471 CanonKeyword = ETK_Typename;
2473 if (CanonNNS != NNS || CanonKeyword != Keyword)
2474 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2477 llvm::FoldingSetNodeID ID;
2478 DependentNameType::Profile(ID, Keyword, NNS, Name);
2480 void *InsertPos = 0;
2481 DependentNameType *T
2482 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2484 return QualType(T, 0);
2486 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2488 DependentNameTypes.InsertNode(T, InsertPos);
2489 return QualType(T, 0);
2493 ASTContext::getDependentTemplateSpecializationType(
2494 ElaboratedTypeKeyword Keyword,
2495 NestedNameSpecifier *NNS,
2496 const IdentifierInfo *Name,
2497 const TemplateArgumentListInfo &Args) const {
2498 // TODO: avoid this copy
2499 llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2500 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2501 ArgCopy.push_back(Args[I].getArgument());
2502 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2508 ASTContext::getDependentTemplateSpecializationType(
2509 ElaboratedTypeKeyword Keyword,
2510 NestedNameSpecifier *NNS,
2511 const IdentifierInfo *Name,
2513 const TemplateArgument *Args) const {
2514 assert((!NNS || NNS->isDependent()) &&
2515 "nested-name-specifier must be dependent");
2517 llvm::FoldingSetNodeID ID;
2518 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2519 Name, NumArgs, Args);
2521 void *InsertPos = 0;
2522 DependentTemplateSpecializationType *T
2523 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2525 return QualType(T, 0);
2527 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2529 ElaboratedTypeKeyword CanonKeyword = Keyword;
2530 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2532 bool AnyNonCanonArgs = false;
2533 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2534 for (unsigned I = 0; I != NumArgs; ++I) {
2535 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2536 if (!CanonArgs[I].structurallyEquals(Args[I]))
2537 AnyNonCanonArgs = true;
2541 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2542 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2546 // Find the insert position again.
2547 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2550 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2551 sizeof(TemplateArgument) * NumArgs),
2553 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2554 Name, NumArgs, Args, Canon);
2556 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2557 return QualType(T, 0);
2560 QualType ASTContext::getPackExpansionType(QualType Pattern,
2561 llvm::Optional<unsigned> NumExpansions) {
2562 llvm::FoldingSetNodeID ID;
2563 PackExpansionType::Profile(ID, Pattern, NumExpansions);
2565 assert(Pattern->containsUnexpandedParameterPack() &&
2566 "Pack expansions must expand one or more parameter packs");
2567 void *InsertPos = 0;
2568 PackExpansionType *T
2569 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2571 return QualType(T, 0);
2574 if (!Pattern.isCanonical()) {
2575 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2577 // Find the insert position again.
2578 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2581 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2583 PackExpansionTypes.InsertNode(T, InsertPos);
2584 return QualType(T, 0);
2587 /// CmpProtocolNames - Comparison predicate for sorting protocols
2589 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2590 const ObjCProtocolDecl *RHS) {
2591 return LHS->getDeclName() < RHS->getDeclName();
2594 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2595 unsigned NumProtocols) {
2596 if (NumProtocols == 0) return true;
2598 for (unsigned i = 1; i != NumProtocols; ++i)
2599 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2604 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2605 unsigned &NumProtocols) {
2606 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2608 // Sort protocols, keyed by name.
2609 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2611 // Remove duplicates.
2612 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2613 NumProtocols = ProtocolsEnd-Protocols;
2616 QualType ASTContext::getObjCObjectType(QualType BaseType,
2617 ObjCProtocolDecl * const *Protocols,
2618 unsigned NumProtocols) const {
2619 // If the base type is an interface and there aren't any protocols
2620 // to add, then the interface type will do just fine.
2621 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2624 // Look in the folding set for an existing type.
2625 llvm::FoldingSetNodeID ID;
2626 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2627 void *InsertPos = 0;
2628 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2629 return QualType(QT, 0);
2631 // Build the canonical type, which has the canonical base type and
2632 // a sorted-and-uniqued list of protocols.
2634 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2635 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2636 if (!ProtocolsSorted) {
2637 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2638 Protocols + NumProtocols);
2639 unsigned UniqueCount = NumProtocols;
2641 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2642 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2643 &Sorted[0], UniqueCount);
2645 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2646 Protocols, NumProtocols);
2649 // Regenerate InsertPos.
2650 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2653 unsigned Size = sizeof(ObjCObjectTypeImpl);
2654 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2655 void *Mem = Allocate(Size, TypeAlignment);
2656 ObjCObjectTypeImpl *T =
2657 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2660 ObjCObjectTypes.InsertNode(T, InsertPos);
2661 return QualType(T, 0);
2664 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2665 /// the given object type.
2666 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2667 llvm::FoldingSetNodeID ID;
2668 ObjCObjectPointerType::Profile(ID, ObjectT);
2670 void *InsertPos = 0;
2671 if (ObjCObjectPointerType *QT =
2672 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2673 return QualType(QT, 0);
2675 // Find the canonical object type.
2677 if (!ObjectT.isCanonical()) {
2678 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2680 // Regenerate InsertPos.
2681 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2685 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2686 ObjCObjectPointerType *QType =
2687 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2689 Types.push_back(QType);
2690 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2691 return QualType(QType, 0);
2694 /// getObjCInterfaceType - Return the unique reference to the type for the
2695 /// specified ObjC interface decl. The list of protocols is optional.
2696 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
2697 if (Decl->TypeForDecl)
2698 return QualType(Decl->TypeForDecl, 0);
2700 // FIXME: redeclarations?
2701 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2702 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2703 Decl->TypeForDecl = T;
2705 return QualType(T, 0);
2708 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2709 /// TypeOfExprType AST's (since expression's are never shared). For example,
2710 /// multiple declarations that refer to "typeof(x)" all contain different
2711 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
2712 /// on canonical type's (which are always unique).
2713 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2714 TypeOfExprType *toe;
2715 if (tofExpr->isTypeDependent()) {
2716 llvm::FoldingSetNodeID ID;
2717 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2719 void *InsertPos = 0;
2720 DependentTypeOfExprType *Canon
2721 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2723 // We already have a "canonical" version of an identical, dependent
2724 // typeof(expr) type. Use that as our canonical type.
2725 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2726 QualType((TypeOfExprType*)Canon, 0));
2729 // Build a new, canonical typeof(expr) type.
2731 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2732 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2736 QualType Canonical = getCanonicalType(tofExpr->getType());
2737 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2739 Types.push_back(toe);
2740 return QualType(toe, 0);
2743 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2744 /// TypeOfType AST's. The only motivation to unique these nodes would be
2745 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2746 /// an issue. This doesn't effect the type checker, since it operates
2747 /// on canonical type's (which are always unique).
2748 QualType ASTContext::getTypeOfType(QualType tofType) const {
2749 QualType Canonical = getCanonicalType(tofType);
2750 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2751 Types.push_back(tot);
2752 return QualType(tot, 0);
2755 /// getDecltypeForExpr - Given an expr, will return the decltype for that
2756 /// expression, according to the rules in C++0x [dcl.type.simple]p4
2757 static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
2758 if (e->isTypeDependent())
2759 return Context.DependentTy;
2761 // If e is an id expression or a class member access, decltype(e) is defined
2762 // as the type of the entity named by e.
2763 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2764 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2765 return VD->getType();
2767 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2768 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2769 return FD->getType();
2771 // If e is a function call or an invocation of an overloaded operator,
2772 // (parentheses around e are ignored), decltype(e) is defined as the
2773 // return type of that function.
2774 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2775 return CE->getCallReturnType();
2777 QualType T = e->getType();
2779 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2780 // defined as T&, otherwise decltype(e) is defined as T.
2782 T = Context.getLValueReferenceType(T);
2787 /// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2788 /// DecltypeType AST's. The only motivation to unique these nodes would be
2789 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2790 /// an issue. This doesn't effect the type checker, since it operates
2791 /// on canonical type's (which are always unique).
2792 QualType ASTContext::getDecltypeType(Expr *e) const {
2794 if (e->isTypeDependent()) {
2795 llvm::FoldingSetNodeID ID;
2796 DependentDecltypeType::Profile(ID, *this, e);
2798 void *InsertPos = 0;
2799 DependentDecltypeType *Canon
2800 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2802 // We already have a "canonical" version of an equivalent, dependent
2803 // decltype type. Use that as our canonical type.
2804 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2805 QualType((DecltypeType*)Canon, 0));
2808 // Build a new, canonical typeof(expr) type.
2809 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2810 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2814 QualType T = getDecltypeForExpr(e, *this);
2815 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2817 Types.push_back(dt);
2818 return QualType(dt, 0);
2821 /// getUnaryTransformationType - We don't unique these, since the memory
2822 /// savings are minimal and these are rare.
2823 QualType ASTContext::getUnaryTransformType(QualType BaseType,
2824 QualType UnderlyingType,
2825 UnaryTransformType::UTTKind Kind)
2827 UnaryTransformType *Ty =
2828 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2830 UnderlyingType->isDependentType() ?
2831 QualType() : UnderlyingType);
2832 Types.push_back(Ty);
2833 return QualType(Ty, 0);
2836 /// getAutoType - We only unique auto types after they've been deduced.
2837 QualType ASTContext::getAutoType(QualType DeducedType) const {
2838 void *InsertPos = 0;
2839 if (!DeducedType.isNull()) {
2840 // Look in the folding set for an existing type.
2841 llvm::FoldingSetNodeID ID;
2842 AutoType::Profile(ID, DeducedType);
2843 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2844 return QualType(AT, 0);
2847 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2848 Types.push_back(AT);
2850 AutoTypes.InsertNode(AT, InsertPos);
2851 return QualType(AT, 0);
2854 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
2855 QualType ASTContext::getAutoDeductType() const {
2856 if (AutoDeductTy.isNull())
2857 AutoDeductTy = getAutoType(QualType());
2858 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2859 return AutoDeductTy;
2862 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2863 QualType ASTContext::getAutoRRefDeductType() const {
2864 if (AutoRRefDeductTy.isNull())
2865 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2866 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2867 return AutoRRefDeductTy;
2870 /// getTagDeclType - Return the unique reference to the type for the
2871 /// specified TagDecl (struct/union/class/enum) decl.
2872 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
2874 // FIXME: What is the design on getTagDeclType when it requires casting
2875 // away const? mutable?
2876 return getTypeDeclType(const_cast<TagDecl*>(Decl));
2879 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2880 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2881 /// needs to agree with the definition in <stddef.h>.
2882 CanQualType ASTContext::getSizeType() const {
2883 return getFromTargetType(Target.getSizeType());
2886 /// getSignedWCharType - Return the type of "signed wchar_t".
2887 /// Used when in C++, as a GCC extension.
2888 QualType ASTContext::getSignedWCharType() const {
2889 // FIXME: derive from "Target" ?
2893 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2894 /// Used when in C++, as a GCC extension.
2895 QualType ASTContext::getUnsignedWCharType() const {
2896 // FIXME: derive from "Target" ?
2897 return UnsignedIntTy;
2900 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2901 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2902 QualType ASTContext::getPointerDiffType() const {
2903 return getFromTargetType(Target.getPtrDiffType(0));
2906 //===----------------------------------------------------------------------===//
2908 //===----------------------------------------------------------------------===//
2910 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
2911 // Push qualifiers into arrays, and then discard any remaining
2913 T = getCanonicalType(T);
2914 T = getVariableArrayDecayedType(T);
2915 const Type *Ty = T.getTypePtr();
2917 if (isa<ArrayType>(Ty)) {
2918 Result = getArrayDecayedType(QualType(Ty,0));
2919 } else if (isa<FunctionType>(Ty)) {
2920 Result = getPointerType(QualType(Ty, 0));
2922 Result = QualType(Ty, 0);
2925 return CanQualType::CreateUnsafe(Result);
2929 QualType ASTContext::getUnqualifiedArrayType(QualType type,
2930 Qualifiers &quals) {
2931 SplitQualType splitType = type.getSplitUnqualifiedType();
2933 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2934 // the unqualified desugared type and then drops it on the floor.
2935 // We then have to strip that sugar back off with
2936 // getUnqualifiedDesugaredType(), which is silly.
2937 const ArrayType *AT =
2938 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2940 // If we don't have an array, just use the results in splitType.
2942 quals = splitType.second;
2943 return QualType(splitType.first, 0);
2946 // Otherwise, recurse on the array's element type.
2947 QualType elementType = AT->getElementType();
2948 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2950 // If that didn't change the element type, AT has no qualifiers, so we
2951 // can just use the results in splitType.
2952 if (elementType == unqualElementType) {
2953 assert(quals.empty()); // from the recursive call
2954 quals = splitType.second;
2955 return QualType(splitType.first, 0);
2958 // Otherwise, add in the qualifiers from the outermost type, then
2959 // build the type back up.
2960 quals.addConsistentQualifiers(splitType.second);
2962 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
2963 return getConstantArrayType(unqualElementType, CAT->getSize(),
2964 CAT->getSizeModifier(), 0);
2967 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
2968 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
2971 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2972 return getVariableArrayType(unqualElementType,
2974 VAT->getSizeModifier(),
2975 VAT->getIndexTypeCVRQualifiers(),
2976 VAT->getBracketsRange());
2979 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
2980 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
2981 DSAT->getSizeModifier(), 0,
2985 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2986 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2987 /// they point to and return true. If T1 and T2 aren't pointer types
2988 /// or pointer-to-member types, or if they are not similar at this
2989 /// level, returns false and leaves T1 and T2 unchanged. Top-level
2990 /// qualifiers on T1 and T2 are ignored. This function will typically
2991 /// be called in a loop that successively "unwraps" pointer and
2992 /// pointer-to-member types to compare them at each level.
2993 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2994 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2995 *T2PtrType = T2->getAs<PointerType>();
2996 if (T1PtrType && T2PtrType) {
2997 T1 = T1PtrType->getPointeeType();
2998 T2 = T2PtrType->getPointeeType();
3002 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3003 *T2MPType = T2->getAs<MemberPointerType>();
3004 if (T1MPType && T2MPType &&
3005 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3006 QualType(T2MPType->getClass(), 0))) {
3007 T1 = T1MPType->getPointeeType();
3008 T2 = T2MPType->getPointeeType();
3012 if (getLangOptions().ObjC1) {
3013 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3014 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3015 if (T1OPType && T2OPType) {
3016 T1 = T1OPType->getPointeeType();
3017 T2 = T2OPType->getPointeeType();
3022 // FIXME: Block pointers, too?
3028 ASTContext::getNameForTemplate(TemplateName Name,
3029 SourceLocation NameLoc) const {
3030 if (TemplateDecl *TD = Name.getAsTemplateDecl())
3031 // DNInfo work in progress: CHECKME: what about DNLoc?
3032 return DeclarationNameInfo(TD->getDeclName(), NameLoc);
3034 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
3035 DeclarationName DName;
3036 if (DTN->isIdentifier()) {
3037 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3038 return DeclarationNameInfo(DName, NameLoc);
3040 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3041 // DNInfo work in progress: FIXME: source locations?
3042 DeclarationNameLoc DNLoc;
3043 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3044 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3045 return DeclarationNameInfo(DName, NameLoc, DNLoc);
3049 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3051 // DNInfo work in progress: CHECKME: what about DNLoc?
3052 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3055 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3056 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3057 if (TemplateTemplateParmDecl *TTP
3058 = dyn_cast<TemplateTemplateParmDecl>(Template))
3059 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3061 // The canonical template name is the canonical template declaration.
3062 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3065 if (SubstTemplateTemplateParmPackStorage *SubstPack
3066 = Name.getAsSubstTemplateTemplateParmPack()) {
3067 TemplateTemplateParmDecl *CanonParam
3068 = getCanonicalTemplateTemplateParmDecl(SubstPack->getParameterPack());
3069 TemplateArgument CanonArgPack
3070 = getCanonicalTemplateArgument(SubstPack->getArgumentPack());
3071 return getSubstTemplateTemplateParmPack(CanonParam, CanonArgPack);
3074 assert(!Name.getAsOverloadedTemplate());
3076 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3077 assert(DTN && "Non-dependent template names must refer to template decls.");
3078 return DTN->CanonicalTemplateName;
3081 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3082 X = getCanonicalTemplateName(X);
3083 Y = getCanonicalTemplateName(Y);
3084 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3088 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3089 switch (Arg.getKind()) {
3090 case TemplateArgument::Null:
3093 case TemplateArgument::Expression:
3096 case TemplateArgument::Declaration:
3097 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
3099 case TemplateArgument::Template:
3100 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3102 case TemplateArgument::TemplateExpansion:
3103 return TemplateArgument(getCanonicalTemplateName(
3104 Arg.getAsTemplateOrTemplatePattern()),
3105 Arg.getNumTemplateExpansions());
3107 case TemplateArgument::Integral:
3108 return TemplateArgument(*Arg.getAsIntegral(),
3109 getCanonicalType(Arg.getIntegralType()));
3111 case TemplateArgument::Type:
3112 return TemplateArgument(getCanonicalType(Arg.getAsType()));
3114 case TemplateArgument::Pack: {
3115 if (Arg.pack_size() == 0)
3118 TemplateArgument *CanonArgs
3119 = new (*this) TemplateArgument[Arg.pack_size()];
3121 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3122 AEnd = Arg.pack_end();
3123 A != AEnd; (void)++A, ++Idx)
3124 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3126 return TemplateArgument(CanonArgs, Arg.pack_size());
3130 // Silence GCC warning
3131 assert(false && "Unhandled template argument kind");
3132 return TemplateArgument();
3135 NestedNameSpecifier *
3136 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3140 switch (NNS->getKind()) {
3141 case NestedNameSpecifier::Identifier:
3142 // Canonicalize the prefix but keep the identifier the same.
3143 return NestedNameSpecifier::Create(*this,
3144 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3145 NNS->getAsIdentifier());
3147 case NestedNameSpecifier::Namespace:
3148 // A namespace is canonical; build a nested-name-specifier with
3149 // this namespace and no prefix.
3150 return NestedNameSpecifier::Create(*this, 0,
3151 NNS->getAsNamespace()->getOriginalNamespace());
3153 case NestedNameSpecifier::NamespaceAlias:
3154 // A namespace is canonical; build a nested-name-specifier with
3155 // this namespace and no prefix.
3156 return NestedNameSpecifier::Create(*this, 0,
3157 NNS->getAsNamespaceAlias()->getNamespace()
3158 ->getOriginalNamespace());
3160 case NestedNameSpecifier::TypeSpec:
3161 case NestedNameSpecifier::TypeSpecWithTemplate: {
3162 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3164 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3165 // break it apart into its prefix and identifier, then reconsititute those
3166 // as the canonical nested-name-specifier. This is required to canonicalize
3167 // a dependent nested-name-specifier involving typedefs of dependent-name
3169 // typedef typename T::type T1;
3170 // typedef typename T1::type T2;
3171 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3172 NestedNameSpecifier *Prefix
3173 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3174 return NestedNameSpecifier::Create(*this, Prefix,
3175 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3178 // Do the same thing as above, but with dependent-named specializations.
3179 if (const DependentTemplateSpecializationType *DTST
3180 = T->getAs<DependentTemplateSpecializationType>()) {
3181 NestedNameSpecifier *Prefix
3182 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
3184 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3185 Prefix, DTST->getIdentifier(),
3188 T = getCanonicalType(T);
3191 return NestedNameSpecifier::Create(*this, 0, false,
3192 const_cast<Type*>(T.getTypePtr()));
3195 case NestedNameSpecifier::Global:
3196 // The global specifier is canonical and unique.
3200 // Required to silence a GCC warning
3205 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3206 // Handle the non-qualified case efficiently.
3207 if (!T.hasLocalQualifiers()) {
3208 // Handle the common positive case fast.
3209 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3213 // Handle the common negative case fast.
3214 if (!isa<ArrayType>(T.getCanonicalType()))
3217 // Apply any qualifiers from the array type to the element type. This
3218 // implements C99 6.7.3p8: "If the specification of an array type includes
3219 // any type qualifiers, the element type is so qualified, not the array type."
3221 // If we get here, we either have type qualifiers on the type, or we have
3222 // sugar such as a typedef in the way. If we have type qualifiers on the type
3223 // we must propagate them down into the element type.
3225 SplitQualType split = T.getSplitDesugaredType();
3226 Qualifiers qs = split.second;
3228 // If we have a simple case, just return now.
3229 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3230 if (ATy == 0 || qs.empty())
3233 // Otherwise, we have an array and we have qualifiers on it. Push the
3234 // qualifiers into the array element type and return a new array type.
3235 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3237 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3238 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3239 CAT->getSizeModifier(),
3240 CAT->getIndexTypeCVRQualifiers()));
3241 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3242 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3243 IAT->getSizeModifier(),
3244 IAT->getIndexTypeCVRQualifiers()));
3246 if (const DependentSizedArrayType *DSAT
3247 = dyn_cast<DependentSizedArrayType>(ATy))
3248 return cast<ArrayType>(
3249 getDependentSizedArrayType(NewEltTy,
3250 DSAT->getSizeExpr(),
3251 DSAT->getSizeModifier(),
3252 DSAT->getIndexTypeCVRQualifiers(),
3253 DSAT->getBracketsRange()));
3255 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3256 return cast<ArrayType>(getVariableArrayType(NewEltTy,
3258 VAT->getSizeModifier(),
3259 VAT->getIndexTypeCVRQualifiers(),
3260 VAT->getBracketsRange()));
3263 /// getArrayDecayedType - Return the properly qualified result of decaying the
3264 /// specified array type to a pointer. This operation is non-trivial when
3265 /// handling typedefs etc. The canonical type of "T" must be an array type,
3266 /// this returns a pointer to a properly qualified element of the array.
3268 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3269 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3270 // Get the element type with 'getAsArrayType' so that we don't lose any
3271 // typedefs in the element type of the array. This also handles propagation
3272 // of type qualifiers from the array type into the element type if present
3274 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3275 assert(PrettyArrayType && "Not an array type!");
3277 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3279 // int x[restrict 4] -> int *restrict
3280 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3283 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3284 return getBaseElementType(array->getElementType());
3287 QualType ASTContext::getBaseElementType(QualType type) const {
3290 SplitQualType split = type.getSplitDesugaredType();
3291 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3294 type = array->getElementType();
3295 qs.addConsistentQualifiers(split.second);
3298 return getQualifiedType(type, qs);
3301 /// getConstantArrayElementCount - Returns number of constant array elements.
3303 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3304 uint64_t ElementCount = 1;
3306 ElementCount *= CA->getSize().getZExtValue();
3307 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3309 return ElementCount;
3312 /// getFloatingRank - Return a relative rank for floating point types.
3313 /// This routine will assert if passed a built-in type that isn't a float.
3314 static FloatingRank getFloatingRank(QualType T) {
3315 if (const ComplexType *CT = T->getAs<ComplexType>())
3316 return getFloatingRank(CT->getElementType());
3318 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3319 switch (T->getAs<BuiltinType>()->getKind()) {
3320 default: assert(0 && "getFloatingRank(): not a floating type");
3321 case BuiltinType::Float: return FloatRank;
3322 case BuiltinType::Double: return DoubleRank;
3323 case BuiltinType::LongDouble: return LongDoubleRank;
3327 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3328 /// point or a complex type (based on typeDomain/typeSize).
3329 /// 'typeDomain' is a real floating point or complex type.
3330 /// 'typeSize' is a real floating point or complex type.
3331 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3332 QualType Domain) const {
3333 FloatingRank EltRank = getFloatingRank(Size);
3334 if (Domain->isComplexType()) {
3336 default: assert(0 && "getFloatingRank(): illegal value for rank");
3337 case FloatRank: return FloatComplexTy;
3338 case DoubleRank: return DoubleComplexTy;
3339 case LongDoubleRank: return LongDoubleComplexTy;
3343 assert(Domain->isRealFloatingType() && "Unknown domain!");
3345 default: assert(0 && "getFloatingRank(): illegal value for rank");
3346 case FloatRank: return FloatTy;
3347 case DoubleRank: return DoubleTy;
3348 case LongDoubleRank: return LongDoubleTy;
3352 /// getFloatingTypeOrder - Compare the rank of the two specified floating
3353 /// point types, ignoring the domain of the type (i.e. 'double' ==
3354 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
3355 /// LHS < RHS, return -1.
3356 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3357 FloatingRank LHSR = getFloatingRank(LHS);
3358 FloatingRank RHSR = getFloatingRank(RHS);
3367 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3368 /// routine will assert if passed a built-in type that isn't an integer or enum,
3369 /// or if it is not canonicalized.
3370 unsigned ASTContext::getIntegerRank(const Type *T) const {
3371 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3372 if (const EnumType* ET = dyn_cast<EnumType>(T))
3373 T = ET->getDecl()->getPromotionType().getTypePtr();
3375 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3376 T->isSpecificBuiltinType(BuiltinType::WChar_U))
3377 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3379 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3380 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3382 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3383 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3385 switch (cast<BuiltinType>(T)->getKind()) {
3386 default: assert(0 && "getIntegerRank(): not a built-in integer");
3387 case BuiltinType::Bool:
3388 return 1 + (getIntWidth(BoolTy) << 3);
3389 case BuiltinType::Char_S:
3390 case BuiltinType::Char_U:
3391 case BuiltinType::SChar:
3392 case BuiltinType::UChar:
3393 return 2 + (getIntWidth(CharTy) << 3);
3394 case BuiltinType::Short:
3395 case BuiltinType::UShort:
3396 return 3 + (getIntWidth(ShortTy) << 3);
3397 case BuiltinType::Int:
3398 case BuiltinType::UInt:
3399 return 4 + (getIntWidth(IntTy) << 3);
3400 case BuiltinType::Long:
3401 case BuiltinType::ULong:
3402 return 5 + (getIntWidth(LongTy) << 3);
3403 case BuiltinType::LongLong:
3404 case BuiltinType::ULongLong:
3405 return 6 + (getIntWidth(LongLongTy) << 3);
3406 case BuiltinType::Int128:
3407 case BuiltinType::UInt128:
3408 return 7 + (getIntWidth(Int128Ty) << 3);
3412 /// \brief Whether this is a promotable bitfield reference according
3413 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3415 /// \returns the type this bit-field will promote to, or NULL if no
3416 /// promotion occurs.
3417 QualType ASTContext::isPromotableBitField(Expr *E) const {
3418 if (E->isTypeDependent() || E->isValueDependent())
3421 FieldDecl *Field = E->getBitField();
3425 QualType FT = Field->getType();
3427 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3428 uint64_t BitWidth = BitWidthAP.getZExtValue();
3429 uint64_t IntSize = getTypeSize(IntTy);
3430 // GCC extension compatibility: if the bit-field size is less than or equal
3431 // to the size of int, it gets promoted no matter what its type is.
3432 // For instance, unsigned long bf : 4 gets promoted to signed int.
3433 if (BitWidth < IntSize)
3436 if (BitWidth == IntSize)
3437 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3439 // Types bigger than int are not subject to promotions, and therefore act
3440 // like the base type.
3441 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3446 /// getPromotedIntegerType - Returns the type that Promotable will
3447 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3449 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3450 assert(!Promotable.isNull());
3451 assert(Promotable->isPromotableIntegerType());
3452 if (const EnumType *ET = Promotable->getAs<EnumType>())
3453 return ET->getDecl()->getPromotionType();
3454 if (Promotable->isSignedIntegerType())
3456 uint64_t PromotableSize = getTypeSize(Promotable);
3457 uint64_t IntSize = getTypeSize(IntTy);
3458 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3459 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3462 /// getIntegerTypeOrder - Returns the highest ranked integer type:
3463 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
3464 /// LHS < RHS, return -1.
3465 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3466 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3467 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3468 if (LHSC == RHSC) return 0;
3470 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3471 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3473 unsigned LHSRank = getIntegerRank(LHSC);
3474 unsigned RHSRank = getIntegerRank(RHSC);
3476 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3477 if (LHSRank == RHSRank) return 0;
3478 return LHSRank > RHSRank ? 1 : -1;
3481 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3483 // If the unsigned [LHS] type is larger, return it.
3484 if (LHSRank >= RHSRank)
3487 // If the signed type can represent all values of the unsigned type, it
3488 // wins. Because we are dealing with 2's complement and types that are
3489 // powers of two larger than each other, this is always safe.
3493 // If the unsigned [RHS] type is larger, return it.
3494 if (RHSRank >= LHSRank)
3497 // If the signed type can represent all values of the unsigned type, it
3498 // wins. Because we are dealing with 2's complement and types that are
3499 // powers of two larger than each other, this is always safe.
3504 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3505 DeclContext *DC, IdentifierInfo *Id) {
3507 if (Ctx.getLangOptions().CPlusPlus)
3508 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3510 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3513 // getCFConstantStringType - Return the type used for constant CFStrings.
3514 QualType ASTContext::getCFConstantStringType() const {
3515 if (!CFConstantStringTypeDecl) {
3516 CFConstantStringTypeDecl =
3517 CreateRecordDecl(*this, TTK_Struct, TUDecl,
3518 &Idents.get("NSConstantString"));
3519 CFConstantStringTypeDecl->startDefinition();
3521 QualType FieldTypes[4];
3524 FieldTypes[0] = getPointerType(IntTy.withConst());
3526 FieldTypes[1] = IntTy;
3528 FieldTypes[2] = getPointerType(CharTy.withConst());
3530 FieldTypes[3] = LongTy;
3533 for (unsigned i = 0; i < 4; ++i) {
3534 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3536 SourceLocation(), 0,
3537 FieldTypes[i], /*TInfo=*/0,
3541 Field->setAccess(AS_public);
3542 CFConstantStringTypeDecl->addDecl(Field);
3545 CFConstantStringTypeDecl->completeDefinition();
3548 return getTagDeclType(CFConstantStringTypeDecl);
3551 void ASTContext::setCFConstantStringType(QualType T) {
3552 const RecordType *Rec = T->getAs<RecordType>();
3553 assert(Rec && "Invalid CFConstantStringType");
3554 CFConstantStringTypeDecl = Rec->getDecl();
3557 // getNSConstantStringType - Return the type used for constant NSStrings.
3558 QualType ASTContext::getNSConstantStringType() const {
3559 if (!NSConstantStringTypeDecl) {
3560 NSConstantStringTypeDecl =
3561 CreateRecordDecl(*this, TTK_Struct, TUDecl,
3562 &Idents.get("__builtin_NSString"));
3563 NSConstantStringTypeDecl->startDefinition();
3565 QualType FieldTypes[3];
3568 FieldTypes[0] = getPointerType(IntTy.withConst());
3570 FieldTypes[1] = getPointerType(CharTy.withConst());
3571 // unsigned int length;
3572 FieldTypes[2] = UnsignedIntTy;
3575 for (unsigned i = 0; i < 3; ++i) {
3576 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
3578 SourceLocation(), 0,
3579 FieldTypes[i], /*TInfo=*/0,
3583 Field->setAccess(AS_public);
3584 NSConstantStringTypeDecl->addDecl(Field);
3587 NSConstantStringTypeDecl->completeDefinition();
3590 return getTagDeclType(NSConstantStringTypeDecl);
3593 void ASTContext::setNSConstantStringType(QualType T) {
3594 const RecordType *Rec = T->getAs<RecordType>();
3595 assert(Rec && "Invalid NSConstantStringType");
3596 NSConstantStringTypeDecl = Rec->getDecl();
3599 QualType ASTContext::getObjCFastEnumerationStateType() const {
3600 if (!ObjCFastEnumerationStateTypeDecl) {
3601 ObjCFastEnumerationStateTypeDecl =
3602 CreateRecordDecl(*this, TTK_Struct, TUDecl,
3603 &Idents.get("__objcFastEnumerationState"));
3604 ObjCFastEnumerationStateTypeDecl->startDefinition();
3606 QualType FieldTypes[] = {
3608 getPointerType(ObjCIdTypedefType),
3609 getPointerType(UnsignedLongTy),
3610 getConstantArrayType(UnsignedLongTy,
3611 llvm::APInt(32, 5), ArrayType::Normal, 0)
3614 for (size_t i = 0; i < 4; ++i) {
3615 FieldDecl *Field = FieldDecl::Create(*this,
3616 ObjCFastEnumerationStateTypeDecl,
3618 SourceLocation(), 0,
3619 FieldTypes[i], /*TInfo=*/0,
3623 Field->setAccess(AS_public);
3624 ObjCFastEnumerationStateTypeDecl->addDecl(Field);
3627 ObjCFastEnumerationStateTypeDecl->completeDefinition();
3630 return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3633 QualType ASTContext::getBlockDescriptorType() const {
3634 if (BlockDescriptorType)
3635 return getTagDeclType(BlockDescriptorType);
3638 // FIXME: Needs the FlagAppleBlock bit.
3639 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3640 &Idents.get("__block_descriptor"));
3641 T->startDefinition();
3643 QualType FieldTypes[] = {
3648 const char *FieldNames[] = {
3653 for (size_t i = 0; i < 2; ++i) {
3654 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3656 &Idents.get(FieldNames[i]),
3657 FieldTypes[i], /*TInfo=*/0,
3661 Field->setAccess(AS_public);
3665 T->completeDefinition();
3667 BlockDescriptorType = T;
3669 return getTagDeclType(BlockDescriptorType);
3672 void ASTContext::setBlockDescriptorType(QualType T) {
3673 const RecordType *Rec = T->getAs<RecordType>();
3674 assert(Rec && "Invalid BlockDescriptorType");
3675 BlockDescriptorType = Rec->getDecl();
3678 QualType ASTContext::getBlockDescriptorExtendedType() const {
3679 if (BlockDescriptorExtendedType)
3680 return getTagDeclType(BlockDescriptorExtendedType);
3683 // FIXME: Needs the FlagAppleBlock bit.
3684 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3685 &Idents.get("__block_descriptor_withcopydispose"));
3686 T->startDefinition();
3688 QualType FieldTypes[] = {
3691 getPointerType(VoidPtrTy),
3692 getPointerType(VoidPtrTy)
3695 const char *FieldNames[] = {
3702 for (size_t i = 0; i < 4; ++i) {
3703 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3705 &Idents.get(FieldNames[i]),
3706 FieldTypes[i], /*TInfo=*/0,
3710 Field->setAccess(AS_public);
3714 T->completeDefinition();
3716 BlockDescriptorExtendedType = T;
3718 return getTagDeclType(BlockDescriptorExtendedType);
3721 void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3722 const RecordType *Rec = T->getAs<RecordType>();
3723 assert(Rec && "Invalid BlockDescriptorType");
3724 BlockDescriptorExtendedType = Rec->getDecl();
3727 bool ASTContext::BlockRequiresCopying(QualType Ty) const {
3728 if (Ty->isBlockPointerType())
3730 if (isObjCNSObjectType(Ty))
3732 if (Ty->isObjCObjectPointerType())
3734 if (getLangOptions().CPlusPlus) {
3735 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3736 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3737 return RD->hasConstCopyConstructor();
3745 ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) const {
3746 // type = struct __Block_byref_1_X {
3748 // struct __Block_byref_1_X *__forwarding;
3749 // unsigned int __flags;
3750 // unsigned int __size;
3751 // void *__copy_helper; // as needed
3752 // void *__destroy_help // as needed
3756 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3759 llvm::SmallString<36> Name;
3760 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3761 ++UniqueBlockByRefTypeID << '_' << DeclName;
3763 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
3764 T->startDefinition();
3765 QualType Int32Ty = IntTy;
3766 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3767 QualType FieldTypes[] = {
3768 getPointerType(VoidPtrTy),
3769 getPointerType(getTagDeclType(T)),
3772 getPointerType(VoidPtrTy),
3773 getPointerType(VoidPtrTy),
3777 llvm::StringRef FieldNames[] = {
3787 for (size_t i = 0; i < 7; ++i) {
3788 if (!HasCopyAndDispose && i >=4 && i <= 5)
3790 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3792 &Idents.get(FieldNames[i]),
3793 FieldTypes[i], /*TInfo=*/0,
3794 /*BitWidth=*/0, /*Mutable=*/false,
3796 Field->setAccess(AS_public);
3800 T->completeDefinition();
3802 return getPointerType(getTagDeclType(T));
3805 void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3806 const RecordType *Rec = T->getAs<RecordType>();
3807 assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3808 ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3811 // This returns true if a type has been typedefed to BOOL:
3812 // typedef <type> BOOL;
3813 static bool isTypeTypedefedAsBOOL(QualType T) {
3814 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3815 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3816 return II->isStr("BOOL");
3821 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
3823 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
3824 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3825 return CharUnits::Zero();
3827 CharUnits sz = getTypeSizeInChars(type);
3829 // Make all integer and enum types at least as large as an int
3830 if (sz.isPositive() && type->isIntegralOrEnumerationType())
3831 sz = std::max(sz, getTypeSizeInChars(IntTy));
3832 // Treat arrays as pointers, since that's how they're passed in.
3833 else if (type->isArrayType())
3834 sz = getTypeSizeInChars(VoidPtrTy);
3839 std::string charUnitsToString(const CharUnits &CU) {
3840 return llvm::itostr(CU.getQuantity());
3843 /// getObjCEncodingForBlock - Return the encoded type for this block
3845 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3848 const BlockDecl *Decl = Expr->getBlockDecl();
3850 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3851 // Encode result type.
3852 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
3853 // Compute size of all parameters.
3854 // Start with computing size of a pointer in number of bytes.
3855 // FIXME: There might(should) be a better way of doing this computation!
3857 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3858 CharUnits ParmOffset = PtrSize;
3859 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
3860 E = Decl->param_end(); PI != E; ++PI) {
3861 QualType PType = (*PI)->getType();
3862 CharUnits sz = getObjCEncodingTypeSize(PType);
3863 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3866 // Size of the argument frame
3867 S += charUnitsToString(ParmOffset);
3868 // Block pointer and offset.
3870 ParmOffset = PtrSize;
3873 ParmOffset = PtrSize;
3874 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3875 Decl->param_end(); PI != E; ++PI) {
3876 ParmVarDecl *PVDecl = *PI;
3877 QualType PType = PVDecl->getOriginalType();
3878 if (const ArrayType *AT =
3879 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3880 // Use array's original type only if it has known number of
3882 if (!isa<ConstantArrayType>(AT))
3883 PType = PVDecl->getType();
3884 } else if (PType->isFunctionType())
3885 PType = PVDecl->getType();
3886 getObjCEncodingForType(PType, S);
3887 S += charUnitsToString(ParmOffset);
3888 ParmOffset += getObjCEncodingTypeSize(PType);
3894 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
3896 // Encode result type.
3897 getObjCEncodingForType(Decl->getResultType(), S);
3898 CharUnits ParmOffset;
3899 // Compute size of all parameters.
3900 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3901 E = Decl->param_end(); PI != E; ++PI) {
3902 QualType PType = (*PI)->getType();
3903 CharUnits sz = getObjCEncodingTypeSize(PType);
3907 assert (sz.isPositive() &&
3908 "getObjCEncodingForFunctionDecl - Incomplete param type");
3911 S += charUnitsToString(ParmOffset);
3912 ParmOffset = CharUnits::Zero();
3915 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3916 E = Decl->param_end(); PI != E; ++PI) {
3917 ParmVarDecl *PVDecl = *PI;
3918 QualType PType = PVDecl->getOriginalType();
3919 if (const ArrayType *AT =
3920 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3921 // Use array's original type only if it has known number of
3923 if (!isa<ConstantArrayType>(AT))
3924 PType = PVDecl->getType();
3925 } else if (PType->isFunctionType())
3926 PType = PVDecl->getType();
3927 getObjCEncodingForType(PType, S);
3928 S += charUnitsToString(ParmOffset);
3929 ParmOffset += getObjCEncodingTypeSize(PType);
3935 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
3937 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3938 std::string& S) const {
3939 // FIXME: This is not very efficient.
3940 // Encode type qualifer, 'in', 'inout', etc. for the return type.
3941 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3942 // Encode result type.
3943 getObjCEncodingForType(Decl->getResultType(), S);
3944 // Compute size of all parameters.
3945 // Start with computing size of a pointer in number of bytes.
3946 // FIXME: There might(should) be a better way of doing this computation!
3948 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3949 // The first two arguments (self and _cmd) are pointers; account for
3951 CharUnits ParmOffset = 2 * PtrSize;
3952 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3953 E = Decl->sel_param_end(); PI != E; ++PI) {
3954 QualType PType = (*PI)->getType();
3955 CharUnits sz = getObjCEncodingTypeSize(PType);
3959 assert (sz.isPositive() &&
3960 "getObjCEncodingForMethodDecl - Incomplete param type");
3963 S += charUnitsToString(ParmOffset);
3965 S += charUnitsToString(PtrSize);
3968 ParmOffset = 2 * PtrSize;
3969 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3970 E = Decl->sel_param_end(); PI != E; ++PI) {
3971 ParmVarDecl *PVDecl = *PI;
3972 QualType PType = PVDecl->getOriginalType();
3973 if (const ArrayType *AT =
3974 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3975 // Use array's original type only if it has known number of
3977 if (!isa<ConstantArrayType>(AT))
3978 PType = PVDecl->getType();
3979 } else if (PType->isFunctionType())
3980 PType = PVDecl->getType();
3981 // Process argument qualifiers for user supplied arguments; such as,
3982 // 'in', 'inout', etc.
3983 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3984 getObjCEncodingForType(PType, S);
3985 S += charUnitsToString(ParmOffset);
3986 ParmOffset += getObjCEncodingTypeSize(PType);
3992 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
3993 /// property declaration. If non-NULL, Container must be either an
3994 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3995 /// NULL when getting encodings for protocol properties.
3996 /// Property attributes are stored as a comma-delimited C string. The simple
3997 /// attributes readonly and bycopy are encoded as single characters. The
3998 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
3999 /// encoded as single characters, followed by an identifier. Property types
4000 /// are also encoded as a parametrized attribute. The characters used to encode
4001 /// these attributes are defined by the following enumeration:
4003 /// enum PropertyAttributes {
4004 /// kPropertyReadOnly = 'R', // property is read-only.
4005 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4006 /// kPropertyByref = '&', // property is a reference to the value last assigned
4007 /// kPropertyDynamic = 'D', // property is dynamic
4008 /// kPropertyGetter = 'G', // followed by getter selector name
4009 /// kPropertySetter = 'S', // followed by setter selector name
4010 /// kPropertyInstanceVariable = 'V' // followed by instance variable name
4011 /// kPropertyType = 't' // followed by old-style type encoding.
4012 /// kPropertyWeak = 'W' // 'weak' property
4013 /// kPropertyStrong = 'P' // property GC'able
4014 /// kPropertyNonAtomic = 'N' // property non-atomic
4017 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4018 const Decl *Container,
4019 std::string& S) const {
4020 // Collect information from the property implementation decl(s).
4021 bool Dynamic = false;
4022 ObjCPropertyImplDecl *SynthesizePID = 0;
4024 // FIXME: Duplicated code due to poor abstraction.
4026 if (const ObjCCategoryImplDecl *CID =
4027 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4028 for (ObjCCategoryImplDecl::propimpl_iterator
4029 i = CID->propimpl_begin(), e = CID->propimpl_end();
4031 ObjCPropertyImplDecl *PID = *i;
4032 if (PID->getPropertyDecl() == PD) {
4033 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4036 SynthesizePID = PID;
4041 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4042 for (ObjCCategoryImplDecl::propimpl_iterator
4043 i = OID->propimpl_begin(), e = OID->propimpl_end();
4045 ObjCPropertyImplDecl *PID = *i;
4046 if (PID->getPropertyDecl() == PD) {
4047 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4050 SynthesizePID = PID;
4057 // FIXME: This is not very efficient.
4060 // Encode result type.
4061 // GCC has some special rules regarding encoding of properties which
4062 // closely resembles encoding of ivars.
4063 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4064 true /* outermost type */,
4065 true /* encoding for property */);
4067 if (PD->isReadOnly()) {
4070 switch (PD->getSetterKind()) {
4071 case ObjCPropertyDecl::Assign: break;
4072 case ObjCPropertyDecl::Copy: S += ",C"; break;
4073 case ObjCPropertyDecl::Retain: S += ",&"; break;
4077 // It really isn't clear at all what this means, since properties
4078 // are "dynamic by default".
4082 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4085 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4087 S += PD->getGetterName().getAsString();
4090 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4092 S += PD->getSetterName().getAsString();
4095 if (SynthesizePID) {
4096 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4098 S += OID->getNameAsString();
4101 // FIXME: OBJCGC: weak & strong
4104 /// getLegacyIntegralTypeEncoding -
4105 /// Another legacy compatibility encoding: 32-bit longs are encoded as
4106 /// 'l' or 'L' , but not always. For typedefs, we need to use
4107 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
4109 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4110 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4111 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4112 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4113 PointeeTy = UnsignedIntTy;
4115 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4121 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4122 const FieldDecl *Field) const {
4123 // We follow the behavior of gcc, expanding structures which are
4124 // directly pointed to, and expanding embedded structures. Note that
4125 // these rules are sufficient to prevent recursive encoding of the
4127 getObjCEncodingForTypeImpl(T, S, true, true, Field,
4128 true /* outermost type */);
4131 static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4132 switch (T->getAs<BuiltinType>()->getKind()) {
4133 default: assert(0 && "Unhandled builtin type kind");
4134 case BuiltinType::Void: return 'v';
4135 case BuiltinType::Bool: return 'B';
4136 case BuiltinType::Char_U:
4137 case BuiltinType::UChar: return 'C';
4138 case BuiltinType::UShort: return 'S';
4139 case BuiltinType::UInt: return 'I';
4140 case BuiltinType::ULong:
4141 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
4142 case BuiltinType::UInt128: return 'T';
4143 case BuiltinType::ULongLong: return 'Q';
4144 case BuiltinType::Char_S:
4145 case BuiltinType::SChar: return 'c';
4146 case BuiltinType::Short: return 's';
4147 case BuiltinType::WChar_S:
4148 case BuiltinType::WChar_U:
4149 case BuiltinType::Int: return 'i';
4150 case BuiltinType::Long:
4151 return C->getIntWidth(T) == 32 ? 'l' : 'q';
4152 case BuiltinType::LongLong: return 'q';
4153 case BuiltinType::Int128: return 't';
4154 case BuiltinType::Float: return 'f';
4155 case BuiltinType::Double: return 'd';
4156 case BuiltinType::LongDouble: return 'D';
4160 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4161 QualType T, const FieldDecl *FD) {
4162 const Expr *E = FD->getBitWidth();
4163 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
4165 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4166 // The GNU runtime requires more information; bitfields are encoded as b,
4167 // then the offset (in bits) of the first element, then the type of the
4168 // bitfield, then the size in bits. For example, in this structure:
4175 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4176 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4177 // information is not especially sensible, but we're stuck with it for
4178 // compatibility with GCC, although providing it breaks anything that
4179 // actually uses runtime introspection and wants to work on both runtimes...
4180 if (!Ctx->getLangOptions().NeXTRuntime) {
4181 const RecordDecl *RD = FD->getParent();
4182 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4183 // FIXME: This same linear search is also used in ExprConstant - it might
4184 // be better if the FieldDecl stored its offset. We'd be increasing the
4185 // size of the object slightly, but saving some time every time it is used.
4187 for (RecordDecl::field_iterator Field = RD->field_begin(),
4188 FieldEnd = RD->field_end();
4189 Field != FieldEnd; (void)++Field, ++i) {
4193 S += llvm::utostr(RL.getFieldOffset(i));
4194 if (T->isEnumeralType())
4197 S += ObjCEncodingForPrimitiveKind(Ctx, T);
4199 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
4200 S += llvm::utostr(N);
4203 // FIXME: Use SmallString for accumulating string.
4204 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4205 bool ExpandPointedToStructures,
4206 bool ExpandStructures,
4207 const FieldDecl *FD,
4209 bool EncodingProperty,
4210 bool StructField) const {
4211 if (T->getAs<BuiltinType>()) {
4212 if (FD && FD->isBitField())
4213 return EncodeBitField(this, S, T, FD);
4214 S += ObjCEncodingForPrimitiveKind(this, T);
4218 if (const ComplexType *CT = T->getAs<ComplexType>()) {
4220 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4225 // encoding for pointer or r3eference types.
4227 if (const PointerType *PT = T->getAs<PointerType>()) {
4228 if (PT->isObjCSelType()) {
4232 PointeeTy = PT->getPointeeType();
4234 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4235 PointeeTy = RT->getPointeeType();
4236 if (!PointeeTy.isNull()) {
4237 bool isReadOnly = false;
4238 // For historical/compatibility reasons, the read-only qualifier of the
4239 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4240 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4241 // Also, do not emit the 'r' for anything but the outermost type!
4242 if (isa<TypedefType>(T.getTypePtr())) {
4243 if (OutermostType && T.isConstQualified()) {
4247 } else if (OutermostType) {
4248 QualType P = PointeeTy;
4249 while (P->getAs<PointerType>())
4250 P = P->getAs<PointerType>()->getPointeeType();
4251 if (P.isConstQualified()) {
4257 // Another legacy compatibility encoding. Some ObjC qualifier and type
4258 // combinations need to be rearranged.
4259 // Rewrite "in const" from "nr" to "rn"
4260 if (llvm::StringRef(S).endswith("nr"))
4261 S.replace(S.end()-2, S.end(), "rn");
4264 if (PointeeTy->isCharType()) {
4265 // char pointer types should be encoded as '*' unless it is a
4266 // type that has been typedef'd to 'BOOL'.
4267 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4271 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4272 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4273 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4277 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4278 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4285 getLegacyIntegralTypeEncoding(PointeeTy);
4287 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4292 if (const ArrayType *AT =
4293 // Ignore type qualifiers etc.
4294 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4295 if (isa<IncompleteArrayType>(AT) && !StructField) {
4296 // Incomplete arrays are encoded as a pointer to the array element.
4299 getObjCEncodingForTypeImpl(AT->getElementType(), S,
4300 false, ExpandStructures, FD);
4304 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4305 if (getTypeSize(CAT->getElementType()) == 0)
4308 S += llvm::utostr(CAT->getSize().getZExtValue());
4310 //Variable length arrays are encoded as a regular array with 0 elements.
4311 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4312 "Unknown array type!");
4316 getObjCEncodingForTypeImpl(AT->getElementType(), S,
4317 false, ExpandStructures, FD);
4323 if (T->getAs<FunctionType>()) {
4328 if (const RecordType *RTy = T->getAs<RecordType>()) {
4329 RecordDecl *RDecl = RTy->getDecl();
4330 S += RDecl->isUnion() ? '(' : '{';
4331 // Anonymous structures print as '?'
4332 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4334 if (ClassTemplateSpecializationDecl *Spec
4335 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4336 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4337 std::string TemplateArgsStr
4338 = TemplateSpecializationType::PrintTemplateArgumentList(
4339 TemplateArgs.data(),
4340 TemplateArgs.size(),
4341 (*this).PrintingPolicy);
4343 S += TemplateArgsStr;
4348 if (ExpandStructures) {
4350 if (!RDecl->isUnion()) {
4351 getObjCEncodingForStructureImpl(RDecl, S, FD);
4353 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4354 FieldEnd = RDecl->field_end();
4355 Field != FieldEnd; ++Field) {
4358 S += Field->getNameAsString();
4362 // Special case bit-fields.
4363 if (Field->isBitField()) {
4364 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4367 QualType qt = Field->getType();
4368 getLegacyIntegralTypeEncoding(qt);
4369 getObjCEncodingForTypeImpl(qt, S, false, true,
4370 FD, /*OutermostType*/false,
4371 /*EncodingProperty*/false,
4372 /*StructField*/true);
4377 S += RDecl->isUnion() ? ')' : '}';
4381 if (T->isEnumeralType()) {
4382 if (FD && FD->isBitField())
4383 EncodeBitField(this, S, T, FD);
4389 if (T->isBlockPointerType()) {
4390 S += "@?"; // Unlike a pointer-to-function, which is "^?".
4394 // Ignore protocol qualifiers when mangling at this level.
4395 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4396 T = OT->getBaseType();
4398 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4399 // @encode(class_name)
4400 ObjCInterfaceDecl *OI = OIT->getDecl();
4402 const IdentifierInfo *II = OI->getIdentifier();
4405 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
4406 DeepCollectObjCIvars(OI, true, Ivars);
4407 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4408 FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4409 if (Field->isBitField())
4410 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4412 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4418 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4419 if (OPT->isObjCIdType()) {
4424 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4425 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4426 // Since this is a binary compatibility issue, need to consult with runtime
4427 // folks. Fortunately, this is a *very* obsure construct.
4432 if (OPT->isObjCQualifiedIdType()) {
4433 getObjCEncodingForTypeImpl(getObjCIdType(), S,
4434 ExpandPointedToStructures,
4435 ExpandStructures, FD);
4436 if (FD || EncodingProperty) {
4437 // Note that we do extended encoding of protocol qualifer list
4438 // Only when doing ivar or property encoding.
4440 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4441 E = OPT->qual_end(); I != E; ++I) {
4443 S += (*I)->getNameAsString();
4451 QualType PointeeTy = OPT->getPointeeType();
4452 if (!EncodingProperty &&
4453 isa<TypedefType>(PointeeTy.getTypePtr())) {
4454 // Another historical/compatibility reason.
4455 // We encode the underlying type which comes out as
4458 getObjCEncodingForTypeImpl(PointeeTy, S,
4459 false, ExpandPointedToStructures,
4465 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
4467 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4468 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4469 E = OPT->qual_end(); I != E; ++I) {
4471 S += (*I)->getNameAsString();
4479 // gcc just blithely ignores member pointers.
4480 // TODO: maybe there should be a mangling for these
4481 if (T->getAs<MemberPointerType>())
4484 if (T->isVectorType()) {
4485 // This matches gcc's encoding, even though technically it is
4487 // FIXME. We should do a better job than gcc.
4491 assert(0 && "@encode for type not implemented!");
4494 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4496 const FieldDecl *FD,
4497 bool includeVBases) const {
4498 assert(RDecl && "Expected non-null RecordDecl");
4499 assert(!RDecl->isUnion() && "Should not be called for unions");
4500 if (!RDecl->getDefinition())
4503 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4504 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4505 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4508 for (CXXRecordDecl::base_class_iterator
4509 BI = CXXRec->bases_begin(),
4510 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4511 if (!BI->isVirtual()) {
4512 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4513 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4514 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4515 std::make_pair(offs, base));
4521 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4522 FieldEnd = RDecl->field_end();
4523 Field != FieldEnd; ++Field, ++i) {
4524 uint64_t offs = layout.getFieldOffset(i);
4525 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4526 std::make_pair(offs, *Field));
4529 if (CXXRec && includeVBases) {
4530 for (CXXRecordDecl::base_class_iterator
4531 BI = CXXRec->vbases_begin(),
4532 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4533 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4534 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4535 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4536 std::make_pair(offs, base));
4542 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4544 size = layout.getSize();
4547 uint64_t CurOffs = 0;
4548 std::multimap<uint64_t, NamedDecl *>::iterator
4549 CurLayObj = FieldOrBaseOffsets.begin();
4551 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4552 assert(CXXRec && CXXRec->isDynamicClass() &&
4553 "Offset 0 was empty but no VTable ?");
4556 std::string recname = CXXRec->getNameAsString();
4557 if (recname.empty()) recname = "?";
4562 CurOffs += getTypeSize(VoidPtrTy);
4565 if (!RDecl->hasFlexibleArrayMember()) {
4566 // Mark the end of the structure.
4567 uint64_t offs = toBits(size);
4568 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4569 std::make_pair(offs, (NamedDecl*)0));
4572 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4573 assert(CurOffs <= CurLayObj->first);
4575 if (CurOffs < CurLayObj->first) {
4576 uint64_t padding = CurLayObj->first - CurOffs;
4577 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4578 // packing/alignment of members is different that normal, in which case
4579 // the encoding will be out-of-sync with the real layout.
4580 // If the runtime switches to just consider the size of types without
4581 // taking into account alignment, we could make padding explicit in the
4582 // encoding (e.g. using arrays of chars). The encoding strings would be
4583 // longer then though.
4587 NamedDecl *dcl = CurLayObj->second;
4589 break; // reached end of structure.
4591 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4592 // We expand the bases without their virtual bases since those are going
4593 // in the initial structure. Note that this differs from gcc which
4594 // expands virtual bases each time one is encountered in the hierarchy,
4595 // making the encoding type bigger than it really is.
4596 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
4597 if (!base->isEmpty())
4598 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
4600 FieldDecl *field = cast<FieldDecl>(dcl);
4603 S += field->getNameAsString();
4607 if (field->isBitField()) {
4608 EncodeBitField(this, S, field->getType(), field);
4609 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4611 QualType qt = field->getType();
4612 getLegacyIntegralTypeEncoding(qt);
4613 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4614 /*OutermostType*/false,
4615 /*EncodingProperty*/false,
4616 /*StructField*/true);
4617 CurOffs += getTypeSize(field->getType());
4623 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4624 std::string& S) const {
4625 if (QT & Decl::OBJC_TQ_In)
4627 if (QT & Decl::OBJC_TQ_Inout)
4629 if (QT & Decl::OBJC_TQ_Out)
4631 if (QT & Decl::OBJC_TQ_Bycopy)
4633 if (QT & Decl::OBJC_TQ_Byref)
4635 if (QT & Decl::OBJC_TQ_Oneway)
4639 void ASTContext::setBuiltinVaListType(QualType T) {
4640 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
4642 BuiltinVaListType = T;
4645 void ASTContext::setObjCIdType(QualType T) {
4646 ObjCIdTypedefType = T;
4649 void ASTContext::setObjCSelType(QualType T) {
4650 ObjCSelTypedefType = T;
4653 void ASTContext::setObjCProtoType(QualType QT) {
4657 void ASTContext::setObjCClassType(QualType T) {
4658 ObjCClassTypedefType = T;
4661 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4662 assert(ObjCConstantStringType.isNull() &&
4663 "'NSConstantString' type already set!");
4665 ObjCConstantStringType = getObjCInterfaceType(Decl);
4668 /// \brief Retrieve the template name that corresponds to a non-empty
4671 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4672 UnresolvedSetIterator End) const {
4673 unsigned size = End - Begin;
4674 assert(size > 1 && "set is not overloaded!");
4676 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4677 size * sizeof(FunctionTemplateDecl*));
4678 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4680 NamedDecl **Storage = OT->getStorage();
4681 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4683 assert(isa<FunctionTemplateDecl>(D) ||
4684 (isa<UsingShadowDecl>(D) &&
4685 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4689 return TemplateName(OT);
4692 /// \brief Retrieve the template name that represents a qualified
4693 /// template name such as \c std::vector.
4695 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4696 bool TemplateKeyword,
4697 TemplateDecl *Template) const {
4698 assert(NNS && "Missing nested-name-specifier in qualified template name");
4700 // FIXME: Canonicalization?
4701 llvm::FoldingSetNodeID ID;
4702 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4704 void *InsertPos = 0;
4705 QualifiedTemplateName *QTN =
4706 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4708 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4709 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4712 return TemplateName(QTN);
4715 /// \brief Retrieve the template name that represents a dependent
4716 /// template name such as \c MetaFun::template apply.
4718 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4719 const IdentifierInfo *Name) const {
4720 assert((!NNS || NNS->isDependent()) &&
4721 "Nested name specifier must be dependent");
4723 llvm::FoldingSetNodeID ID;
4724 DependentTemplateName::Profile(ID, NNS, Name);
4726 void *InsertPos = 0;
4727 DependentTemplateName *QTN =
4728 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4731 return TemplateName(QTN);
4733 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4734 if (CanonNNS == NNS) {
4735 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4737 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4738 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
4739 DependentTemplateName *CheckQTN =
4740 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4741 assert(!CheckQTN && "Dependent type name canonicalization broken");
4745 DependentTemplateNames.InsertNode(QTN, InsertPos);
4746 return TemplateName(QTN);
4749 /// \brief Retrieve the template name that represents a dependent
4750 /// template name such as \c MetaFun::template operator+.
4752 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4753 OverloadedOperatorKind Operator) const {
4754 assert((!NNS || NNS->isDependent()) &&
4755 "Nested name specifier must be dependent");
4757 llvm::FoldingSetNodeID ID;
4758 DependentTemplateName::Profile(ID, NNS, Operator);
4760 void *InsertPos = 0;
4761 DependentTemplateName *QTN
4762 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4765 return TemplateName(QTN);
4767 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4768 if (CanonNNS == NNS) {
4769 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4771 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4772 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
4774 DependentTemplateName *CheckQTN
4775 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4776 assert(!CheckQTN && "Dependent template name canonicalization broken");
4780 DependentTemplateNames.InsertNode(QTN, InsertPos);
4781 return TemplateName(QTN);
4785 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4786 const TemplateArgument &ArgPack) const {
4787 ASTContext &Self = const_cast<ASTContext &>(*this);
4788 llvm::FoldingSetNodeID ID;
4789 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4791 void *InsertPos = 0;
4792 SubstTemplateTemplateParmPackStorage *Subst
4793 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4796 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Self, Param,
4797 ArgPack.pack_size(),
4798 ArgPack.pack_begin());
4799 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4802 return TemplateName(Subst);
4805 /// getFromTargetType - Given one of the integer types provided by
4806 /// TargetInfo, produce the corresponding type. The unsigned @p Type
4807 /// is actually a value of type @c TargetInfo::IntType.
4808 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
4810 case TargetInfo::NoInt: return CanQualType();
4811 case TargetInfo::SignedShort: return ShortTy;
4812 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4813 case TargetInfo::SignedInt: return IntTy;
4814 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4815 case TargetInfo::SignedLong: return LongTy;
4816 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4817 case TargetInfo::SignedLongLong: return LongLongTy;
4818 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4821 assert(false && "Unhandled TargetInfo::IntType value");
4822 return CanQualType();
4825 //===----------------------------------------------------------------------===//
4827 //===----------------------------------------------------------------------===//
4829 /// isObjCNSObjectType - Return true if this is an NSObject object using
4830 /// NSObject attribute on a c-style pointer type.
4831 /// FIXME - Make it work directly on types.
4832 /// FIXME: Move to Type.
4834 bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4835 if (const TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4836 if (TypedefNameDecl *TD = TDT->getDecl())
4837 if (TD->getAttr<ObjCNSObjectAttr>())
4843 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4844 /// garbage collection attribute.
4846 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4847 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4848 return Qualifiers::GCNone;
4850 assert(getLangOptions().ObjC1);
4851 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4853 // Default behaviour under objective-C's gc is for ObjC pointers
4854 // (or pointers to them) be treated as though they were declared
4856 if (GCAttrs == Qualifiers::GCNone) {
4857 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4858 return Qualifiers::Strong;
4859 else if (Ty->isPointerType())
4860 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4862 // It's not valid to set GC attributes on anything that isn't a
4865 QualType CT = Ty->getCanonicalTypeInternal();
4866 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4867 CT = AT->getElementType();
4868 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4874 //===----------------------------------------------------------------------===//
4875 // Type Compatibility Testing
4876 //===----------------------------------------------------------------------===//
4878 /// areCompatVectorTypes - Return true if the two specified vector types are
4880 static bool areCompatVectorTypes(const VectorType *LHS,
4881 const VectorType *RHS) {
4882 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
4883 return LHS->getElementType() == RHS->getElementType() &&
4884 LHS->getNumElements() == RHS->getNumElements();
4887 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4888 QualType SecondVec) {
4889 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4890 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4892 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4895 // Treat Neon vector types and most AltiVec vector types as if they are the
4896 // equivalent GCC vector types.
4897 const VectorType *First = FirstVec->getAs<VectorType>();
4898 const VectorType *Second = SecondVec->getAs<VectorType>();
4899 if (First->getNumElements() == Second->getNumElements() &&
4900 hasSameType(First->getElementType(), Second->getElementType()) &&
4901 First->getVectorKind() != VectorType::AltiVecPixel &&
4902 First->getVectorKind() != VectorType::AltiVecBool &&
4903 Second->getVectorKind() != VectorType::AltiVecPixel &&
4904 Second->getVectorKind() != VectorType::AltiVecBool)
4910 //===----------------------------------------------------------------------===//
4911 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4912 //===----------------------------------------------------------------------===//
4914 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4915 /// inheritance hierarchy of 'rProto'.
4917 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4918 ObjCProtocolDecl *rProto) const {
4919 if (lProto == rProto)
4921 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4922 E = rProto->protocol_end(); PI != E; ++PI)
4923 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4928 /// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4929 /// return true if lhs's protocols conform to rhs's protocol; false
4931 bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4932 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4933 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4937 /// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4939 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4941 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4942 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4943 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4945 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4946 E = lhsQID->qual_end(); I != E; ++I) {
4948 ObjCProtocolDecl *lhsProto = *I;
4949 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4950 E = rhsOPT->qual_end(); J != E; ++J) {
4951 ObjCProtocolDecl *rhsProto = *J;
4952 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4963 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4964 /// ObjCQualifiedIDType.
4965 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4967 // Allow id<P..> and an 'id' or void* type in all cases.
4968 if (lhs->isVoidPointerType() ||
4969 lhs->isObjCIdType() || lhs->isObjCClassType())
4971 else if (rhs->isVoidPointerType() ||
4972 rhs->isObjCIdType() || rhs->isObjCClassType())
4975 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4976 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4978 if (!rhsOPT) return false;
4980 if (rhsOPT->qual_empty()) {
4981 // If the RHS is a unqualified interface pointer "NSString*",
4982 // make sure we check the class hierarchy.
4983 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4984 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4985 E = lhsQID->qual_end(); I != E; ++I) {
4986 // when comparing an id<P> on lhs with a static type on rhs,
4987 // see if static class implements all of id's protocols, directly or
4988 // through its super class and categories.
4989 if (!rhsID->ClassImplementsProtocol(*I, true))
4993 // If there are no qualifiers and no interface, we have an 'id'.
4996 // Both the right and left sides have qualifiers.
4997 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4998 E = lhsQID->qual_end(); I != E; ++I) {
4999 ObjCProtocolDecl *lhsProto = *I;
5002 // when comparing an id<P> on lhs with a static type on rhs,
5003 // see if static class implements all of id's protocols, directly or
5004 // through its super class and categories.
5005 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5006 E = rhsOPT->qual_end(); J != E; ++J) {
5007 ObjCProtocolDecl *rhsProto = *J;
5008 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5009 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5014 // If the RHS is a qualified interface pointer "NSString<P>*",
5015 // make sure we check the class hierarchy.
5016 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5017 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5018 E = lhsQID->qual_end(); I != E; ++I) {
5019 // when comparing an id<P> on lhs with a static type on rhs,
5020 // see if static class implements all of id's protocols, directly or
5021 // through its super class and categories.
5022 if (rhsID->ClassImplementsProtocol(*I, true)) {
5035 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5036 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5038 if (const ObjCObjectPointerType *lhsOPT =
5039 lhs->getAsObjCInterfacePointerType()) {
5040 // If both the right and left sides have qualifiers.
5041 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5042 E = lhsOPT->qual_end(); I != E; ++I) {
5043 ObjCProtocolDecl *lhsProto = *I;
5046 // when comparing an id<P> on rhs with a static type on lhs,
5047 // see if static class implements all of id's protocols, directly or
5048 // through its super class and categories.
5049 // First, lhs protocols in the qualifier list must be found, direct
5050 // or indirect in rhs's qualifier list or it is a mismatch.
5051 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5052 E = rhsQID->qual_end(); J != E; ++J) {
5053 ObjCProtocolDecl *rhsProto = *J;
5054 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5055 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5064 // Static class's protocols, or its super class or category protocols
5065 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5066 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5067 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5068 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5069 // This is rather dubious but matches gcc's behavior. If lhs has
5070 // no type qualifier and its class has no static protocol(s)
5071 // assume that it is mismatch.
5072 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5074 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5075 LHSInheritedProtocols.begin(),
5076 E = LHSInheritedProtocols.end(); I != E; ++I) {
5078 ObjCProtocolDecl *lhsProto = (*I);
5079 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5080 E = rhsQID->qual_end(); J != E; ++J) {
5081 ObjCProtocolDecl *rhsProto = *J;
5082 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5083 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5097 /// canAssignObjCInterfaces - Return true if the two interface types are
5098 /// compatible for assignment from RHS to LHS. This handles validation of any
5099 /// protocol qualifiers on the LHS or RHS.
5101 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5102 const ObjCObjectPointerType *RHSOPT) {
5103 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5104 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5106 // If either type represents the built-in 'id' or 'Class' types, return true.
5107 if (LHS->isObjCUnqualifiedIdOrClass() ||
5108 RHS->isObjCUnqualifiedIdOrClass())
5111 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
5112 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5116 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5117 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5118 QualType(RHSOPT,0));
5120 // If we have 2 user-defined types, fall into that path.
5121 if (LHS->getInterface() && RHS->getInterface())
5122 return canAssignObjCInterfaces(LHS, RHS);
5127 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
5128 /// for providing type-safety for objective-c pointers used to pass/return
5129 /// arguments in block literals. When passed as arguments, passing 'A*' where
5130 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5131 /// not OK. For the return type, the opposite is not OK.
5132 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5133 const ObjCObjectPointerType *LHSOPT,
5134 const ObjCObjectPointerType *RHSOPT,
5135 bool BlockReturnType) {
5136 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
5139 if (LHSOPT->isObjCBuiltinType()) {
5140 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5143 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
5144 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5148 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5149 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5150 if (LHS && RHS) { // We have 2 user-defined types.
5152 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
5153 return BlockReturnType;
5154 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
5155 return !BlockReturnType;
5163 /// getIntersectionOfProtocols - This routine finds the intersection of set
5164 /// of protocols inherited from two distinct objective-c pointer objects.
5165 /// It is used to build composite qualifier list of the composite type of
5166 /// the conditional expression involving two objective-c pointer objects.
5168 void getIntersectionOfProtocols(ASTContext &Context,
5169 const ObjCObjectPointerType *LHSOPT,
5170 const ObjCObjectPointerType *RHSOPT,
5171 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5173 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5174 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5175 assert(LHS->getInterface() && "LHS must have an interface base");
5176 assert(RHS->getInterface() && "RHS must have an interface base");
5178 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5179 unsigned LHSNumProtocols = LHS->getNumProtocols();
5180 if (LHSNumProtocols > 0)
5181 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5183 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5184 Context.CollectInheritedProtocols(LHS->getInterface(),
5185 LHSInheritedProtocols);
5186 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5187 LHSInheritedProtocols.end());
5190 unsigned RHSNumProtocols = RHS->getNumProtocols();
5191 if (RHSNumProtocols > 0) {
5192 ObjCProtocolDecl **RHSProtocols =
5193 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
5194 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5195 if (InheritedProtocolSet.count(RHSProtocols[i]))
5196 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5199 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
5200 Context.CollectInheritedProtocols(RHS->getInterface(),
5201 RHSInheritedProtocols);
5202 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5203 RHSInheritedProtocols.begin(),
5204 E = RHSInheritedProtocols.end(); I != E; ++I)
5205 if (InheritedProtocolSet.count((*I)))
5206 IntersectionOfProtocols.push_back((*I));
5210 /// areCommonBaseCompatible - Returns common base class of the two classes if
5211 /// one found. Note that this is O'2 algorithm. But it will be called as the
5212 /// last type comparison in a ?-exp of ObjC pointer types before a
5213 /// warning is issued. So, its invokation is extremely rare.
5214 QualType ASTContext::areCommonBaseCompatible(
5215 const ObjCObjectPointerType *Lptr,
5216 const ObjCObjectPointerType *Rptr) {
5217 const ObjCObjectType *LHS = Lptr->getObjectType();
5218 const ObjCObjectType *RHS = Rptr->getObjectType();
5219 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5220 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
5221 if (!LDecl || !RDecl || (LDecl == RDecl))
5225 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
5226 if (canAssignObjCInterfaces(LHS, RHS)) {
5227 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
5228 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5230 QualType Result = QualType(LHS, 0);
5231 if (!Protocols.empty())
5232 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5233 Result = getObjCObjectPointerType(Result);
5236 } while ((LDecl = LDecl->getSuperClass()));
5241 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5242 const ObjCObjectType *RHS) {
5243 assert(LHS->getInterface() && "LHS is not an interface type");
5244 assert(RHS->getInterface() && "RHS is not an interface type");
5246 // Verify that the base decls are compatible: the RHS must be a subclass of
5248 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
5251 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5252 // protocol qualified at all, then we are good.
5253 if (LHS->getNumProtocols() == 0)
5256 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5257 // more detailed analysis is required.
5258 if (RHS->getNumProtocols() == 0) {
5259 // OK, if LHS is a superclass of RHS *and*
5260 // this superclass is assignment compatible with LHS.
5263 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5265 // OK if conversion of LHS to SuperClass results in narrowing of types
5266 // ; i.e., SuperClass may implement at least one of the protocols
5267 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5268 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5269 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
5270 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
5271 // If super class has no protocols, it is not a match.
5272 if (SuperClassInheritedProtocols.empty())
5275 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5276 LHSPE = LHS->qual_end();
5277 LHSPI != LHSPE; LHSPI++) {
5278 bool SuperImplementsProtocol = false;
5279 ObjCProtocolDecl *LHSProto = (*LHSPI);
5281 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5282 SuperClassInheritedProtocols.begin(),
5283 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5284 ObjCProtocolDecl *SuperClassProto = (*I);
5285 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5286 SuperImplementsProtocol = true;
5290 if (!SuperImplementsProtocol)
5298 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5299 LHSPE = LHS->qual_end();
5300 LHSPI != LHSPE; LHSPI++) {
5301 bool RHSImplementsProtocol = false;
5303 // If the RHS doesn't implement the protocol on the left, the types
5304 // are incompatible.
5305 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5306 RHSPE = RHS->qual_end();
5307 RHSPI != RHSPE; RHSPI++) {
5308 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
5309 RHSImplementsProtocol = true;
5313 // FIXME: For better diagnostics, consider passing back the protocol name.
5314 if (!RHSImplementsProtocol)
5317 // The RHS implements all protocols listed on the LHS.
5321 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5322 // get the "pointed to" types
5323 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5324 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
5326 if (!LHSOPT || !RHSOPT)
5329 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5330 canAssignObjCInterfaces(RHSOPT, LHSOPT);
5333 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5334 return canAssignObjCInterfaces(
5335 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5336 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5339 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5340 /// both shall have the identically qualified version of a compatible type.
5341 /// C99 6.2.7p1: Two types have compatible types if their types are the
5342 /// same. See 6.7.[2,3,5] for additional rules.
5343 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5344 bool CompareUnqualified) {
5345 if (getLangOptions().CPlusPlus)
5346 return hasSameType(LHS, RHS);
5348 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5351 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5352 return !mergeTypes(LHS, RHS, true).isNull();
5355 /// mergeTransparentUnionType - if T is a transparent union type and a member
5356 /// of T is compatible with SubType, return the merged type, else return
5358 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5359 bool OfBlockPointer,
5361 if (const RecordType *UT = T->getAsUnionType()) {
5362 RecordDecl *UD = UT->getDecl();
5363 if (UD->hasAttr<TransparentUnionAttr>()) {
5364 for (RecordDecl::field_iterator it = UD->field_begin(),
5365 itend = UD->field_end(); it != itend; ++it) {
5366 QualType ET = it->getType().getUnqualifiedType();
5367 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5377 /// mergeFunctionArgumentTypes - merge two types which appear as function
5379 QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5380 bool OfBlockPointer,
5382 // GNU extension: two types are compatible if they appear as a function
5383 // argument, one of the types is a transparent union type and the other
5384 // type is compatible with a union member
5385 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5387 if (!lmerge.isNull())
5390 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5392 if (!rmerge.isNull())
5395 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5398 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
5399 bool OfBlockPointer,
5401 const FunctionType *lbase = lhs->getAs<FunctionType>();
5402 const FunctionType *rbase = rhs->getAs<FunctionType>();
5403 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5404 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
5405 bool allLTypes = true;
5406 bool allRTypes = true;
5408 // Check return type
5410 if (OfBlockPointer) {
5411 QualType RHS = rbase->getResultType();
5412 QualType LHS = lbase->getResultType();
5413 bool UnqualifiedResult = Unqualified;
5414 if (!UnqualifiedResult)
5415 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5416 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
5419 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5421 if (retType.isNull()) return QualType();
5424 retType = retType.getUnqualifiedType();
5426 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5427 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5429 LRetType = LRetType.getUnqualifiedType();
5430 RRetType = RRetType.getUnqualifiedType();
5433 if (getCanonicalType(retType) != LRetType)
5435 if (getCanonicalType(retType) != RRetType)
5438 // FIXME: double check this
5439 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5440 // rbase->getRegParmAttr() != 0 &&
5441 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
5442 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5443 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
5445 // Compatible functions must have compatible calling conventions
5446 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
5449 // Regparm is part of the calling convention.
5450 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5452 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5455 // It's noreturn if either type is.
5456 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5457 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5458 if (NoReturn != lbaseInfo.getNoReturn())
5460 if (NoReturn != rbaseInfo.getNoReturn())
5463 FunctionType::ExtInfo einfo(NoReturn,
5464 lbaseInfo.getHasRegParm(),
5465 lbaseInfo.getRegParm(),
5468 if (lproto && rproto) { // two C99 style function prototypes
5469 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5470 "C++ shouldn't be here");
5471 unsigned lproto_nargs = lproto->getNumArgs();
5472 unsigned rproto_nargs = rproto->getNumArgs();
5474 // Compatible functions must have the same number of arguments
5475 if (lproto_nargs != rproto_nargs)
5478 // Variadic and non-variadic functions aren't compatible
5479 if (lproto->isVariadic() != rproto->isVariadic())
5482 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5485 // Check argument compatibility
5486 llvm::SmallVector<QualType, 10> types;
5487 for (unsigned i = 0; i < lproto_nargs; i++) {
5488 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5489 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
5490 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5493 if (argtype.isNull()) return QualType();
5496 argtype = argtype.getUnqualifiedType();
5498 types.push_back(argtype);
5500 largtype = largtype.getUnqualifiedType();
5501 rargtype = rargtype.getUnqualifiedType();
5504 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5506 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5509 if (allLTypes) return lhs;
5510 if (allRTypes) return rhs;
5512 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5513 EPI.ExtInfo = einfo;
5514 return getFunctionType(retType, types.begin(), types.size(), EPI);
5517 if (lproto) allRTypes = false;
5518 if (rproto) allLTypes = false;
5520 const FunctionProtoType *proto = lproto ? lproto : rproto;
5522 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
5523 if (proto->isVariadic()) return QualType();
5524 // Check that the types are compatible with the types that
5525 // would result from default argument promotions (C99 6.7.5.3p15).
5526 // The only types actually affected are promotable integer
5527 // types and floats, which would be passed as a different
5528 // type depending on whether the prototype is visible.
5529 unsigned proto_nargs = proto->getNumArgs();
5530 for (unsigned i = 0; i < proto_nargs; ++i) {
5531 QualType argTy = proto->getArgType(i);
5533 // Look at the promotion type of enum types, since that is the type used
5534 // to pass enum values.
5535 if (const EnumType *Enum = argTy->getAs<EnumType>())
5536 argTy = Enum->getDecl()->getPromotionType();
5538 if (argTy->isPromotableIntegerType() ||
5539 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5543 if (allLTypes) return lhs;
5544 if (allRTypes) return rhs;
5546 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5547 EPI.ExtInfo = einfo;
5548 return getFunctionType(retType, proto->arg_type_begin(),
5549 proto->getNumArgs(), EPI);
5552 if (allLTypes) return lhs;
5553 if (allRTypes) return rhs;
5554 return getFunctionNoProtoType(retType, einfo);
5557 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
5558 bool OfBlockPointer,
5559 bool Unqualified, bool BlockReturnType) {
5560 // C++ [expr]: If an expression initially has the type "reference to T", the
5561 // type is adjusted to "T" prior to any further analysis, the expression
5562 // designates the object or function denoted by the reference, and the
5563 // expression is an lvalue unless the reference is an rvalue reference and
5564 // the expression is a function call (possibly inside parentheses).
5565 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5566 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
5569 LHS = LHS.getUnqualifiedType();
5570 RHS = RHS.getUnqualifiedType();
5573 QualType LHSCan = getCanonicalType(LHS),
5574 RHSCan = getCanonicalType(RHS);
5576 // If two types are identical, they are compatible.
5577 if (LHSCan == RHSCan)
5580 // If the qualifiers are different, the types aren't compatible... mostly.
5581 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5582 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5583 if (LQuals != RQuals) {
5584 // If any of these qualifiers are different, we have a type
5586 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5587 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5590 // Exactly one GC qualifier difference is allowed: __strong is
5591 // okay if the other type has no GC qualifier but is an Objective
5592 // C object pointer (i.e. implicitly strong by default). We fix
5593 // this by pretending that the unqualified type was actually
5594 // qualified __strong.
5595 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5596 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5597 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5599 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5602 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5603 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5605 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5606 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5611 // Okay, qualifiers are equal.
5613 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5614 Type::TypeClass RHSClass = RHSCan->getTypeClass();
5616 // We want to consider the two function types to be the same for these
5617 // comparisons, just force one to the other.
5618 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5619 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
5621 // Same as above for arrays
5622 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5623 LHSClass = Type::ConstantArray;
5624 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5625 RHSClass = Type::ConstantArray;
5627 // ObjCInterfaces are just specialized ObjCObjects.
5628 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5629 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5631 // Canonicalize ExtVector -> Vector.
5632 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5633 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
5635 // If the canonical type classes don't match.
5636 if (LHSClass != RHSClass) {
5637 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
5638 // a signed integer type, or an unsigned integer type.
5639 // Compatibility is based on the underlying type, not the promotion
5641 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
5642 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5645 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
5646 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5653 // The canonical type classes match.
5655 #define TYPE(Class, Base)
5656 #define ABSTRACT_TYPE(Class, Base)
5657 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5658 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5659 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
5660 #include "clang/AST/TypeNodes.def"
5661 assert(false && "Non-canonical and dependent types shouldn't get here");
5664 case Type::LValueReference:
5665 case Type::RValueReference:
5666 case Type::MemberPointer:
5667 assert(false && "C++ should never be in mergeTypes");
5670 case Type::ObjCInterface:
5671 case Type::IncompleteArray:
5672 case Type::VariableArray:
5673 case Type::FunctionProto:
5674 case Type::ExtVector:
5675 assert(false && "Types are eliminated above");
5680 // Merge two pointer types, while trying to preserve typedef info
5681 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5682 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
5684 LHSPointee = LHSPointee.getUnqualifiedType();
5685 RHSPointee = RHSPointee.getUnqualifiedType();
5687 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5689 if (ResultType.isNull()) return QualType();
5690 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5692 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5694 return getPointerType(ResultType);
5696 case Type::BlockPointer:
5698 // Merge two block pointer types, while trying to preserve typedef info
5699 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5700 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
5702 LHSPointee = LHSPointee.getUnqualifiedType();
5703 RHSPointee = RHSPointee.getUnqualifiedType();
5705 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5707 if (ResultType.isNull()) return QualType();
5708 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5710 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5712 return getBlockPointerType(ResultType);
5714 case Type::ConstantArray:
5716 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5717 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5718 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5721 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5722 QualType RHSElem = getAsArrayType(RHS)->getElementType();
5724 LHSElem = LHSElem.getUnqualifiedType();
5725 RHSElem = RHSElem.getUnqualifiedType();
5728 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
5729 if (ResultType.isNull()) return QualType();
5730 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5732 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5734 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5735 ArrayType::ArraySizeModifier(), 0);
5736 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5737 ArrayType::ArraySizeModifier(), 0);
5738 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5739 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
5740 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5742 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5745 // FIXME: This isn't correct! But tricky to implement because
5746 // the array's size has to be the size of LHS, but the type
5747 // has to be different.
5751 // FIXME: This isn't correct! But tricky to implement because
5752 // the array's size has to be the size of RHS, but the type
5753 // has to be different.
5756 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5757 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
5758 return getIncompleteArrayType(ResultType,
5759 ArrayType::ArraySizeModifier(), 0);
5761 case Type::FunctionNoProto:
5762 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
5767 // Only exactly equal builtin types are compatible, which is tested above.
5770 // Distinct complex types are incompatible.
5773 // FIXME: The merged type should be an ExtVector!
5774 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5775 RHSCan->getAs<VectorType>()))
5778 case Type::ObjCObject: {
5779 // Check if the types are assignment compatible.
5780 // FIXME: This should be type compatibility, e.g. whether
5781 // "LHS x; RHS x;" at global scope is legal.
5782 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5783 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5784 if (canAssignObjCInterfaces(LHSIface, RHSIface))
5789 case Type::ObjCObjectPointer: {
5790 if (OfBlockPointer) {
5791 if (canAssignObjCInterfacesInBlockPointer(
5792 LHS->getAs<ObjCObjectPointerType>(),
5793 RHS->getAs<ObjCObjectPointerType>(),
5798 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5799 RHS->getAs<ObjCObjectPointerType>()))
5809 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5810 /// 'RHS' attributes and returns the merged version; including for function
5812 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5813 QualType LHSCan = getCanonicalType(LHS),
5814 RHSCan = getCanonicalType(RHS);
5815 // If two types are identical, they are compatible.
5816 if (LHSCan == RHSCan)
5818 if (RHSCan->isFunctionType()) {
5819 if (!LHSCan->isFunctionType())
5821 QualType OldReturnType =
5822 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5823 QualType NewReturnType =
5824 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5825 QualType ResReturnType =
5826 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5827 if (ResReturnType.isNull())
5829 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5830 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5831 // In either case, use OldReturnType to build the new function type.
5832 const FunctionType *F = LHS->getAs<FunctionType>();
5833 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
5834 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5835 EPI.ExtInfo = getFunctionExtInfo(LHS);
5837 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
5838 FPT->getNumArgs(), EPI);
5845 // If the qualifiers are different, the types can still be merged.
5846 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5847 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5848 if (LQuals != RQuals) {
5849 // If any of these qualifiers are different, we have a type mismatch.
5850 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5851 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5854 // Exactly one GC qualifier difference is allowed: __strong is
5855 // okay if the other type has no GC qualifier but is an Objective
5856 // C object pointer (i.e. implicitly strong by default). We fix
5857 // this by pretending that the unqualified type was actually
5858 // qualified __strong.
5859 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5860 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5861 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5863 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5866 if (GC_L == Qualifiers::Strong)
5868 if (GC_R == Qualifiers::Strong)
5873 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5874 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5875 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5876 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5877 if (ResQT == LHSBaseQT)
5879 if (ResQT == RHSBaseQT)
5885 //===----------------------------------------------------------------------===//
5886 // Integer Predicates
5887 //===----------------------------------------------------------------------===//
5889 unsigned ASTContext::getIntWidth(QualType T) const {
5890 if (const EnumType *ET = dyn_cast<EnumType>(T))
5891 T = ET->getDecl()->getIntegerType();
5892 if (T->isBooleanType())
5894 // For builtin types, just use the standard type sizing method
5895 return (unsigned)getTypeSize(T);
5898 QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
5899 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
5901 // Turn <4 x signed int> -> <4 x unsigned int>
5902 if (const VectorType *VTy = T->getAs<VectorType>())
5903 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
5904 VTy->getNumElements(), VTy->getVectorKind());
5906 // For enums, we return the unsigned version of the base type.
5907 if (const EnumType *ETy = T->getAs<EnumType>())
5908 T = ETy->getDecl()->getIntegerType();
5910 const BuiltinType *BTy = T->getAs<BuiltinType>();
5911 assert(BTy && "Unexpected signed integer type");
5912 switch (BTy->getKind()) {
5913 case BuiltinType::Char_S:
5914 case BuiltinType::SChar:
5915 return UnsignedCharTy;
5916 case BuiltinType::Short:
5917 return UnsignedShortTy;
5918 case BuiltinType::Int:
5919 return UnsignedIntTy;
5920 case BuiltinType::Long:
5921 return UnsignedLongTy;
5922 case BuiltinType::LongLong:
5923 return UnsignedLongLongTy;
5924 case BuiltinType::Int128:
5925 return UnsignedInt128Ty;
5927 assert(0 && "Unexpected signed integer type");
5932 ASTMutationListener::~ASTMutationListener() { }
5935 //===----------------------------------------------------------------------===//
5936 // Builtin Type Computation
5937 //===----------------------------------------------------------------------===//
5939 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
5940 /// pointer over the consumed characters. This returns the resultant type. If
5941 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5942 /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5943 /// a vector of "i*".
5945 /// RequiresICE is filled in on return to indicate whether the value is required
5946 /// to be an Integer Constant Expression.
5947 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
5948 ASTContext::GetBuiltinTypeError &Error,
5950 bool AllowTypeModifiers) {
5953 bool Signed = false, Unsigned = false;
5954 RequiresICE = false;
5956 // Read the prefixed modifiers first.
5960 default: Done = true; --Str; break;
5965 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5966 assert(!Signed && "Can't use 'S' modifier multiple times!");
5970 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5971 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5975 assert(HowLong <= 2 && "Can't have LLLL modifier");
5983 // Read the base type.
5985 default: assert(0 && "Unknown builtin type letter!");
5987 assert(HowLong == 0 && !Signed && !Unsigned &&
5988 "Bad modifiers used with 'v'!");
5989 Type = Context.VoidTy;
5992 assert(HowLong == 0 && !Signed && !Unsigned &&
5993 "Bad modifiers used with 'f'!");
5994 Type = Context.FloatTy;
5997 assert(HowLong < 2 && !Signed && !Unsigned &&
5998 "Bad modifiers used with 'd'!");
6000 Type = Context.LongDoubleTy;
6002 Type = Context.DoubleTy;
6005 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6007 Type = Context.UnsignedShortTy;
6009 Type = Context.ShortTy;
6013 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6014 else if (HowLong == 2)
6015 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6016 else if (HowLong == 1)
6017 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6019 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6022 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6024 Type = Context.SignedCharTy;
6026 Type = Context.UnsignedCharTy;
6028 Type = Context.CharTy;
6030 case 'b': // boolean
6031 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6032 Type = Context.BoolTy;
6034 case 'z': // size_t.
6035 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6036 Type = Context.getSizeType();
6039 Type = Context.getCFConstantStringType();
6042 Type = Context.getObjCIdType();
6045 Type = Context.getObjCSelType();
6048 Type = Context.getBuiltinVaListType();
6049 assert(!Type.isNull() && "builtin va list type not initialized!");
6052 // This is a "reference" to a va_list; however, what exactly
6053 // this means depends on how va_list is defined. There are two
6054 // different kinds of va_list: ones passed by value, and ones
6055 // passed by reference. An example of a by-value va_list is
6056 // x86, where va_list is a char*. An example of by-ref va_list
6057 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6058 // we want this argument to be a char*&; for x86-64, we want
6059 // it to be a __va_list_tag*.
6060 Type = Context.getBuiltinVaListType();
6061 assert(!Type.isNull() && "builtin va list type not initialized!");
6062 if (Type->isArrayType())
6063 Type = Context.getArrayDecayedType(Type);
6065 Type = Context.getLValueReferenceType(Type);
6069 unsigned NumElements = strtoul(Str, &End, 10);
6070 assert(End != Str && "Missing vector size");
6073 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6074 RequiresICE, false);
6075 assert(!RequiresICE && "Can't require vector ICE");
6077 // TODO: No way to make AltiVec vectors in builtins yet.
6078 Type = Context.getVectorType(ElementType, NumElements,
6079 VectorType::GenericVector);
6083 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6085 assert(!RequiresICE && "Can't require complex ICE");
6086 Type = Context.getComplexType(ElementType);
6090 Type = Context.getFILEType();
6091 if (Type.isNull()) {
6092 Error = ASTContext::GE_Missing_stdio;
6098 Type = Context.getsigjmp_bufType();
6100 Type = Context.getjmp_bufType();
6102 if (Type.isNull()) {
6103 Error = ASTContext::GE_Missing_setjmp;
6109 // If there are modifiers and if we're allowed to parse them, go for it.
6110 Done = !AllowTypeModifiers;
6112 switch (char c = *Str++) {
6113 default: Done = true; --Str; break;
6116 // Both pointers and references can have their pointee types
6117 // qualified with an address space.
6119 unsigned AddrSpace = strtoul(Str, &End, 10);
6120 if (End != Str && AddrSpace != 0) {
6121 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6125 Type = Context.getPointerType(Type);
6127 Type = Context.getLValueReferenceType(Type);
6130 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6132 Type = Type.withConst();
6135 Type = Context.getVolatileType(Type);
6140 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
6141 "Integer constant 'I' type must be an integer");
6146 /// GetBuiltinType - Return the type for the specified builtin.
6147 QualType ASTContext::GetBuiltinType(unsigned Id,
6148 GetBuiltinTypeError &Error,
6149 unsigned *IntegerConstantArgs) const {
6150 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
6152 llvm::SmallVector<QualType, 8> ArgTypes;
6154 bool RequiresICE = false;
6156 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6158 if (Error != GE_None)
6161 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6163 while (TypeStr[0] && TypeStr[0] != '.') {
6164 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
6165 if (Error != GE_None)
6168 // If this argument is required to be an IntegerConstantExpression and the
6169 // caller cares, fill in the bitmask we return.
6170 if (RequiresICE && IntegerConstantArgs)
6171 *IntegerConstantArgs |= 1 << ArgTypes.size();
6173 // Do array -> pointer decay. The builtin should use the decayed type.
6174 if (Ty->isArrayType())
6175 Ty = getArrayDecayedType(Ty);
6177 ArgTypes.push_back(Ty);
6180 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6181 "'.' should only occur at end of builtin type list!");
6183 FunctionType::ExtInfo EI;
6184 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6186 bool Variadic = (TypeStr[0] == '.');
6188 // We really shouldn't be making a no-proto type here, especially in C++.
6189 if (ArgTypes.empty() && Variadic)
6190 return getFunctionNoProtoType(ResType, EI);
6192 FunctionProtoType::ExtProtoInfo EPI;
6194 EPI.Variadic = Variadic;
6196 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
6199 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6200 GVALinkage External = GVA_StrongExternal;
6202 Linkage L = FD->getLinkage();
6205 case InternalLinkage:
6206 case UniqueExternalLinkage:
6207 return GVA_Internal;
6209 case ExternalLinkage:
6210 switch (FD->getTemplateSpecializationKind()) {
6211 case TSK_Undeclared:
6212 case TSK_ExplicitSpecialization:
6213 External = GVA_StrongExternal;
6216 case TSK_ExplicitInstantiationDefinition:
6217 return GVA_ExplicitTemplateInstantiation;
6219 case TSK_ExplicitInstantiationDeclaration:
6220 case TSK_ImplicitInstantiation:
6221 External = GVA_TemplateInstantiation;
6226 if (!FD->isInlined())
6229 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6230 // GNU or C99 inline semantics. Determine whether this symbol should be
6231 // externally visible.
6232 if (FD->isInlineDefinitionExternallyVisible())
6235 // C99 inline semantics, where the symbol is not externally visible.
6236 return GVA_C99Inline;
6239 // C++0x [temp.explicit]p9:
6240 // [ Note: The intent is that an inline function that is the subject of
6241 // an explicit instantiation declaration will still be implicitly
6242 // instantiated when used so that the body can be considered for
6243 // inlining, but that no out-of-line copy of the inline function would be
6244 // generated in the translation unit. -- end note ]
6245 if (FD->getTemplateSpecializationKind()
6246 == TSK_ExplicitInstantiationDeclaration)
6247 return GVA_C99Inline;
6249 return GVA_CXXInline;
6252 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6253 // If this is a static data member, compute the kind of template
6254 // specialization. Otherwise, this variable is not part of a
6256 TemplateSpecializationKind TSK = TSK_Undeclared;
6257 if (VD->isStaticDataMember())
6258 TSK = VD->getTemplateSpecializationKind();
6260 Linkage L = VD->getLinkage();
6261 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6262 VD->getType()->getLinkage() == UniqueExternalLinkage)
6263 L = UniqueExternalLinkage;
6267 case InternalLinkage:
6268 case UniqueExternalLinkage:
6269 return GVA_Internal;
6271 case ExternalLinkage:
6273 case TSK_Undeclared:
6274 case TSK_ExplicitSpecialization:
6275 return GVA_StrongExternal;
6277 case TSK_ExplicitInstantiationDeclaration:
6278 llvm_unreachable("Variable should not be instantiated");
6279 // Fall through to treat this like any other instantiation.
6281 case TSK_ExplicitInstantiationDefinition:
6282 return GVA_ExplicitTemplateInstantiation;
6284 case TSK_ImplicitInstantiation:
6285 return GVA_TemplateInstantiation;
6289 return GVA_StrongExternal;
6292 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
6293 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6294 if (!VD->isFileVarDecl())
6296 } else if (!isa<FunctionDecl>(D))
6299 // Weak references don't produce any output by themselves.
6300 if (D->hasAttr<WeakRefAttr>())
6303 // Aliases and used decls are required.
6304 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6307 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6308 // Forward declarations aren't required.
6309 if (!FD->doesThisDeclarationHaveABody())
6312 // Constructors and destructors are required.
6313 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6316 // The key function for a class is required.
6317 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6318 const CXXRecordDecl *RD = MD->getParent();
6319 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6320 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6321 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6326 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6328 // static, static inline, always_inline, and extern inline functions can
6329 // always be deferred. Normal inline functions can be deferred in C99/C++.
6330 // Implicit template instantiations can also be deferred in C++.
6331 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6332 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6337 const VarDecl *VD = cast<VarDecl>(D);
6338 assert(VD->isFileVarDecl() && "Expected file scoped var");
6340 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6343 // Structs that have non-trivial constructors or destructors are required.
6345 // FIXME: Handle references.
6346 // FIXME: Be more selective about which constructors we care about.
6347 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6348 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
6349 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6350 RD->hasTrivialCopyConstructor() &&
6351 RD->hasTrivialMoveConstructor() &&
6352 RD->hasTrivialDestructor()))
6357 GVALinkage L = GetGVALinkageForVariable(VD);
6358 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6359 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6366 CallingConv ASTContext::getDefaultMethodCallConv() {
6367 // Pass through to the C++ ABI object
6368 return ABI->getDefaultMethodCallConv();
6371 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
6372 // Pass through to the C++ ABI object
6373 return ABI->isNearlyEmpty(RD);
6376 MangleContext *ASTContext::createMangleContext() {
6377 switch (Target.getCXXABI()) {
6379 case CXXABI_Itanium:
6380 return createItaniumMangleContext(*this, getDiagnostics());
6381 case CXXABI_Microsoft:
6382 return createMicrosoftMangleContext(*this, getDiagnostics());
6384 assert(0 && "Unsupported ABI");
6388 CXXABI::~CXXABI() {}
6390 size_t ASTContext::getSideTableAllocatedMemory() const {
6392 bytes += ASTRecordLayouts.getMemorySize();
6393 bytes += ObjCLayouts.getMemorySize();
6394 bytes += KeyFunctions.getMemorySize();
6395 bytes += ObjCImpls.getMemorySize();
6396 bytes += BlockVarCopyInits.getMemorySize();
6397 bytes += DeclAttrs.getMemorySize();
6398 bytes += InstantiatedFromStaticDataMember.getMemorySize();
6399 bytes += InstantiatedFromUsingDecl.getMemorySize();
6400 bytes += InstantiatedFromUsingShadowDecl.getMemorySize();
6401 bytes += InstantiatedFromUnnamedFieldDecl.getMemorySize();