blob: 9784191ad80f475839dd673a040741d81a3f6363 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Ken Dyckbdc601b2009-12-22 14:23:30 +000015#include "clang/AST/CharUnits.h"
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +000016#include "clang/AST/DeclCXX.h"
Steve Naroff980e5082007-10-01 19:00:59 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000018#include "clang/AST/DeclTemplate.h"
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000020#include "clang/AST/Expr.h"
John McCallea1471e2010-05-20 01:18:31 +000021#include "clang/AST/ExprCXX.h"
Douglas Gregor2cf26342009-04-09 22:27:44 +000022#include "clang/AST/ExternalASTSource.h"
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +000023#include "clang/AST/ASTMutationListener.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000024#include "clang/AST/RecordLayout.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000025#include "clang/AST/Mangle.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Chris Lattnera9376d42009-03-28 03:45:20 +000027#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028#include "clang/Basic/TargetInfo.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000029#include "llvm/ADT/SmallString.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000030#include "llvm/ADT/StringExtras.h"
Nate Begeman6fe7c8a2009-01-18 06:42:49 +000031#include "llvm/Support/MathExtras.h"
Benjamin Kramerf5942a42009-10-24 09:57:09 +000032#include "llvm/Support/raw_ostream.h"
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +000033#include "llvm/Support/Capacity.h"
Charles Davis071cc7d2010-08-16 03:33:14 +000034#include "CXXABI.h"
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +000035#include <map>
Anders Carlsson29445a02009-07-18 21:19:52 +000036
Reid Spencer5f016e22007-07-11 17:01:13 +000037using namespace clang;
38
Douglas Gregor18274032010-07-03 00:47:00 +000039unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregor22584312010-07-02 23:41:54 +000041unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000043unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregora376d102010-07-02 21:50:04 +000045unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Huntffe37fd2011-05-25 20:50:04 +000047unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor4923aa22010-07-02 20:37:36 +000049unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
Reid Spencer5f016e22007-07-11 17:01:13 +000052enum FloatingRank {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +000053 HalfRank, FloatRank, DoubleRank, LongDoubleRank
Reid Spencer5f016e22007-07-11 17:01:13 +000054};
55
Douglas Gregor3e1274f2010-06-16 21:09:37 +000056void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58 TemplateTemplateParmDecl *Parm) {
59 ID.AddInteger(Parm->getDepth());
60 ID.AddInteger(Parm->getPosition());
Douglas Gregor61c4d282011-01-05 15:48:55 +000061 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000062
63 TemplateParameterList *Params = Parm->getTemplateParameters();
64 ID.AddInteger(Params->size());
65 for (TemplateParameterList::const_iterator P = Params->begin(),
66 PEnd = Params->end();
67 P != PEnd; ++P) {
68 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69 ID.AddInteger(0);
70 ID.AddBoolean(TTP->isParameterPack());
71 continue;
72 }
73
74 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75 ID.AddInteger(1);
Douglas Gregor61c4d282011-01-05 15:48:55 +000076 ID.AddBoolean(NTTP->isParameterPack());
Douglas Gregor3e1274f2010-06-16 21:09:37 +000077 ID.AddPointer(NTTP->getType().getAsOpaquePtr());
Douglas Gregor6952f1e2011-01-19 20:10:05 +000078 if (NTTP->isExpandedParameterPack()) {
79 ID.AddBoolean(true);
80 ID.AddInteger(NTTP->getNumExpansionTypes());
81 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82 ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83 } else
84 ID.AddBoolean(false);
Douglas Gregor3e1274f2010-06-16 21:09:37 +000085 continue;
86 }
87
88 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89 ID.AddInteger(2);
90 Profile(ID, TTP);
91 }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad4ba2a172011-01-12 09:06:06 +000096 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor3e1274f2010-06-16 21:09:37 +000097 // Check if we already have a canonical template template parameter.
98 llvm::FoldingSetNodeID ID;
99 CanonicalTemplateTemplateParm::Profile(ID, TTP);
100 void *InsertPos = 0;
101 CanonicalTemplateTemplateParm *Canonical
102 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103 if (Canonical)
104 return Canonical->getParam();
105
106 // Build a canonical template parameter list.
107 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000109 CanonParams.reserve(Params->size());
110 for (TemplateParameterList::const_iterator P = Params->begin(),
111 PEnd = Params->end();
112 P != PEnd; ++P) {
113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114 CanonParams.push_back(
115 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnara344577e2011-03-06 15:48:19 +0000116 SourceLocation(),
117 SourceLocation(),
118 TTP->getDepth(),
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000119 TTP->getIndex(), 0, false,
120 TTP->isParameterPack()));
121 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000122 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123 QualType T = getCanonicalType(NTTP->getType());
124 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125 NonTypeTemplateParmDecl *Param;
126 if (NTTP->isExpandedParameterPack()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<QualType, 2> ExpandedTypes;
128 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000129 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131 ExpandedTInfos.push_back(
132 getTrivialTypeSourceInfo(ExpandedTypes.back()));
133 }
134
135 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000136 SourceLocation(),
137 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000138 NTTP->getDepth(),
139 NTTP->getPosition(), 0,
140 T,
141 TInfo,
142 ExpandedTypes.data(),
143 ExpandedTypes.size(),
144 ExpandedTInfos.data());
145 } else {
146 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000147 SourceLocation(),
148 SourceLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000149 NTTP->getDepth(),
150 NTTP->getPosition(), 0,
151 T,
152 NTTP->isParameterPack(),
153 TInfo);
154 }
155 CanonParams.push_back(Param);
156
157 } else
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000158 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159 cast<TemplateTemplateParmDecl>(*P)));
160 }
161
162 TemplateTemplateParmDecl *CanonTTP
163 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164 SourceLocation(), TTP->getDepth(),
Douglas Gregor61c4d282011-01-05 15:48:55 +0000165 TTP->getPosition(),
166 TTP->isParameterPack(),
167 0,
Douglas Gregor3e1274f2010-06-16 21:09:37 +0000168 TemplateParameterList::Create(*this, SourceLocation(),
169 SourceLocation(),
170 CanonParams.data(),
171 CanonParams.size(),
172 SourceLocation()));
173
174 // Get the new insert position for the node we care about.
175 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176 assert(Canonical == 0 && "Shouldn't be in the map!");
177 (void)Canonical;
178
179 // Create the canonical template template parameter entry.
180 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182 return CanonTTP;
183}
184
Charles Davis071cc7d2010-08-16 03:33:14 +0000185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
John McCallee79a4c2010-08-21 22:46:04 +0000186 if (!LangOpts.CPlusPlus) return 0;
187
Charles Davis20cf7172010-08-19 02:18:14 +0000188 switch (T.getCXXABI()) {
John McCallee79a4c2010-08-21 22:46:04 +0000189 case CXXABI_ARM:
190 return CreateARMCXXABI(*this);
191 case CXXABI_Itanium:
Charles Davis071cc7d2010-08-16 03:33:14 +0000192 return CreateItaniumCXXABI(*this);
Charles Davis20cf7172010-08-19 02:18:14 +0000193 case CXXABI_Microsoft:
194 return CreateMicrosoftCXXABI(*this);
195 }
John McCallee79a4c2010-08-21 22:46:04 +0000196 return 0;
Charles Davis071cc7d2010-08-16 03:33:14 +0000197}
198
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000200 const LangOptions &LOpts) {
201 if (LOpts.FakeAddressSpaceMap) {
202 // The fake address space map must have a distinct entry for each
203 // language-specific address space.
204 static const unsigned FakeAddrSpaceMap[] = {
205 1, // opencl_global
206 2, // opencl_local
207 3 // opencl_constant
208 };
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000209 return &FakeAddrSpaceMap;
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000210 } else {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000211 return &T.getAddressSpaceMap();
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000212 }
213}
214
Douglas Gregor3e3cd932011-09-01 20:23:19 +0000215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000216 const TargetInfo *t,
Daniel Dunbare91593e2008-08-11 04:54:23 +0000217 IdentifierTable &idents, SelectorTable &sels,
Chris Lattner1b63e4f2009-06-14 01:54:56 +0000218 Builtin::Context &builtins,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000219 unsigned size_reserve,
220 bool DelayInitialization)
221 : FunctionProtoTypes(this_()),
222 TemplateSpecializationTypes(this_()),
223 DependentTemplateSpecializationTypes(this_()),
224 SubstTemplateTemplateParmPacks(this_()),
225 GlobalNestedNameSpecifier(0),
226 Int128Decl(0), UInt128Decl(0),
227 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0),
Douglas Gregore97179c2011-09-08 01:46:34 +0000228 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000229 FILEDecl(0),
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +0000230 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
231 BlockDescriptorType(0), BlockDescriptorExtendedType(0),
232 cudaConfigureCallDecl(0),
Douglas Gregore6649772011-12-03 00:30:27 +0000233 NullTypeSourceInfo(QualType()),
234 FirstLocalImport(), LastLocalImport(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000235 SourceMgr(SM), LangOpts(LOpts),
Douglas Gregor30c42402011-09-27 22:38:19 +0000236 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000237 Idents(idents), Selectors(sels),
238 BuiltinInfo(builtins),
239 DeclarationNames(*this),
Douglas Gregor30c42402011-09-27 22:38:19 +0000240 ExternalSource(0), Listener(0),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000241 LastSDM(0, 0),
242 UniqueBlockByRefTypeID(0)
243{
Mike Stump1eb44332009-09-09 15:08:12 +0000244 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000245 TUDecl = TranslationUnitDecl::Create(*this);
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000246
247 if (!DelayInitialization) {
248 assert(t && "No target supplied for ASTContext initialization");
249 InitBuiltinTypes(*t);
250 }
Daniel Dunbare91593e2008-08-11 04:54:23 +0000251}
252
Reid Spencer5f016e22007-07-11 17:01:13 +0000253ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000254 // Release the DenseMaps associated with DeclContext objects.
255 // FIXME: Is this the ideal solution?
256 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000257
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000258 // Call all of the deallocation functions.
259 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
260 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000261
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000262 // Release all of the memory associated with overridden C++ methods.
263 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
264 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
265 OM != OMEnd; ++OM)
266 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000267
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000268 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000269 // because they can contain DenseMaps.
270 for (llvm::DenseMap<const ObjCContainerDecl*,
271 const ASTRecordLayout*>::iterator
272 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
273 // Increment in loop to prevent using deallocated memory.
274 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
275 R->Destroy(*this);
276
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000277 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
278 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
279 // Increment in loop to prevent using deallocated memory.
280 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
281 R->Destroy(*this);
282 }
Douglas Gregor63200642010-08-30 16:49:28 +0000283
284 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
285 AEnd = DeclAttrs.end();
286 A != AEnd; ++A)
287 A->second->~AttrVec();
288}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000289
Douglas Gregor00545312010-05-23 18:26:36 +0000290void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
291 Deallocations.push_back(std::make_pair(Callback, Data));
292}
293
Mike Stump1eb44332009-09-09 15:08:12 +0000294void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000295ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
296 ExternalSource.reset(Source.take());
297}
298
Reid Spencer5f016e22007-07-11 17:01:13 +0000299void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000300 llvm::errs() << "\n*** AST Context Stats:\n";
301 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000302
Douglas Gregordbe833d2009-05-26 14:40:08 +0000303 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000304#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000305#define ABSTRACT_TYPE(Name, Parent)
306#include "clang/AST/TypeNodes.def"
307 0 // Extra
308 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000309
Reid Spencer5f016e22007-07-11 17:01:13 +0000310 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
311 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000312 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 }
314
Douglas Gregordbe833d2009-05-26 14:40:08 +0000315 unsigned Idx = 0;
316 unsigned TotalBytes = 0;
317#define TYPE(Name, Parent) \
318 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000319 llvm::errs() << " " << counts[Idx] << " " << #Name \
320 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000321 TotalBytes += counts[Idx] * sizeof(Name##Type); \
322 ++Idx;
323#define ABSTRACT_TYPE(Name, Parent)
324#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chandler Carruthcd92a652011-07-04 05:32:14 +0000326 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
327
Douglas Gregor4923aa22010-07-02 20:37:36 +0000328 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000329 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
330 << NumImplicitDefaultConstructors
331 << " implicit default constructors created\n";
332 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
333 << NumImplicitCopyConstructors
334 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000335 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000336 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
337 << NumImplicitMoveConstructors
338 << " implicit move constructors created\n";
339 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
340 << NumImplicitCopyAssignmentOperators
341 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000342 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000343 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
344 << NumImplicitMoveAssignmentOperators
345 << " implicit move assignment operators created\n";
346 llvm::errs() << NumImplicitDestructorsDeclared << "/"
347 << NumImplicitDestructors
348 << " implicit destructors created\n";
349
Douglas Gregor2cf26342009-04-09 22:27:44 +0000350 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000351 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000352 ExternalSource->PrintStats();
353 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000354
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000355 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000356}
357
Douglas Gregor772eeae2011-08-12 06:49:56 +0000358TypedefDecl *ASTContext::getInt128Decl() const {
359 if (!Int128Decl) {
360 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
361 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
362 getTranslationUnitDecl(),
363 SourceLocation(),
364 SourceLocation(),
365 &Idents.get("__int128_t"),
366 TInfo);
367 }
368
369 return Int128Decl;
370}
371
372TypedefDecl *ASTContext::getUInt128Decl() const {
373 if (!UInt128Decl) {
374 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
375 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
376 getTranslationUnitDecl(),
377 SourceLocation(),
378 SourceLocation(),
379 &Idents.get("__uint128_t"),
380 TInfo);
381 }
382
383 return UInt128Decl;
384}
Reid Spencer5f016e22007-07-11 17:01:13 +0000385
John McCalle27ec8a2009-10-23 23:03:21 +0000386void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000387 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000388 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000389 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000390}
391
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000392void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
393 assert((!this->Target || this->Target == &Target) &&
394 "Incorrect target reinitialization");
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000397 this->Target = &Target;
398
399 ABI.reset(createCXXABI(Target));
400 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
401
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 // C99 6.2.5p19.
403 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Reid Spencer5f016e22007-07-11 17:01:13 +0000405 // C99 6.2.5p2.
406 InitBuiltinType(BoolTy, BuiltinType::Bool);
407 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000408 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 InitBuiltinType(CharTy, BuiltinType::Char_S);
410 else
411 InitBuiltinType(CharTy, BuiltinType::Char_U);
412 // C99 6.2.5p4.
413 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
414 InitBuiltinType(ShortTy, BuiltinType::Short);
415 InitBuiltinType(IntTy, BuiltinType::Int);
416 InitBuiltinType(LongTy, BuiltinType::Long);
417 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 // C99 6.2.5p6.
420 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
421 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
422 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
423 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
424 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 // C99 6.2.5p10.
427 InitBuiltinType(FloatTy, BuiltinType::Float);
428 InitBuiltinType(DoubleTy, BuiltinType::Double);
429 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000430
Chris Lattner2df9ced2009-04-30 02:43:43 +0000431 // GNU extension, 128-bit integers.
432 InitBuiltinType(Int128Ty, BuiltinType::Int128);
433 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
434
Chris Lattner3f59c972010-12-25 23:25:43 +0000435 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000436 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000437 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
438 else // -fshort-wchar makes wchar_t be unsigned.
439 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
440 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000441 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000442
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000443 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
444 InitBuiltinType(Char16Ty, BuiltinType::Char16);
445 else // C99
446 Char16Ty = getFromTargetType(Target.getChar16Type());
447
448 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
449 InitBuiltinType(Char32Ty, BuiltinType::Char32);
450 else // C99
451 Char32Ty = getFromTargetType(Target.getChar32Type());
452
Douglas Gregor898574e2008-12-05 23:32:09 +0000453 // Placeholder type for type-dependent expressions whose type is
454 // completely unknown. No code should ever check a type against
455 // DependentTy and users should never see it; however, it is here to
456 // help diagnose failures to properly check for type-dependent
457 // expressions.
458 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000459
John McCall2a984ca2010-10-12 00:20:44 +0000460 // Placeholder type for functions.
461 InitBuiltinType(OverloadTy, BuiltinType::Overload);
462
John McCall864c0412011-04-26 20:42:42 +0000463 // Placeholder type for bound members.
464 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
465
John McCall3c3b7f92011-10-25 17:37:35 +0000466 // Placeholder type for pseudo-objects.
467 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
468
John McCall1de4d4e2011-04-07 08:22:57 +0000469 // "any" type; useful for debugger-like clients.
470 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
471
John McCall0ddaeb92011-10-17 18:09:15 +0000472 // Placeholder type for unbridged ARC casts.
473 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
474
Reid Spencer5f016e22007-07-11 17:01:13 +0000475 // C99 6.2.5p11.
476 FloatComplexTy = getComplexType(FloatTy);
477 DoubleComplexTy = getComplexType(DoubleTy);
478 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000479
Steve Naroff7e219e42007-10-15 14:41:52 +0000480 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000482 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000483 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
484 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000485 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000486
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000487 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000489 // void * type
490 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000491
492 // nullptr type (C++0x 2.14.7)
493 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000494
495 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
496 InitBuiltinType(HalfTy, BuiltinType::Half);
Reid Spencer5f016e22007-07-11 17:01:13 +0000497}
498
David Blaikied6471f72011-09-25 23:23:43 +0000499DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000500 return SourceMgr.getDiagnostics();
501}
502
Douglas Gregor63200642010-08-30 16:49:28 +0000503AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
504 AttrVec *&Result = DeclAttrs[D];
505 if (!Result) {
506 void *Mem = Allocate(sizeof(AttrVec));
507 Result = new (Mem) AttrVec;
508 }
509
510 return *Result;
511}
512
513/// \brief Erase the attributes corresponding to the given declaration.
514void ASTContext::eraseDeclAttrs(const Decl *D) {
515 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
516 if (Pos != DeclAttrs.end()) {
517 Pos->second->~AttrVec();
518 DeclAttrs.erase(Pos);
519 }
520}
521
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000522MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000523ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000524 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000525 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000526 = InstantiatedFromStaticDataMember.find(Var);
527 if (Pos == InstantiatedFromStaticDataMember.end())
528 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregor7caa6822009-07-24 20:34:43 +0000530 return Pos->second;
531}
532
Mike Stump1eb44332009-09-09 15:08:12 +0000533void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000534ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000535 TemplateSpecializationKind TSK,
536 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000537 assert(Inst->isStaticDataMember() && "Not a static data member");
538 assert(Tmpl->isStaticDataMember() && "Not a static data member");
539 assert(!InstantiatedFromStaticDataMember[Inst] &&
540 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000541 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000542 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000543}
544
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000545FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
546 const FunctionDecl *FD){
547 assert(FD && "Specialization is 0");
548 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000549 = ClassScopeSpecializationPattern.find(FD);
550 if (Pos == ClassScopeSpecializationPattern.end())
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000551 return 0;
552
553 return Pos->second;
554}
555
556void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
557 FunctionDecl *Pattern) {
558 assert(FD && "Specialization is 0");
559 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet0d95f0d2011-08-14 14:28:49 +0000560 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000561}
562
John McCall7ba107a2009-11-18 02:36:19 +0000563NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000564ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000565 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000566 = InstantiatedFromUsingDecl.find(UUD);
567 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000568 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Anders Carlsson0d8df782009-08-29 19:37:28 +0000570 return Pos->second;
571}
572
573void
John McCalled976492009-12-04 22:46:56 +0000574ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
575 assert((isa<UsingDecl>(Pattern) ||
576 isa<UnresolvedUsingValueDecl>(Pattern) ||
577 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
578 "pattern decl is not a using decl");
579 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
580 InstantiatedFromUsingDecl[Inst] = Pattern;
581}
582
583UsingShadowDecl *
584ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
585 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
586 = InstantiatedFromUsingShadowDecl.find(Inst);
587 if (Pos == InstantiatedFromUsingShadowDecl.end())
588 return 0;
589
590 return Pos->second;
591}
592
593void
594ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
595 UsingShadowDecl *Pattern) {
596 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
597 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000598}
599
Anders Carlssond8b285f2009-09-01 04:26:58 +0000600FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
601 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
602 = InstantiatedFromUnnamedFieldDecl.find(Field);
603 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
604 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Anders Carlssond8b285f2009-09-01 04:26:58 +0000606 return Pos->second;
607}
608
609void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
610 FieldDecl *Tmpl) {
611 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
612 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
613 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
614 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Anders Carlssond8b285f2009-09-01 04:26:58 +0000616 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
617}
618
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000619bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
620 const FieldDecl *LastFD) const {
621 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000622 FD->getBitWidthValue(*this) == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000623}
624
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000625bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
626 const FieldDecl *LastFD) const {
627 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000628 FD->getBitWidthValue(*this) == 0 &&
629 LastFD->getBitWidthValue(*this) != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000630}
631
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000632bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
633 const FieldDecl *LastFD) const {
634 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000635 FD->getBitWidthValue(*this) &&
636 LastFD->getBitWidthValue(*this));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000637}
638
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000639bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000640 const FieldDecl *LastFD) const {
641 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000642 LastFD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000643}
644
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000645bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000646 const FieldDecl *LastFD) const {
647 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000648 FD->getBitWidthValue(*this));
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000649}
650
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000651ASTContext::overridden_cxx_method_iterator
652ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
653 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
654 = OverriddenMethods.find(Method);
655 if (Pos == OverriddenMethods.end())
656 return 0;
657
658 return Pos->second.begin();
659}
660
661ASTContext::overridden_cxx_method_iterator
662ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
663 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
664 = OverriddenMethods.find(Method);
665 if (Pos == OverriddenMethods.end())
666 return 0;
667
668 return Pos->second.end();
669}
670
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000671unsigned
672ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
673 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
674 = OverriddenMethods.find(Method);
675 if (Pos == OverriddenMethods.end())
676 return 0;
677
678 return Pos->second.size();
679}
680
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000681void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
682 const CXXMethodDecl *Overridden) {
683 OverriddenMethods[Method].push_back(Overridden);
684}
685
Douglas Gregore6649772011-12-03 00:30:27 +0000686void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
687 assert(!Import->NextLocalImport && "Import declaration already in the chain");
688 assert(!Import->isFromASTFile() && "Non-local import declaration");
689 if (!FirstLocalImport) {
690 FirstLocalImport = Import;
691 LastLocalImport = Import;
692 return;
693 }
694
695 LastLocalImport->NextLocalImport = Import;
696 LastLocalImport = Import;
697}
698
Chris Lattner464175b2007-07-18 17:52:12 +0000699//===----------------------------------------------------------------------===//
700// Type Sizing and Analysis
701//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000702
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000703/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
704/// scalar floating point type.
705const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000706 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000707 assert(BT && "Not a floating point type!");
708 switch (BT->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000709 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000710 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000711 case BuiltinType::Float: return Target->getFloatFormat();
712 case BuiltinType::Double: return Target->getDoubleFormat();
713 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000714 }
715}
716
Ken Dyck8b752f12010-01-27 17:10:57 +0000717/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000718/// specified decl. Note that bitfields do not have a valid alignment, so
719/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000720/// If @p RefAsPointee, references are treated like their underlying type
721/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000722CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000723 unsigned Align = Target->getCharWidth();
Eli Friedmandcdafb62009-02-22 02:56:25 +0000724
John McCall4081a5c2010-10-08 18:24:19 +0000725 bool UseAlignAttrOnly = false;
726 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
727 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000728
John McCall4081a5c2010-10-08 18:24:19 +0000729 // __attribute__((aligned)) can increase or decrease alignment
730 // *except* on a struct or struct member, where it only increases
731 // alignment unless 'packed' is also specified.
732 //
Peter Collingbourne82d0b0a2011-09-29 18:04:28 +0000733 // It is an error for alignas to decrease alignment, so we can
John McCall4081a5c2010-10-08 18:24:19 +0000734 // ignore that possibility; Sema should diagnose it.
735 if (isa<FieldDecl>(D)) {
736 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
737 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
738 } else {
739 UseAlignAttrOnly = true;
740 }
741 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000742 else if (isa<FieldDecl>(D))
743 UseAlignAttrOnly =
744 D->hasAttr<PackedAttr>() ||
745 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000746
John McCallba4f5d52011-01-20 07:57:12 +0000747 // If we're using the align attribute only, just ignore everything
748 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000749 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000750 // do nothing
751
John McCall4081a5c2010-10-08 18:24:19 +0000752 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000753 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000754 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000755 if (RefAsPointee)
756 T = RT->getPointeeType();
757 else
758 T = getPointerType(RT->getPointeeType());
759 }
760 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000761 // Adjust alignments of declarations with array type by the
762 // large-array alignment on the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000763 unsigned MinWidth = Target->getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000764 const ArrayType *arrayType;
765 if (MinWidth && (arrayType = getAsArrayType(T))) {
766 if (isa<VariableArrayType>(arrayType))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000767 Align = std::max(Align, Target->getLargeArrayAlign());
John McCall3b657512011-01-19 10:06:00 +0000768 else if (isa<ConstantArrayType>(arrayType) &&
769 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000770 Align = std::max(Align, Target->getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000771
John McCall3b657512011-01-19 10:06:00 +0000772 // Walk through any array types while we're at it.
773 T = getBaseElementType(arrayType);
774 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000775 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000776 }
John McCallba4f5d52011-01-20 07:57:12 +0000777
778 // Fields can be subject to extra alignment constraints, like if
779 // the field is packed, the struct is packed, or the struct has a
780 // a max-field-alignment constraint (#pragma pack). So calculate
781 // the actual alignment of the field within the struct, and then
782 // (as we're expected to) constrain that by the alignment of the type.
783 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
784 // So calculate the alignment of the field.
785 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
786
787 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000788 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000789
790 // Use the GCD of that and the offset within the record.
791 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
792 if (offset > 0) {
793 // Alignment is always a power of 2, so the GCD will be a power of 2,
794 // which means we get to do this crazy thing instead of Euclid's.
795 uint64_t lowBitOfOffset = offset & (~offset + 1);
796 if (lowBitOfOffset < fieldAlign)
797 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
798 }
799
800 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000801 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000802 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000803
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000804 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000805}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000806
John McCallea1471e2010-05-20 01:18:31 +0000807std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000808ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000809 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000810 return std::make_pair(toCharUnitsFromBits(Info.first),
811 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000812}
813
814std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000815ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000816 return getTypeInfoInChars(T.getTypePtr());
817}
818
Chris Lattnera7674d82007-07-13 22:13:22 +0000819/// getTypeSize - Return the size of the specified type, in bits. This method
820/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000821///
822/// FIXME: Pointers into different addr spaces could have different sizes and
823/// alignment requirements: getPointerInfo should take an AddrSpace, this
824/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000825std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000826ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000827 uint64_t Width=0;
828 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000829 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000830#define TYPE(Class, Base)
831#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000832#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000833#define DEPENDENT_TYPE(Class, Base) case Type::Class:
834#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000835 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000836 break;
837
Chris Lattner692233e2007-07-13 22:27:08 +0000838 case Type::FunctionNoProto:
839 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000840 // GCC extension: alignof(function) = 32 bits
841 Width = 0;
842 Align = 32;
843 break;
844
Douglas Gregor72564e72009-02-26 23:50:07 +0000845 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000846 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000847 Width = 0;
848 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
849 break;
850
Steve Narofffb22d962007-08-30 01:06:46 +0000851 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000852 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Chris Lattner98be4942008-03-05 18:54:05 +0000854 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarafea966a2011-12-13 11:23:52 +0000855 uint64_t Size = CAT->getSize().getZExtValue();
856 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
857 Width = EltInfo.first*Size;
Chris Lattner030d8842007-07-19 22:06:24 +0000858 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000859 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000860 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000861 }
Nate Begeman213541a2008-04-18 23:10:10 +0000862 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000863 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000864 const VectorType *VT = cast<VectorType>(T);
865 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
866 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000867 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000868 // If the alignment is not a power of 2, round up to the next power of 2.
869 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000870 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000871 Align = llvm::NextPowerOf2(Align);
872 Width = llvm::RoundUpToAlignment(Width, Align);
873 }
Chris Lattner030d8842007-07-19 22:06:24 +0000874 break;
875 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000876
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000877 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000878 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000879 default: llvm_unreachable("Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000880 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000881 // GCC extension: alignof(void) = 8 bits.
882 Width = 0;
883 Align = 8;
884 break;
885
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000886 case BuiltinType::Bool:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000887 Width = Target->getBoolWidth();
888 Align = Target->getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000889 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000890 case BuiltinType::Char_S:
891 case BuiltinType::Char_U:
892 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000893 case BuiltinType::SChar:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000894 Width = Target->getCharWidth();
895 Align = Target->getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000896 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000897 case BuiltinType::WChar_S:
898 case BuiltinType::WChar_U:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000899 Width = Target->getWCharWidth();
900 Align = Target->getWCharAlign();
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000901 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000902 case BuiltinType::Char16:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000903 Width = Target->getChar16Width();
904 Align = Target->getChar16Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000905 break;
906 case BuiltinType::Char32:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000907 Width = Target->getChar32Width();
908 Align = Target->getChar32Align();
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000909 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000910 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000911 case BuiltinType::Short:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000912 Width = Target->getShortWidth();
913 Align = Target->getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000914 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000915 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000916 case BuiltinType::Int:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000917 Width = Target->getIntWidth();
918 Align = Target->getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000919 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000920 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000921 case BuiltinType::Long:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000922 Width = Target->getLongWidth();
923 Align = Target->getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000924 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000925 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000926 case BuiltinType::LongLong:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000927 Width = Target->getLongLongWidth();
928 Align = Target->getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000929 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000930 case BuiltinType::Int128:
931 case BuiltinType::UInt128:
932 Width = 128;
933 Align = 128; // int128_t is 128-bit aligned on all targets.
934 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000935 case BuiltinType::Half:
936 Width = Target->getHalfWidth();
937 Align = Target->getHalfAlign();
938 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000939 case BuiltinType::Float:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000940 Width = Target->getFloatWidth();
941 Align = Target->getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000942 break;
943 case BuiltinType::Double:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000944 Width = Target->getDoubleWidth();
945 Align = Target->getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000946 break;
947 case BuiltinType::LongDouble:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000948 Width = Target->getLongDoubleWidth();
949 Align = Target->getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000950 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000951 case BuiltinType::NullPtr:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000952 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
953 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000954 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000955 case BuiltinType::ObjCId:
956 case BuiltinType::ObjCClass:
957 case BuiltinType::ObjCSel:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000958 Width = Target->getPointerWidth(0);
959 Align = Target->getPointerAlign(0);
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000960 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000961 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000962 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000963 case Type::ObjCObjectPointer:
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000964 Width = Target->getPointerWidth(0);
965 Align = Target->getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000966 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000967 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000968 unsigned AS = getTargetAddressSpace(
969 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000970 Width = Target->getPointerWidth(AS);
971 Align = Target->getPointerAlign(AS);
Steve Naroff485eeff2008-09-24 15:05:44 +0000972 break;
973 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000974 case Type::LValueReference:
975 case Type::RValueReference: {
976 // alignof and sizeof should never enter this code path here, so we go
977 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000978 unsigned AS = getTargetAddressSpace(
979 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000980 Width = Target->getPointerWidth(AS);
981 Align = Target->getPointerAlign(AS);
Sebastian Redl5d484e82009-11-23 17:18:46 +0000982 break;
983 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000984 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000985 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000986 Width = Target->getPointerWidth(AS);
987 Align = Target->getPointerAlign(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000988 break;
989 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000990 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000991 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000992 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000993 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000994 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000995 Align = PtrDiffInfo.second;
996 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000997 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000998 case Type::Complex: {
999 // Complex types have the same alignment as their elements, but twice the
1000 // size.
Mike Stump1eb44332009-09-09 15:08:12 +00001001 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +00001002 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001003 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +00001004 Align = EltInfo.second;
1005 break;
1006 }
John McCallc12c5bb2010-05-15 11:32:37 +00001007 case Type::ObjCObject:
1008 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +00001009 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001010 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +00001011 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001012 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001013 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +00001014 break;
1015 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001016 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00001017 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +00001018 const TagType *TT = cast<TagType>(T);
1019
1020 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +00001021 Width = 8;
1022 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +00001023 break;
1024 }
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Daniel Dunbar1d751182008-11-08 05:48:37 +00001026 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +00001027 return getTypeInfo(ET->getDecl()->getIntegerType());
1028
Daniel Dunbar1d751182008-11-08 05:48:37 +00001029 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +00001030 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001031 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +00001032 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +00001033 break;
Chris Lattnera7674d82007-07-13 22:13:22 +00001034 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001035
Chris Lattner9fcfe922009-10-22 05:17:15 +00001036 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +00001037 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1038 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +00001039
Richard Smith34b41d92011-02-20 03:19:35 +00001040 case Type::Auto: {
1041 const AutoType *A = cast<AutoType>(T);
1042 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +00001043 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +00001044 }
1045
Abramo Bagnara075f8f12010-12-10 16:29:40 +00001046 case Type::Paren:
1047 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1048
Douglas Gregor18857642009-04-30 17:32:17 +00001049 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +00001050 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +00001051 std::pair<uint64_t, unsigned> Info
1052 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +00001053 // If the typedef has an aligned attribute on it, it overrides any computed
1054 // alignment we have. This violates the GCC documentation (which says that
1055 // attribute(aligned) can only round up) but matches its implementation.
1056 if (unsigned AttrAlign = Typedef->getMaxAlignment())
1057 Align = AttrAlign;
1058 else
1059 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +00001060 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +00001061 break;
Chris Lattner71763312008-04-06 22:05:18 +00001062 }
Douglas Gregor18857642009-04-30 17:32:17 +00001063
1064 case Type::TypeOfExpr:
1065 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1066 .getTypePtr());
1067
1068 case Type::TypeOf:
1069 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1070
Anders Carlsson395b4752009-06-24 19:06:50 +00001071 case Type::Decltype:
1072 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1073 .getTypePtr());
1074
Sean Huntca63c202011-05-24 22:41:36 +00001075 case Type::UnaryTransform:
1076 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1077
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001078 case Type::Elaborated:
1079 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +00001080
John McCall9d156a72011-01-06 01:58:22 +00001081 case Type::Attributed:
1082 return getTypeInfo(
1083 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1084
Richard Smith3e4c6c42011-05-05 21:57:07 +00001085 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00001086 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001087 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001088 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1089 // A type alias template specialization may refer to a typedef with the
1090 // aligned attribute on it.
1091 if (TST->isTypeAlias())
1092 return getTypeInfo(TST->getAliasedType().getTypePtr());
1093 else
1094 return getTypeInfo(getCanonicalType(T));
1095 }
1096
Eli Friedmanb001de72011-10-06 23:00:33 +00001097 case Type::Atomic: {
Eli Friedman2be46072011-10-14 20:59:01 +00001098 std::pair<uint64_t, unsigned> Info
1099 = getTypeInfo(cast<AtomicType>(T)->getValueType());
1100 Width = Info.first;
1101 Align = Info.second;
1102 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1103 llvm::isPowerOf2_64(Width)) {
1104 // We can potentially perform lock-free atomic operations for this
1105 // type; promote the alignment appropriately.
1106 // FIXME: We could potentially promote the width here as well...
1107 // is that worthwhile? (Non-struct atomic types generally have
1108 // power-of-two size anyway, but structs might not. Requires a bit
1109 // of implementation work to make sure we zero out the extra bits.)
1110 Align = static_cast<unsigned>(Width);
1111 }
Eli Friedmanb001de72011-10-06 23:00:33 +00001112 }
1113
Douglas Gregor18857642009-04-30 17:32:17 +00001114 }
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Eli Friedman2be46072011-10-14 20:59:01 +00001116 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001117 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001118}
1119
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001120/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1121CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1122 return CharUnits::fromQuantity(BitSize / getCharWidth());
1123}
1124
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001125/// toBits - Convert a size in characters to a size in characters.
1126int64_t ASTContext::toBits(CharUnits CharSize) const {
1127 return CharSize.getQuantity() * getCharWidth();
1128}
1129
Ken Dyckbdc601b2009-12-22 14:23:30 +00001130/// getTypeSizeInChars - Return the size of the specified type, in characters.
1131/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001132CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001133 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001134}
Jay Foad4ba2a172011-01-12 09:06:06 +00001135CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001136 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001137}
1138
Ken Dyck16e20cc2010-01-26 17:25:18 +00001139/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001140/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001141CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001142 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001143}
Jay Foad4ba2a172011-01-12 09:06:06 +00001144CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001145 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001146}
1147
Chris Lattner34ebde42009-01-27 18:08:34 +00001148/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1149/// type for the current target in bits. This can be different than the ABI
1150/// alignment in cases where it is beneficial for performance to overalign
1151/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001152unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001153 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001154
1155 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001156 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001157 T = CT->getElementType().getTypePtr();
1158 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1159 T->isSpecificBuiltinType(BuiltinType::LongLong))
1160 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1161
Chris Lattner34ebde42009-01-27 18:08:34 +00001162 return ABIAlign;
1163}
1164
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001165/// DeepCollectObjCIvars -
1166/// This routine first collects all declared, but not synthesized, ivars in
1167/// super class and then collects all ivars, including those synthesized for
1168/// current class. This routine is used for implementation of current class
1169/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001170///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001171void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1172 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001173 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001174 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1175 DeepCollectObjCIvars(SuperClass, false, Ivars);
1176 if (!leafClass) {
1177 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1178 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001179 Ivars.push_back(*I);
Chad Rosier30601782011-08-17 23:08:45 +00001180 } else {
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001181 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001182 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001183 Iv= Iv->getNextIvar())
1184 Ivars.push_back(Iv);
1185 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001186}
1187
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001188/// CollectInheritedProtocols - Collect all protocols in current class and
1189/// those inherited by it.
1190void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001191 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001192 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001193 // We can use protocol_iterator here instead of
1194 // all_referenced_protocol_iterator since we are walking all categories.
1195 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1196 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001197 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001198 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001199 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001200 PE = Proto->protocol_end(); P != PE; ++P) {
1201 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001202 CollectInheritedProtocols(*P, Protocols);
1203 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001204 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001205
1206 // Categories of this Interface.
1207 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1208 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1209 CollectInheritedProtocols(CDeclChain, Protocols);
1210 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1211 while (SD) {
1212 CollectInheritedProtocols(SD, Protocols);
1213 SD = SD->getSuperClass();
1214 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001215 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001216 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001217 PE = OC->protocol_end(); P != PE; ++P) {
1218 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001219 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001220 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1221 PE = Proto->protocol_end(); P != PE; ++P)
1222 CollectInheritedProtocols(*P, Protocols);
1223 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001224 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001225 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1226 PE = OP->protocol_end(); P != PE; ++P) {
1227 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001228 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001229 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1230 PE = Proto->protocol_end(); P != PE; ++P)
1231 CollectInheritedProtocols(*P, Protocols);
1232 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001233 }
1234}
1235
Jay Foad4ba2a172011-01-12 09:06:06 +00001236unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001237 unsigned count = 0;
1238 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001239 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1240 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001241 count += CDecl->ivar_size();
1242
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001243 // Count ivar defined in this class's implementation. This
1244 // includes synthesized ivars.
1245 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001246 count += ImplDecl->ivar_size();
1247
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001248 return count;
1249}
1250
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001251/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1252ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1253 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1254 I = ObjCImpls.find(D);
1255 if (I != ObjCImpls.end())
1256 return cast<ObjCImplementationDecl>(I->second);
1257 return 0;
1258}
1259/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1260ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1261 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1262 I = ObjCImpls.find(D);
1263 if (I != ObjCImpls.end())
1264 return cast<ObjCCategoryImplDecl>(I->second);
1265 return 0;
1266}
1267
1268/// \brief Set the implementation of ObjCInterfaceDecl.
1269void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1270 ObjCImplementationDecl *ImplD) {
1271 assert(IFaceD && ImplD && "Passed null params");
1272 ObjCImpls[IFaceD] = ImplD;
1273}
1274/// \brief Set the implementation of ObjCCategoryDecl.
1275void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1276 ObjCCategoryImplDecl *ImplD) {
1277 assert(CatD && ImplD && "Passed null params");
1278 ObjCImpls[CatD] = ImplD;
1279}
1280
Argyrios Kyrtzidis87ec9c22011-11-01 17:14:12 +00001281ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1282 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1283 return ID;
1284 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1285 return CD->getClassInterface();
1286 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1287 return IMD->getClassInterface();
1288
1289 return 0;
1290}
1291
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001292/// \brief Get the copy initialization expression of VarDecl,or NULL if
1293/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001294Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001295 assert(VD && "Passed null params");
1296 assert(VD->hasAttr<BlocksAttr>() &&
1297 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001298 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001299 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001300 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1301}
1302
1303/// \brief Set the copy inialization expression of a block var decl.
1304void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1305 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001306 assert(VD->hasAttr<BlocksAttr>() &&
1307 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001308 BlockVarCopyInits[VD] = Init;
1309}
1310
John McCalla93c9342009-12-07 02:54:59 +00001311/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001312///
John McCalla93c9342009-12-07 02:54:59 +00001313/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001314/// the TypeLoc wrappers.
1315///
1316/// \param T the type that will be the basis for type source info. This type
1317/// should refer to how the declarator was written in source code, not to
1318/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001319TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001320 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001321 if (!DataSize)
1322 DataSize = TypeLoc::getFullDataSizeForType(T);
1323 else
1324 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001325 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001326
John McCalla93c9342009-12-07 02:54:59 +00001327 TypeSourceInfo *TInfo =
1328 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1329 new (TInfo) TypeSourceInfo(T);
1330 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001331}
1332
John McCalla93c9342009-12-07 02:54:59 +00001333TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001334 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001335 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001336 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001337 return DI;
1338}
1339
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001340const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001341ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001342 return getObjCLayout(D, 0);
1343}
1344
1345const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001346ASTContext::getASTObjCImplementationLayout(
1347 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001348 return getObjCLayout(D->getClassInterface(), D);
1349}
1350
Chris Lattnera7674d82007-07-13 22:13:22 +00001351//===----------------------------------------------------------------------===//
1352// Type creation/memoization methods
1353//===----------------------------------------------------------------------===//
1354
Jay Foad4ba2a172011-01-12 09:06:06 +00001355QualType
John McCall3b657512011-01-19 10:06:00 +00001356ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1357 unsigned fastQuals = quals.getFastQualifiers();
1358 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001359
1360 // Check if we've already instantiated this type.
1361 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001362 ExtQuals::Profile(ID, baseType, quals);
1363 void *insertPos = 0;
1364 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1365 assert(eq->getQualifiers() == quals);
1366 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001367 }
1368
John McCall3b657512011-01-19 10:06:00 +00001369 // If the base type is not canonical, make the appropriate canonical type.
1370 QualType canon;
1371 if (!baseType->isCanonicalUnqualified()) {
1372 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1373 canonSplit.second.addConsistentQualifiers(quals);
1374 canon = getExtQualType(canonSplit.first, canonSplit.second);
1375
1376 // Re-find the insert position.
1377 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1378 }
1379
1380 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1381 ExtQualNodes.InsertNode(eq, insertPos);
1382 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001383}
1384
Jay Foad4ba2a172011-01-12 09:06:06 +00001385QualType
1386ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001387 QualType CanT = getCanonicalType(T);
1388 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001389 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001390
John McCall0953e762009-09-24 19:53:00 +00001391 // If we are composing extended qualifiers together, merge together
1392 // into one ExtQuals node.
1393 QualifierCollector Quals;
1394 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001395
John McCall0953e762009-09-24 19:53:00 +00001396 // If this type already has an address space specified, it cannot get
1397 // another one.
1398 assert(!Quals.hasAddressSpace() &&
1399 "Type cannot be in multiple addr spaces!");
1400 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001401
John McCall0953e762009-09-24 19:53:00 +00001402 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001403}
1404
Chris Lattnerb7d25532009-02-18 22:53:11 +00001405QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001406 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001407 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001408 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001409 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001410
John McCall7f040a92010-12-24 02:08:15 +00001411 if (const PointerType *ptr = T->getAs<PointerType>()) {
1412 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001413 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001414 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1415 return getPointerType(ResultType);
1416 }
1417 }
Mike Stump1eb44332009-09-09 15:08:12 +00001418
John McCall0953e762009-09-24 19:53:00 +00001419 // If we are composing extended qualifiers together, merge together
1420 // into one ExtQuals node.
1421 QualifierCollector Quals;
1422 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001423
John McCall0953e762009-09-24 19:53:00 +00001424 // If this type already has an ObjCGC specified, it cannot get
1425 // another one.
1426 assert(!Quals.hasObjCGCAttr() &&
1427 "Type cannot have multiple ObjCGCs!");
1428 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
John McCall0953e762009-09-24 19:53:00 +00001430 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001431}
Chris Lattnera7674d82007-07-13 22:13:22 +00001432
John McCalle6a365d2010-12-19 02:44:49 +00001433const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1434 FunctionType::ExtInfo Info) {
1435 if (T->getExtInfo() == Info)
1436 return T;
1437
1438 QualType Result;
1439 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1440 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1441 } else {
1442 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1443 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1444 EPI.ExtInfo = Info;
1445 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1446 FPT->getNumArgs(), EPI);
1447 }
1448
1449 return cast<FunctionType>(Result.getTypePtr());
1450}
1451
Reid Spencer5f016e22007-07-11 17:01:13 +00001452/// getComplexType - Return the uniqued reference to the type for a complex
1453/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001454QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001455 // Unique pointers, to guarantee there is only one pointer of a particular
1456 // structure.
1457 llvm::FoldingSetNodeID ID;
1458 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Reid Spencer5f016e22007-07-11 17:01:13 +00001460 void *InsertPos = 0;
1461 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1462 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Reid Spencer5f016e22007-07-11 17:01:13 +00001464 // If the pointee type isn't canonical, this won't be a canonical type either,
1465 // so fill in the canonical type field.
1466 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001467 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001468 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Reid Spencer5f016e22007-07-11 17:01:13 +00001470 // Get the new insert position for the node we care about.
1471 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001472 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001473 }
John McCall6b304a02009-09-24 23:30:46 +00001474 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 Types.push_back(New);
1476 ComplexTypes.InsertNode(New, InsertPos);
1477 return QualType(New, 0);
1478}
1479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480/// getPointerType - Return the uniqued reference to the type for a pointer to
1481/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001482QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001483 // Unique pointers, to guarantee there is only one pointer of a particular
1484 // structure.
1485 llvm::FoldingSetNodeID ID;
1486 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Reid Spencer5f016e22007-07-11 17:01:13 +00001488 void *InsertPos = 0;
1489 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1490 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 // If the pointee type isn't canonical, this won't be a canonical type either,
1493 // so fill in the canonical type field.
1494 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001495 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001496 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Reid Spencer5f016e22007-07-11 17:01:13 +00001498 // Get the new insert position for the node we care about.
1499 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001500 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001501 }
John McCall6b304a02009-09-24 23:30:46 +00001502 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001503 Types.push_back(New);
1504 PointerTypes.InsertNode(New, InsertPos);
1505 return QualType(New, 0);
1506}
1507
Mike Stump1eb44332009-09-09 15:08:12 +00001508/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001509/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001510QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001511 assert(T->isFunctionType() && "block of function types only");
1512 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001513 // structure.
1514 llvm::FoldingSetNodeID ID;
1515 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Steve Naroff5618bd42008-08-27 16:04:49 +00001517 void *InsertPos = 0;
1518 if (BlockPointerType *PT =
1519 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1520 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
1522 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001523 // type either so fill in the canonical type field.
1524 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001525 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001526 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Steve Naroff5618bd42008-08-27 16:04:49 +00001528 // Get the new insert position for the node we care about.
1529 BlockPointerType *NewIP =
1530 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001531 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001532 }
John McCall6b304a02009-09-24 23:30:46 +00001533 BlockPointerType *New
1534 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001535 Types.push_back(New);
1536 BlockPointerTypes.InsertNode(New, InsertPos);
1537 return QualType(New, 0);
1538}
1539
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001540/// getLValueReferenceType - Return the uniqued reference to the type for an
1541/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001542QualType
1543ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001544 assert(getCanonicalType(T) != OverloadTy &&
1545 "Unresolved overloaded function type");
1546
Reid Spencer5f016e22007-07-11 17:01:13 +00001547 // Unique pointers, to guarantee there is only one pointer of a particular
1548 // structure.
1549 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001550 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001551
1552 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001553 if (LValueReferenceType *RT =
1554 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001556
John McCall54e14c42009-10-22 22:37:11 +00001557 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1558
Reid Spencer5f016e22007-07-11 17:01:13 +00001559 // If the referencee type isn't canonical, this won't be a canonical type
1560 // either, so fill in the canonical type field.
1561 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001562 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1563 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1564 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001567 LValueReferenceType *NewIP =
1568 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001569 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001570 }
1571
John McCall6b304a02009-09-24 23:30:46 +00001572 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001573 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1574 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001576 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001577
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001578 return QualType(New, 0);
1579}
1580
1581/// getRValueReferenceType - Return the uniqued reference to the type for an
1582/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001583QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001584 // Unique pointers, to guarantee there is only one pointer of a particular
1585 // structure.
1586 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001587 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001588
1589 void *InsertPos = 0;
1590 if (RValueReferenceType *RT =
1591 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1592 return QualType(RT, 0);
1593
John McCall54e14c42009-10-22 22:37:11 +00001594 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1595
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001596 // If the referencee type isn't canonical, this won't be a canonical type
1597 // either, so fill in the canonical type field.
1598 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001599 if (InnerRef || !T.isCanonical()) {
1600 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1601 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001602
1603 // Get the new insert position for the node we care about.
1604 RValueReferenceType *NewIP =
1605 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001606 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001607 }
1608
John McCall6b304a02009-09-24 23:30:46 +00001609 RValueReferenceType *New
1610 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001611 Types.push_back(New);
1612 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 return QualType(New, 0);
1614}
1615
Sebastian Redlf30208a2009-01-24 21:16:55 +00001616/// getMemberPointerType - Return the uniqued reference to the type for a
1617/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001618QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001619 // Unique pointers, to guarantee there is only one pointer of a particular
1620 // structure.
1621 llvm::FoldingSetNodeID ID;
1622 MemberPointerType::Profile(ID, T, Cls);
1623
1624 void *InsertPos = 0;
1625 if (MemberPointerType *PT =
1626 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1627 return QualType(PT, 0);
1628
1629 // If the pointee or class type isn't canonical, this won't be a canonical
1630 // type either, so fill in the canonical type field.
1631 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001632 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001633 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1634
1635 // Get the new insert position for the node we care about.
1636 MemberPointerType *NewIP =
1637 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001638 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001639 }
John McCall6b304a02009-09-24 23:30:46 +00001640 MemberPointerType *New
1641 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001642 Types.push_back(New);
1643 MemberPointerTypes.InsertNode(New, InsertPos);
1644 return QualType(New, 0);
1645}
1646
Mike Stump1eb44332009-09-09 15:08:12 +00001647/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001648/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001649QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001650 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001651 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001652 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001653 assert((EltTy->isDependentType() ||
1654 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001655 "Constant array of VLAs is illegal!");
1656
Chris Lattner38aeec72009-05-13 04:12:56 +00001657 // Convert the array size into a canonical width matching the pointer size for
1658 // the target.
1659 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001660 ArySize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001661 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001664 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001667 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001668 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001669 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
John McCall3b657512011-01-19 10:06:00 +00001671 // If the element type isn't canonical or has qualifiers, this won't
1672 // be a canonical type either, so fill in the canonical type field.
1673 QualType Canon;
1674 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1675 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1676 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001677 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001678 Canon = getQualifiedType(Canon, canonSplit.second);
1679
Reid Spencer5f016e22007-07-11 17:01:13 +00001680 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001681 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001682 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001683 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
John McCall6b304a02009-09-24 23:30:46 +00001686 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001687 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001688 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 Types.push_back(New);
1690 return QualType(New, 0);
1691}
1692
John McCallce889032011-01-18 08:40:38 +00001693/// getVariableArrayDecayedType - Turns the given type, which may be
1694/// variably-modified, into the corresponding type with all the known
1695/// sizes replaced with [*].
1696QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1697 // Vastly most common case.
1698 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001699
John McCallce889032011-01-18 08:40:38 +00001700 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001701
John McCallce889032011-01-18 08:40:38 +00001702 SplitQualType split = type.getSplitDesugaredType();
1703 const Type *ty = split.first;
1704 switch (ty->getTypeClass()) {
1705#define TYPE(Class, Base)
1706#define ABSTRACT_TYPE(Class, Base)
1707#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1708#include "clang/AST/TypeNodes.def"
1709 llvm_unreachable("didn't desugar past all non-canonical types?");
1710
1711 // These types should never be variably-modified.
1712 case Type::Builtin:
1713 case Type::Complex:
1714 case Type::Vector:
1715 case Type::ExtVector:
1716 case Type::DependentSizedExtVector:
1717 case Type::ObjCObject:
1718 case Type::ObjCInterface:
1719 case Type::ObjCObjectPointer:
1720 case Type::Record:
1721 case Type::Enum:
1722 case Type::UnresolvedUsing:
1723 case Type::TypeOfExpr:
1724 case Type::TypeOf:
1725 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001726 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001727 case Type::DependentName:
1728 case Type::InjectedClassName:
1729 case Type::TemplateSpecialization:
1730 case Type::DependentTemplateSpecialization:
1731 case Type::TemplateTypeParm:
1732 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001733 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001734 case Type::PackExpansion:
1735 llvm_unreachable("type should never be variably-modified");
1736
1737 // These types can be variably-modified but should never need to
1738 // further decay.
1739 case Type::FunctionNoProto:
1740 case Type::FunctionProto:
1741 case Type::BlockPointer:
1742 case Type::MemberPointer:
1743 return type;
1744
1745 // These types can be variably-modified. All these modifications
1746 // preserve structure except as noted by comments.
1747 // TODO: if we ever care about optimizing VLAs, there are no-op
1748 // optimizations available here.
1749 case Type::Pointer:
1750 result = getPointerType(getVariableArrayDecayedType(
1751 cast<PointerType>(ty)->getPointeeType()));
1752 break;
1753
1754 case Type::LValueReference: {
1755 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1756 result = getLValueReferenceType(
1757 getVariableArrayDecayedType(lv->getPointeeType()),
1758 lv->isSpelledAsLValue());
1759 break;
1760 }
1761
1762 case Type::RValueReference: {
1763 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1764 result = getRValueReferenceType(
1765 getVariableArrayDecayedType(lv->getPointeeType()));
1766 break;
1767 }
1768
Eli Friedmanb001de72011-10-06 23:00:33 +00001769 case Type::Atomic: {
1770 const AtomicType *at = cast<AtomicType>(ty);
1771 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1772 break;
1773 }
1774
John McCallce889032011-01-18 08:40:38 +00001775 case Type::ConstantArray: {
1776 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1777 result = getConstantArrayType(
1778 getVariableArrayDecayedType(cat->getElementType()),
1779 cat->getSize(),
1780 cat->getSizeModifier(),
1781 cat->getIndexTypeCVRQualifiers());
1782 break;
1783 }
1784
1785 case Type::DependentSizedArray: {
1786 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1787 result = getDependentSizedArrayType(
1788 getVariableArrayDecayedType(dat->getElementType()),
1789 dat->getSizeExpr(),
1790 dat->getSizeModifier(),
1791 dat->getIndexTypeCVRQualifiers(),
1792 dat->getBracketsRange());
1793 break;
1794 }
1795
1796 // Turn incomplete types into [*] types.
1797 case Type::IncompleteArray: {
1798 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1799 result = getVariableArrayType(
1800 getVariableArrayDecayedType(iat->getElementType()),
1801 /*size*/ 0,
1802 ArrayType::Normal,
1803 iat->getIndexTypeCVRQualifiers(),
1804 SourceRange());
1805 break;
1806 }
1807
1808 // Turn VLA types into [*] types.
1809 case Type::VariableArray: {
1810 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1811 result = getVariableArrayType(
1812 getVariableArrayDecayedType(vat->getElementType()),
1813 /*size*/ 0,
1814 ArrayType::Star,
1815 vat->getIndexTypeCVRQualifiers(),
1816 vat->getBracketsRange());
1817 break;
1818 }
1819 }
1820
1821 // Apply the top-level qualifiers from the original.
1822 return getQualifiedType(result, split.second);
1823}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001824
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001825/// getVariableArrayType - Returns a non-unique reference to the type for a
1826/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001827QualType ASTContext::getVariableArrayType(QualType EltTy,
1828 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001829 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001830 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001831 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001832 // Since we don't unique expressions, it isn't possible to unique VLA's
1833 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001834 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001835
John McCall3b657512011-01-19 10:06:00 +00001836 // Be sure to pull qualifiers off the element type.
1837 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1838 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1839 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001840 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001841 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001842 }
1843
John McCall6b304a02009-09-24 23:30:46 +00001844 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001845 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001846
1847 VariableArrayTypes.push_back(New);
1848 Types.push_back(New);
1849 return QualType(New, 0);
1850}
1851
Douglas Gregor898574e2008-12-05 23:32:09 +00001852/// getDependentSizedArrayType - Returns a non-unique reference to
1853/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001854/// type.
John McCall3b657512011-01-19 10:06:00 +00001855QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1856 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001857 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001858 unsigned elementTypeQuals,
1859 SourceRange brackets) const {
1860 assert((!numElements || numElements->isTypeDependent() ||
1861 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001862 "Size must be type- or value-dependent!");
1863
John McCall3b657512011-01-19 10:06:00 +00001864 // Dependently-sized array types that do not have a specified number
1865 // of elements will have their sizes deduced from a dependent
1866 // initializer. We do no canonicalization here at all, which is okay
1867 // because they can't be used in most locations.
1868 if (!numElements) {
1869 DependentSizedArrayType *newType
1870 = new (*this, TypeAlignment)
1871 DependentSizedArrayType(*this, elementType, QualType(),
1872 numElements, ASM, elementTypeQuals,
1873 brackets);
1874 Types.push_back(newType);
1875 return QualType(newType, 0);
1876 }
1877
1878 // Otherwise, we actually build a new type every time, but we
1879 // also build a canonical type.
1880
1881 SplitQualType canonElementType = getCanonicalType(elementType).split();
1882
1883 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001884 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001885 DependentSizedArrayType::Profile(ID, *this,
1886 QualType(canonElementType.first, 0),
1887 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001888
John McCall3b657512011-01-19 10:06:00 +00001889 // Look for an existing type with these properties.
1890 DependentSizedArrayType *canonTy =
1891 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001892
John McCall3b657512011-01-19 10:06:00 +00001893 // If we don't have one, build one.
1894 if (!canonTy) {
1895 canonTy = new (*this, TypeAlignment)
1896 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1897 QualType(), numElements, ASM, elementTypeQuals,
1898 brackets);
1899 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1900 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001901 }
1902
John McCall3b657512011-01-19 10:06:00 +00001903 // Apply qualifiers from the element type to the array.
1904 QualType canon = getQualifiedType(QualType(canonTy,0),
1905 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001906
John McCall3b657512011-01-19 10:06:00 +00001907 // If we didn't need extra canonicalization for the element type,
1908 // then just use that as our result.
1909 if (QualType(canonElementType.first, 0) == elementType)
1910 return canon;
1911
1912 // Otherwise, we need to build a type which follows the spelling
1913 // of the element type.
1914 DependentSizedArrayType *sugaredType
1915 = new (*this, TypeAlignment)
1916 DependentSizedArrayType(*this, elementType, canon, numElements,
1917 ASM, elementTypeQuals, brackets);
1918 Types.push_back(sugaredType);
1919 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001920}
1921
John McCall3b657512011-01-19 10:06:00 +00001922QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001923 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001924 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001925 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001926 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001927
John McCall3b657512011-01-19 10:06:00 +00001928 void *insertPos = 0;
1929 if (IncompleteArrayType *iat =
1930 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1931 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001932
1933 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001934 // either, so fill in the canonical type field. We also have to pull
1935 // qualifiers off the element type.
1936 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001937
John McCall3b657512011-01-19 10:06:00 +00001938 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1939 SplitQualType canonSplit = getCanonicalType(elementType).split();
1940 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1941 ASM, elementTypeQuals);
1942 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001943
1944 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001945 IncompleteArrayType *existing =
1946 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1947 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001948 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001949
John McCall3b657512011-01-19 10:06:00 +00001950 IncompleteArrayType *newType = new (*this, TypeAlignment)
1951 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001952
John McCall3b657512011-01-19 10:06:00 +00001953 IncompleteArrayTypes.InsertNode(newType, insertPos);
1954 Types.push_back(newType);
1955 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001956}
1957
Steve Naroff73322922007-07-18 18:00:27 +00001958/// getVectorType - Return the unique reference to a vector type of
1959/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001960QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001961 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001962 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Reid Spencer5f016e22007-07-11 17:01:13 +00001964 // Check if we've already instantiated a vector of this type.
1965 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001966 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001967
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 void *InsertPos = 0;
1969 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1970 return QualType(VTP, 0);
1971
1972 // If the element type isn't canonical, this won't be a canonical type either,
1973 // so fill in the canonical type field.
1974 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001975 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001976 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 // Get the new insert position for the node we care about.
1979 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001980 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001981 }
John McCall6b304a02009-09-24 23:30:46 +00001982 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001983 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 VectorTypes.InsertNode(New, InsertPos);
1985 Types.push_back(New);
1986 return QualType(New, 0);
1987}
1988
Nate Begeman213541a2008-04-18 23:10:10 +00001989/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001990/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001991QualType
1992ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001993 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Steve Naroff73322922007-07-18 18:00:27 +00001995 // Check if we've already instantiated a vector of this type.
1996 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001997 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001998 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001999 void *InsertPos = 0;
2000 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2001 return QualType(VTP, 0);
2002
2003 // If the element type isn't canonical, this won't be a canonical type either,
2004 // so fill in the canonical type field.
2005 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00002006 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002007 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Steve Naroff73322922007-07-18 18:00:27 +00002009 // Get the new insert position for the node we care about.
2010 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002011 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00002012 }
John McCall6b304a02009-09-24 23:30:46 +00002013 ExtVectorType *New = new (*this, TypeAlignment)
2014 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00002015 VectorTypes.InsertNode(New, InsertPos);
2016 Types.push_back(New);
2017 return QualType(New, 0);
2018}
2019
Jay Foad4ba2a172011-01-12 09:06:06 +00002020QualType
2021ASTContext::getDependentSizedExtVectorType(QualType vecType,
2022 Expr *SizeExpr,
2023 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002024 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00002025 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002026 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002028 void *InsertPos = 0;
2029 DependentSizedExtVectorType *Canon
2030 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2031 DependentSizedExtVectorType *New;
2032 if (Canon) {
2033 // We already have a canonical version of this array type; use it as
2034 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00002035 New = new (*this, TypeAlignment)
2036 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2037 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002038 } else {
2039 QualType CanonVecTy = getCanonicalType(vecType);
2040 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00002041 New = new (*this, TypeAlignment)
2042 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2043 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002044
2045 DependentSizedExtVectorType *CanonCheck
2046 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2047 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2048 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002049 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2050 } else {
2051 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2052 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00002053 New = new (*this, TypeAlignment)
2054 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00002055 }
2056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002058 Types.push_back(New);
2059 return QualType(New, 0);
2060}
2061
Douglas Gregor72564e72009-02-26 23:50:07 +00002062/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00002063///
Jay Foad4ba2a172011-01-12 09:06:06 +00002064QualType
2065ASTContext::getFunctionNoProtoType(QualType ResultTy,
2066 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00002067 const CallingConv DefaultCC = Info.getCC();
2068 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2069 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00002070 // Unique functions, to guarantee there is only one function of a particular
2071 // structure.
2072 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00002073 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002076 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00002077 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002078 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Reid Spencer5f016e22007-07-11 17:01:13 +00002080 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00002081 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00002082 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00002083 Canonical =
2084 getFunctionNoProtoType(getCanonicalType(ResultTy),
2085 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002088 FunctionNoProtoType *NewIP =
2089 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002090 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Roman Divackycfe9af22011-03-01 17:40:53 +00002093 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00002094 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00002095 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002096 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00002097 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 return QualType(New, 0);
2099}
2100
2101/// getFunctionType - Return a normal function type with a typed argument
2102/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00002103QualType
2104ASTContext::getFunctionType(QualType ResultTy,
2105 const QualType *ArgArray, unsigned NumArgs,
2106 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002107 // Unique functions, to guarantee there is only one function of a particular
2108 // structure.
2109 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002110 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00002111
2112 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002113 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00002114 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00002115 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00002116
2117 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002118 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00002119 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002120 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002121 isCanonical = false;
2122
Roman Divackycfe9af22011-03-01 17:40:53 +00002123 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2124 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2125 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002126
Reid Spencer5f016e22007-07-11 17:01:13 +00002127 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002128 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002130 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002131 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002132 CanonicalArgs.reserve(NumArgs);
2133 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002134 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002135
John McCalle23cf432010-12-14 08:05:40 +00002136 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002137 CanonicalEPI.ExceptionSpecType = EST_None;
2138 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002139 CanonicalEPI.ExtInfo
2140 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2141
Chris Lattnerf52ab252008-04-06 22:59:24 +00002142 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002143 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002144 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002145
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002147 FunctionProtoType *NewIP =
2148 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002149 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002150 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002151
John McCallf85e1932011-06-15 23:02:42 +00002152 // FunctionProtoType objects are allocated with extra bytes after
2153 // them for three variable size arrays at the end:
2154 // - parameter types
2155 // - exception types
2156 // - consumed-arguments flags
2157 // Instead of the exception types, there could be a noexcept
2158 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002159 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002160 NumArgs * sizeof(QualType);
2161 if (EPI.ExceptionSpecType == EST_Dynamic)
2162 Size += EPI.NumExceptions * sizeof(QualType);
2163 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002164 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002165 }
John McCallf85e1932011-06-15 23:02:42 +00002166 if (EPI.ConsumedArguments)
2167 Size += NumArgs * sizeof(bool);
2168
John McCalle23cf432010-12-14 08:05:40 +00002169 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002170 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2171 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002172 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002173 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002174 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002175 return QualType(FTP, 0);
2176}
2177
John McCall3cb0ebd2010-03-10 03:28:59 +00002178#ifndef NDEBUG
2179static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2180 if (!isa<CXXRecordDecl>(D)) return false;
2181 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2182 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2183 return true;
2184 if (RD->getDescribedClassTemplate() &&
2185 !isa<ClassTemplateSpecializationDecl>(RD))
2186 return true;
2187 return false;
2188}
2189#endif
2190
2191/// getInjectedClassNameType - Return the unique reference to the
2192/// injected class name type for the specified templated declaration.
2193QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002194 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002195 assert(NeedsInjectedClassNameType(Decl));
2196 if (Decl->TypeForDecl) {
2197 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002198 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002199 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2200 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2201 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2202 } else {
John McCallf4c73712011-01-19 06:33:43 +00002203 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002204 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002205 Decl->TypeForDecl = newType;
2206 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002207 }
2208 return QualType(Decl->TypeForDecl, 0);
2209}
2210
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002211/// getTypeDeclType - Return the unique reference to the type for the
2212/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002213QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002214 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002215 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Richard Smith162e1c12011-04-15 14:24:37 +00002217 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002218 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002219
John McCallbecb8d52010-03-10 06:48:02 +00002220 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2221 "Template type parameter types are always available.");
2222
John McCall19c85762010-02-16 03:57:14 +00002223 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002224 assert(!Record->getPreviousDeclaration() &&
2225 "struct/union has previous declaration");
2226 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002227 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002228 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002229 assert(!Enum->getPreviousDeclaration() &&
2230 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002231 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002232 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002233 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002234 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2235 Decl->TypeForDecl = newType;
2236 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002237 } else
John McCallbecb8d52010-03-10 06:48:02 +00002238 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002239
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002240 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002241}
2242
Reid Spencer5f016e22007-07-11 17:01:13 +00002243/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002244/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002245QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002246ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2247 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002250 if (Canonical.isNull())
2251 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002252 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002253 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002254 Decl->TypeForDecl = newType;
2255 Types.push_back(newType);
2256 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002257}
2258
Jay Foad4ba2a172011-01-12 09:06:06 +00002259QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002260 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2261
2262 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2263 if (PrevDecl->TypeForDecl)
2264 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2265
John McCallf4c73712011-01-19 06:33:43 +00002266 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2267 Decl->TypeForDecl = newType;
2268 Types.push_back(newType);
2269 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002270}
2271
Jay Foad4ba2a172011-01-12 09:06:06 +00002272QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002273 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2274
2275 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2276 if (PrevDecl->TypeForDecl)
2277 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2278
John McCallf4c73712011-01-19 06:33:43 +00002279 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2280 Decl->TypeForDecl = newType;
2281 Types.push_back(newType);
2282 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002283}
2284
John McCall9d156a72011-01-06 01:58:22 +00002285QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2286 QualType modifiedType,
2287 QualType equivalentType) {
2288 llvm::FoldingSetNodeID id;
2289 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2290
2291 void *insertPos = 0;
2292 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2293 if (type) return QualType(type, 0);
2294
2295 QualType canon = getCanonicalType(equivalentType);
2296 type = new (*this, TypeAlignment)
2297 AttributedType(canon, attrKind, modifiedType, equivalentType);
2298
2299 Types.push_back(type);
2300 AttributedTypes.InsertNode(type, insertPos);
2301
2302 return QualType(type, 0);
2303}
2304
2305
John McCall49a832b2009-10-18 09:09:24 +00002306/// \brief Retrieve a substitution-result type.
2307QualType
2308ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002309 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002310 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002311 && "replacement types must always be canonical");
2312
2313 llvm::FoldingSetNodeID ID;
2314 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2315 void *InsertPos = 0;
2316 SubstTemplateTypeParmType *SubstParm
2317 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2318
2319 if (!SubstParm) {
2320 SubstParm = new (*this, TypeAlignment)
2321 SubstTemplateTypeParmType(Parm, Replacement);
2322 Types.push_back(SubstParm);
2323 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2324 }
2325
2326 return QualType(SubstParm, 0);
2327}
2328
Douglas Gregorc3069d62011-01-14 02:55:32 +00002329/// \brief Retrieve a
2330QualType ASTContext::getSubstTemplateTypeParmPackType(
2331 const TemplateTypeParmType *Parm,
2332 const TemplateArgument &ArgPack) {
2333#ifndef NDEBUG
2334 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2335 PEnd = ArgPack.pack_end();
2336 P != PEnd; ++P) {
2337 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2338 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2339 }
2340#endif
2341
2342 llvm::FoldingSetNodeID ID;
2343 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2344 void *InsertPos = 0;
2345 if (SubstTemplateTypeParmPackType *SubstParm
2346 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2347 return QualType(SubstParm, 0);
2348
2349 QualType Canon;
2350 if (!Parm->isCanonicalUnqualified()) {
2351 Canon = getCanonicalType(QualType(Parm, 0));
2352 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2353 ArgPack);
2354 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2355 }
2356
2357 SubstTemplateTypeParmPackType *SubstParm
2358 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2359 ArgPack);
2360 Types.push_back(SubstParm);
2361 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2362 return QualType(SubstParm, 0);
2363}
2364
Douglas Gregorfab9d672009-02-05 23:33:38 +00002365/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002366/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002367/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002368QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002369 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002370 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002371 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002372 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002373 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002374 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002375 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2376
2377 if (TypeParm)
2378 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002380 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002381 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002382 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002383
2384 TemplateTypeParmType *TypeCheck
2385 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2386 assert(!TypeCheck && "Template type parameter canonical type broken");
2387 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002388 } else
John McCall6b304a02009-09-24 23:30:46 +00002389 TypeParm = new (*this, TypeAlignment)
2390 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002391
2392 Types.push_back(TypeParm);
2393 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2394
2395 return QualType(TypeParm, 0);
2396}
2397
John McCall3cb0ebd2010-03-10 03:28:59 +00002398TypeSourceInfo *
2399ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2400 SourceLocation NameLoc,
2401 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002402 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002403 assert(!Name.getAsDependentTemplateName() &&
2404 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002405 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002406
2407 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2408 TemplateSpecializationTypeLoc TL
2409 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2410 TL.setTemplateNameLoc(NameLoc);
2411 TL.setLAngleLoc(Args.getLAngleLoc());
2412 TL.setRAngleLoc(Args.getRAngleLoc());
2413 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2414 TL.setArgLocInfo(i, Args[i].getLocInfo());
2415 return DI;
2416}
2417
Mike Stump1eb44332009-09-09 15:08:12 +00002418QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002419ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002420 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002421 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002422 assert(!Template.getAsDependentTemplateName() &&
2423 "No dependent template names here!");
2424
John McCalld5532b62009-11-23 01:53:49 +00002425 unsigned NumArgs = Args.size();
2426
Chris Lattner5f9e2722011-07-23 10:55:15 +00002427 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002428 ArgVec.reserve(NumArgs);
2429 for (unsigned i = 0; i != NumArgs; ++i)
2430 ArgVec.push_back(Args[i].getArgument());
2431
John McCall31f17ec2010-04-27 00:57:59 +00002432 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002433 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002434}
2435
2436QualType
2437ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002438 const TemplateArgument *Args,
2439 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002440 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002441 assert(!Template.getAsDependentTemplateName() &&
2442 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002443 // Look through qualified template names.
2444 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2445 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002446
Richard Smith3e4c6c42011-05-05 21:57:07 +00002447 bool isTypeAlias =
2448 Template.getAsTemplateDecl() &&
2449 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2450
2451 QualType CanonType;
2452 if (!Underlying.isNull())
2453 CanonType = getCanonicalType(Underlying);
2454 else {
2455 assert(!isTypeAlias &&
2456 "Underlying type for template alias must be computed by caller");
2457 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2458 NumArgs);
2459 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002460
Douglas Gregor1275ae02009-07-28 23:00:59 +00002461 // Allocate the (non-canonical) template specialization type, but don't
2462 // try to unique it: these types typically have location information that
2463 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002464 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2465 sizeof(TemplateArgument) * NumArgs +
2466 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002467 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002468 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002469 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002470 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002471 CanonType,
2472 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Douglas Gregor55f6b142009-02-09 18:46:07 +00002474 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002475 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002476}
2477
Mike Stump1eb44332009-09-09 15:08:12 +00002478QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002479ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2480 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002481 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002482 assert(!Template.getAsDependentTemplateName() &&
2483 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002484 assert((!Template.getAsTemplateDecl() ||
2485 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2486 "Underlying type for template alias must be computed by caller");
2487
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002488 // Look through qualified template names.
2489 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2490 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002491
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002492 // Build the canonical template specialization type.
2493 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002494 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002495 CanonArgs.reserve(NumArgs);
2496 for (unsigned I = 0; I != NumArgs; ++I)
2497 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2498
2499 // Determine whether this canonical template specialization type already
2500 // exists.
2501 llvm::FoldingSetNodeID ID;
2502 TemplateSpecializationType::Profile(ID, CanonTemplate,
2503 CanonArgs.data(), NumArgs, *this);
2504
2505 void *InsertPos = 0;
2506 TemplateSpecializationType *Spec
2507 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2508
2509 if (!Spec) {
2510 // Allocate a new canonical template specialization type.
2511 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2512 sizeof(TemplateArgument) * NumArgs),
2513 TypeAlignment);
2514 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2515 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002516 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002517 Types.push_back(Spec);
2518 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2519 }
2520
2521 assert(Spec->isDependentType() &&
2522 "Non-dependent template-id type must have a canonical type");
2523 return QualType(Spec, 0);
2524}
2525
2526QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002527ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2528 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002529 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002530 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002531 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002532
2533 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002534 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002535 if (T)
2536 return QualType(T, 0);
2537
Douglas Gregor789b1f62010-02-04 18:10:26 +00002538 QualType Canon = NamedType;
2539 if (!Canon.isCanonical()) {
2540 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002541 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2542 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002543 (void)CheckT;
2544 }
2545
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002546 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002547 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002548 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002549 return QualType(T, 0);
2550}
2551
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002552QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002553ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002554 llvm::FoldingSetNodeID ID;
2555 ParenType::Profile(ID, InnerType);
2556
2557 void *InsertPos = 0;
2558 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2559 if (T)
2560 return QualType(T, 0);
2561
2562 QualType Canon = InnerType;
2563 if (!Canon.isCanonical()) {
2564 Canon = getCanonicalType(InnerType);
2565 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2566 assert(!CheckT && "Paren canonical type broken");
2567 (void)CheckT;
2568 }
2569
2570 T = new (*this) ParenType(InnerType, Canon);
2571 Types.push_back(T);
2572 ParenTypes.InsertNode(T, InsertPos);
2573 return QualType(T, 0);
2574}
2575
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002576QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2577 NestedNameSpecifier *NNS,
2578 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002579 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002580 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2581
2582 if (Canon.isNull()) {
2583 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002584 ElaboratedTypeKeyword CanonKeyword = Keyword;
2585 if (Keyword == ETK_None)
2586 CanonKeyword = ETK_Typename;
2587
2588 if (CanonNNS != NNS || CanonKeyword != Keyword)
2589 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002590 }
2591
2592 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002593 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002594
2595 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002596 DependentNameType *T
2597 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002598 if (T)
2599 return QualType(T, 0);
2600
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002601 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002602 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002603 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002604 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002605}
2606
Mike Stump1eb44332009-09-09 15:08:12 +00002607QualType
John McCall33500952010-06-11 00:33:02 +00002608ASTContext::getDependentTemplateSpecializationType(
2609 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002610 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002611 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002612 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002613 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002614 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002615 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2616 ArgCopy.push_back(Args[I].getArgument());
2617 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2618 ArgCopy.size(),
2619 ArgCopy.data());
2620}
2621
2622QualType
2623ASTContext::getDependentTemplateSpecializationType(
2624 ElaboratedTypeKeyword Keyword,
2625 NestedNameSpecifier *NNS,
2626 const IdentifierInfo *Name,
2627 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002628 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002629 assert((!NNS || NNS->isDependent()) &&
2630 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002631
Douglas Gregor789b1f62010-02-04 18:10:26 +00002632 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002633 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2634 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002635
2636 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002637 DependentTemplateSpecializationType *T
2638 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002639 if (T)
2640 return QualType(T, 0);
2641
John McCall33500952010-06-11 00:33:02 +00002642 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002643
John McCall33500952010-06-11 00:33:02 +00002644 ElaboratedTypeKeyword CanonKeyword = Keyword;
2645 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2646
2647 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002648 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002649 for (unsigned I = 0; I != NumArgs; ++I) {
2650 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2651 if (!CanonArgs[I].structurallyEquals(Args[I]))
2652 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002653 }
2654
John McCall33500952010-06-11 00:33:02 +00002655 QualType Canon;
2656 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2657 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2658 Name, NumArgs,
2659 CanonArgs.data());
2660
2661 // Find the insert position again.
2662 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2663 }
2664
2665 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2666 sizeof(TemplateArgument) * NumArgs),
2667 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002668 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002669 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002670 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002671 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002672 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002673}
2674
Douglas Gregorcded4f62011-01-14 17:04:44 +00002675QualType ASTContext::getPackExpansionType(QualType Pattern,
2676 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002677 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002678 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002679
2680 assert(Pattern->containsUnexpandedParameterPack() &&
2681 "Pack expansions must expand one or more parameter packs");
2682 void *InsertPos = 0;
2683 PackExpansionType *T
2684 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2685 if (T)
2686 return QualType(T, 0);
2687
2688 QualType Canon;
2689 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002690 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002691
2692 // Find the insert position again.
2693 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2694 }
2695
Douglas Gregorcded4f62011-01-14 17:04:44 +00002696 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002697 Types.push_back(T);
2698 PackExpansionTypes.InsertNode(T, InsertPos);
2699 return QualType(T, 0);
2700}
2701
Chris Lattner88cb27a2008-04-07 04:56:42 +00002702/// CmpProtocolNames - Comparison predicate for sorting protocols
2703/// alphabetically.
2704static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2705 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002706 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002707}
2708
John McCallc12c5bb2010-05-15 11:32:37 +00002709static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002710 unsigned NumProtocols) {
2711 if (NumProtocols == 0) return true;
2712
2713 for (unsigned i = 1; i != NumProtocols; ++i)
2714 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2715 return false;
2716 return true;
2717}
2718
2719static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002720 unsigned &NumProtocols) {
2721 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Chris Lattner88cb27a2008-04-07 04:56:42 +00002723 // Sort protocols, keyed by name.
2724 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2725
2726 // Remove duplicates.
2727 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2728 NumProtocols = ProtocolsEnd-Protocols;
2729}
2730
John McCallc12c5bb2010-05-15 11:32:37 +00002731QualType ASTContext::getObjCObjectType(QualType BaseType,
2732 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002733 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002734 // If the base type is an interface and there aren't any protocols
2735 // to add, then the interface type will do just fine.
2736 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2737 return BaseType;
2738
2739 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002740 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002741 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002742 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002743 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2744 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002745
John McCallc12c5bb2010-05-15 11:32:37 +00002746 // Build the canonical type, which has the canonical base type and
2747 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002748 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002749 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2750 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2751 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002752 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002753 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002754 unsigned UniqueCount = NumProtocols;
2755
John McCall54e14c42009-10-22 22:37:11 +00002756 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002757 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2758 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002759 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002760 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2761 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002762 }
2763
2764 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002765 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2766 }
2767
2768 unsigned Size = sizeof(ObjCObjectTypeImpl);
2769 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2770 void *Mem = Allocate(Size, TypeAlignment);
2771 ObjCObjectTypeImpl *T =
2772 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2773
2774 Types.push_back(T);
2775 ObjCObjectTypes.InsertNode(T, InsertPos);
2776 return QualType(T, 0);
2777}
2778
2779/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2780/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002781QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002782 llvm::FoldingSetNodeID ID;
2783 ObjCObjectPointerType::Profile(ID, ObjectT);
2784
2785 void *InsertPos = 0;
2786 if (ObjCObjectPointerType *QT =
2787 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2788 return QualType(QT, 0);
2789
2790 // Find the canonical object type.
2791 QualType Canonical;
2792 if (!ObjectT.isCanonical()) {
2793 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2794
2795 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002796 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2797 }
2798
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002799 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002800 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2801 ObjCObjectPointerType *QType =
2802 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002803
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002804 Types.push_back(QType);
2805 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002806 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002807}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002808
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002809/// getObjCInterfaceType - Return the unique reference to the type for the
2810/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregor0af55012011-12-16 03:12:41 +00002811QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2812 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002813 if (Decl->TypeForDecl)
2814 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Douglas Gregor0af55012011-12-16 03:12:41 +00002816 if (PrevDecl) {
2817 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2818 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2819 return QualType(PrevDecl->TypeForDecl, 0);
2820 }
2821
Douglas Gregor8d2dbbf2011-12-16 16:34:57 +00002822 // Prefer the definition, if there is one.
2823 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2824 Decl = Def;
2825
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002826 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2827 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2828 Decl->TypeForDecl = T;
2829 Types.push_back(T);
2830 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002831}
2832
Douglas Gregor72564e72009-02-26 23:50:07 +00002833/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2834/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002835/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002836/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002837/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002838QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002839 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002840 if (tofExpr->isTypeDependent()) {
2841 llvm::FoldingSetNodeID ID;
2842 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002843
Douglas Gregorb1975722009-07-30 23:18:24 +00002844 void *InsertPos = 0;
2845 DependentTypeOfExprType *Canon
2846 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2847 if (Canon) {
2848 // We already have a "canonical" version of an identical, dependent
2849 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002850 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002851 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002852 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002853 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002854 Canon
2855 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002856 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2857 toe = Canon;
2858 }
2859 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002860 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002861 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002862 }
Steve Naroff9752f252007-08-01 18:02:17 +00002863 Types.push_back(toe);
2864 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002865}
2866
Steve Naroff9752f252007-08-01 18:02:17 +00002867/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2868/// TypeOfType AST's. The only motivation to unique these nodes would be
2869/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002870/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002871/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002872QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002873 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002874 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002875 Types.push_back(tot);
2876 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002877}
2878
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002879/// getDecltypeForExpr - Given an expr, will return the decltype for that
2880/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002881static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002882 if (e->isTypeDependent())
2883 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002884
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002885 // If e is an id expression or a class member access, decltype(e) is defined
2886 // as the type of the entity named by e.
2887 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2888 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2889 return VD->getType();
2890 }
2891 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2892 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2893 return FD->getType();
2894 }
2895 // If e is a function call or an invocation of an overloaded operator,
2896 // (parentheses around e are ignored), decltype(e) is defined as the
2897 // return type of that function.
2898 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2899 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002900
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002901 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002902
2903 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002904 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002905 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002906 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002907
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002908 return T;
2909}
2910
Anders Carlsson395b4752009-06-24 19:06:50 +00002911/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2912/// DecltypeType AST's. The only motivation to unique these nodes would be
2913/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002914/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002915/// on canonical types (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002916QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002917 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002918
2919 // C++0x [temp.type]p2:
2920 // If an expression e involves a template parameter, decltype(e) denotes a
2921 // unique dependent type. Two such decltype-specifiers refer to the same
2922 // type only if their expressions are equivalent (14.5.6.1).
2923 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002924 llvm::FoldingSetNodeID ID;
2925 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002926
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002927 void *InsertPos = 0;
2928 DependentDecltypeType *Canon
2929 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2930 if (Canon) {
2931 // We already have a "canonical" version of an equivalent, dependent
2932 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002933 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002934 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002935 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002936 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002937 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002938 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2939 dt = Canon;
2940 }
2941 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002942 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002943 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002944 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002945 Types.push_back(dt);
2946 return QualType(dt, 0);
2947}
2948
Sean Huntca63c202011-05-24 22:41:36 +00002949/// getUnaryTransformationType - We don't unique these, since the memory
2950/// savings are minimal and these are rare.
2951QualType ASTContext::getUnaryTransformType(QualType BaseType,
2952 QualType UnderlyingType,
2953 UnaryTransformType::UTTKind Kind)
2954 const {
2955 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002956 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2957 Kind,
2958 UnderlyingType->isDependentType() ?
2959 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002960 Types.push_back(Ty);
2961 return QualType(Ty, 0);
2962}
2963
Richard Smith483b9f32011-02-21 20:05:19 +00002964/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002965QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002966 void *InsertPos = 0;
2967 if (!DeducedType.isNull()) {
2968 // Look in the folding set for an existing type.
2969 llvm::FoldingSetNodeID ID;
2970 AutoType::Profile(ID, DeducedType);
2971 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2972 return QualType(AT, 0);
2973 }
2974
2975 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2976 Types.push_back(AT);
2977 if (InsertPos)
2978 AutoTypes.InsertNode(AT, InsertPos);
2979 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002980}
2981
Eli Friedmanb001de72011-10-06 23:00:33 +00002982/// getAtomicType - Return the uniqued reference to the atomic type for
2983/// the given value type.
2984QualType ASTContext::getAtomicType(QualType T) const {
2985 // Unique pointers, to guarantee there is only one pointer of a particular
2986 // structure.
2987 llvm::FoldingSetNodeID ID;
2988 AtomicType::Profile(ID, T);
2989
2990 void *InsertPos = 0;
2991 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2992 return QualType(AT, 0);
2993
2994 // If the atomic value type isn't canonical, this won't be a canonical type
2995 // either, so fill in the canonical type field.
2996 QualType Canonical;
2997 if (!T.isCanonical()) {
2998 Canonical = getAtomicType(getCanonicalType(T));
2999
3000 // Get the new insert position for the node we care about.
3001 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3002 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3003 }
3004 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3005 Types.push_back(New);
3006 AtomicTypes.InsertNode(New, InsertPos);
3007 return QualType(New, 0);
3008}
3009
Richard Smithad762fc2011-04-14 22:09:26 +00003010/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3011QualType ASTContext::getAutoDeductType() const {
3012 if (AutoDeductTy.isNull())
3013 AutoDeductTy = getAutoType(QualType());
3014 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3015 return AutoDeductTy;
3016}
3017
3018/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3019QualType ASTContext::getAutoRRefDeductType() const {
3020 if (AutoRRefDeductTy.isNull())
3021 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3022 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3023 return AutoRRefDeductTy;
3024}
3025
Reid Spencer5f016e22007-07-11 17:01:13 +00003026/// getTagDeclType - Return the unique reference to the type for the
3027/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003028QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003029 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003030 // FIXME: What is the design on getTagDeclType when it requires casting
3031 // away const? mutable?
3032 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003033}
3034
Mike Stump1eb44332009-09-09 15:08:12 +00003035/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3036/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3037/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003038CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003039 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003040}
3041
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003042/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3043CanQualType ASTContext::getIntMaxType() const {
3044 return getFromTargetType(Target->getIntMaxType());
3045}
3046
3047/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3048CanQualType ASTContext::getUIntMaxType() const {
3049 return getFromTargetType(Target->getUIntMaxType());
3050}
3051
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003052/// getSignedWCharType - Return the type of "signed wchar_t".
3053/// Used when in C++, as a GCC extension.
3054QualType ASTContext::getSignedWCharType() const {
3055 // FIXME: derive from "Target" ?
3056 return WCharTy;
3057}
3058
3059/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3060/// Used when in C++, as a GCC extension.
3061QualType ASTContext::getUnsignedWCharType() const {
3062 // FIXME: derive from "Target" ?
3063 return UnsignedIntTy;
3064}
3065
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003066/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003067/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3068QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003069 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003070}
3071
Chris Lattnere6327742008-04-02 05:18:44 +00003072//===----------------------------------------------------------------------===//
3073// Type Operators
3074//===----------------------------------------------------------------------===//
3075
Jay Foad4ba2a172011-01-12 09:06:06 +00003076CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003077 // Push qualifiers into arrays, and then discard any remaining
3078 // qualifiers.
3079 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003080 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003081 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003082 QualType Result;
3083 if (isa<ArrayType>(Ty)) {
3084 Result = getArrayDecayedType(QualType(Ty,0));
3085 } else if (isa<FunctionType>(Ty)) {
3086 Result = getPointerType(QualType(Ty, 0));
3087 } else {
3088 Result = QualType(Ty, 0);
3089 }
3090
3091 return CanQualType::CreateUnsafe(Result);
3092}
3093
John McCall62c28c82011-01-18 07:41:22 +00003094QualType ASTContext::getUnqualifiedArrayType(QualType type,
3095 Qualifiers &quals) {
3096 SplitQualType splitType = type.getSplitUnqualifiedType();
3097
3098 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3099 // the unqualified desugared type and then drops it on the floor.
3100 // We then have to strip that sugar back off with
3101 // getUnqualifiedDesugaredType(), which is silly.
3102 const ArrayType *AT =
3103 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3104
3105 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003106 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00003107 quals = splitType.second;
3108 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003109 }
3110
John McCall62c28c82011-01-18 07:41:22 +00003111 // Otherwise, recurse on the array's element type.
3112 QualType elementType = AT->getElementType();
3113 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3114
3115 // If that didn't change the element type, AT has no qualifiers, so we
3116 // can just use the results in splitType.
3117 if (elementType == unqualElementType) {
3118 assert(quals.empty()); // from the recursive call
3119 quals = splitType.second;
3120 return QualType(splitType.first, 0);
3121 }
3122
3123 // Otherwise, add in the qualifiers from the outermost type, then
3124 // build the type back up.
3125 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003126
Douglas Gregor9dadd942010-05-17 18:45:21 +00003127 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003128 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003129 CAT->getSizeModifier(), 0);
3130 }
3131
Douglas Gregor9dadd942010-05-17 18:45:21 +00003132 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003133 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003134 }
3135
Douglas Gregor9dadd942010-05-17 18:45:21 +00003136 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003137 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003138 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003139 VAT->getSizeModifier(),
3140 VAT->getIndexTypeCVRQualifiers(),
3141 VAT->getBracketsRange());
3142 }
3143
3144 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003145 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003146 DSAT->getSizeModifier(), 0,
3147 SourceRange());
3148}
3149
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003150/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3151/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3152/// they point to and return true. If T1 and T2 aren't pointer types
3153/// or pointer-to-member types, or if they are not similar at this
3154/// level, returns false and leaves T1 and T2 unchanged. Top-level
3155/// qualifiers on T1 and T2 are ignored. This function will typically
3156/// be called in a loop that successively "unwraps" pointer and
3157/// pointer-to-member types to compare them at each level.
3158bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3159 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3160 *T2PtrType = T2->getAs<PointerType>();
3161 if (T1PtrType && T2PtrType) {
3162 T1 = T1PtrType->getPointeeType();
3163 T2 = T2PtrType->getPointeeType();
3164 return true;
3165 }
3166
3167 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3168 *T2MPType = T2->getAs<MemberPointerType>();
3169 if (T1MPType && T2MPType &&
3170 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3171 QualType(T2MPType->getClass(), 0))) {
3172 T1 = T1MPType->getPointeeType();
3173 T2 = T2MPType->getPointeeType();
3174 return true;
3175 }
3176
3177 if (getLangOptions().ObjC1) {
3178 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3179 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3180 if (T1OPType && T2OPType) {
3181 T1 = T1OPType->getPointeeType();
3182 T2 = T2OPType->getPointeeType();
3183 return true;
3184 }
3185 }
3186
3187 // FIXME: Block pointers, too?
3188
3189 return false;
3190}
3191
Jay Foad4ba2a172011-01-12 09:06:06 +00003192DeclarationNameInfo
3193ASTContext::getNameForTemplate(TemplateName Name,
3194 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003195 switch (Name.getKind()) {
3196 case TemplateName::QualifiedTemplate:
3197 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003198 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003199 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3200 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003201
John McCall14606042011-06-30 08:33:18 +00003202 case TemplateName::OverloadedTemplate: {
3203 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3204 // DNInfo work in progress: CHECKME: what about DNLoc?
3205 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3206 }
3207
3208 case TemplateName::DependentTemplate: {
3209 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003210 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003211 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003212 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3213 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003214 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003215 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3216 // DNInfo work in progress: FIXME: source locations?
3217 DeclarationNameLoc DNLoc;
3218 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3219 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3220 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003221 }
3222 }
3223
John McCall14606042011-06-30 08:33:18 +00003224 case TemplateName::SubstTemplateTemplateParm: {
3225 SubstTemplateTemplateParmStorage *subst
3226 = Name.getAsSubstTemplateTemplateParm();
3227 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3228 NameLoc);
3229 }
3230
3231 case TemplateName::SubstTemplateTemplateParmPack: {
3232 SubstTemplateTemplateParmPackStorage *subst
3233 = Name.getAsSubstTemplateTemplateParmPack();
3234 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3235 NameLoc);
3236 }
3237 }
3238
3239 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003240}
3241
Jay Foad4ba2a172011-01-12 09:06:06 +00003242TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003243 switch (Name.getKind()) {
3244 case TemplateName::QualifiedTemplate:
3245 case TemplateName::Template: {
3246 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003247 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003248 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003249 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3250
3251 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003252 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003253 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003254
John McCall14606042011-06-30 08:33:18 +00003255 case TemplateName::OverloadedTemplate:
3256 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003257
John McCall14606042011-06-30 08:33:18 +00003258 case TemplateName::DependentTemplate: {
3259 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3260 assert(DTN && "Non-dependent template names must refer to template decls.");
3261 return DTN->CanonicalTemplateName;
3262 }
3263
3264 case TemplateName::SubstTemplateTemplateParm: {
3265 SubstTemplateTemplateParmStorage *subst
3266 = Name.getAsSubstTemplateTemplateParm();
3267 return getCanonicalTemplateName(subst->getReplacement());
3268 }
3269
3270 case TemplateName::SubstTemplateTemplateParmPack: {
3271 SubstTemplateTemplateParmPackStorage *subst
3272 = Name.getAsSubstTemplateTemplateParmPack();
3273 TemplateTemplateParmDecl *canonParameter
3274 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3275 TemplateArgument canonArgPack
3276 = getCanonicalTemplateArgument(subst->getArgumentPack());
3277 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3278 }
3279 }
3280
3281 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003282}
3283
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003284bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3285 X = getCanonicalTemplateName(X);
3286 Y = getCanonicalTemplateName(Y);
3287 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3288}
3289
Mike Stump1eb44332009-09-09 15:08:12 +00003290TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003291ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003292 switch (Arg.getKind()) {
3293 case TemplateArgument::Null:
3294 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Douglas Gregor1275ae02009-07-28 23:00:59 +00003296 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003297 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Douglas Gregor1275ae02009-07-28 23:00:59 +00003299 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003300 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Douglas Gregor788cd062009-11-11 01:00:40 +00003302 case TemplateArgument::Template:
3303 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003304
3305 case TemplateArgument::TemplateExpansion:
3306 return TemplateArgument(getCanonicalTemplateName(
3307 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003308 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003309
Douglas Gregor1275ae02009-07-28 23:00:59 +00003310 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003311 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003312 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003313
Douglas Gregor1275ae02009-07-28 23:00:59 +00003314 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003315 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Douglas Gregor1275ae02009-07-28 23:00:59 +00003317 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003318 if (Arg.pack_size() == 0)
3319 return Arg;
3320
Douglas Gregor910f8002010-11-07 23:05:16 +00003321 TemplateArgument *CanonArgs
3322 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003323 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003324 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003325 AEnd = Arg.pack_end();
3326 A != AEnd; (void)++A, ++Idx)
3327 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003328
Douglas Gregor910f8002010-11-07 23:05:16 +00003329 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003330 }
3331 }
3332
3333 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003334 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003335}
3336
Douglas Gregord57959a2009-03-27 23:10:48 +00003337NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003338ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003339 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003340 return 0;
3341
3342 switch (NNS->getKind()) {
3343 case NestedNameSpecifier::Identifier:
3344 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003345 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003346 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3347 NNS->getAsIdentifier());
3348
3349 case NestedNameSpecifier::Namespace:
3350 // A namespace is canonical; build a nested-name-specifier with
3351 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003352 return NestedNameSpecifier::Create(*this, 0,
3353 NNS->getAsNamespace()->getOriginalNamespace());
3354
3355 case NestedNameSpecifier::NamespaceAlias:
3356 // A namespace is canonical; build a nested-name-specifier with
3357 // this namespace and no prefix.
3358 return NestedNameSpecifier::Create(*this, 0,
3359 NNS->getAsNamespaceAlias()->getNamespace()
3360 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003361
3362 case NestedNameSpecifier::TypeSpec:
3363 case NestedNameSpecifier::TypeSpecWithTemplate: {
3364 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003365
3366 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3367 // break it apart into its prefix and identifier, then reconsititute those
3368 // as the canonical nested-name-specifier. This is required to canonicalize
3369 // a dependent nested-name-specifier involving typedefs of dependent-name
3370 // types, e.g.,
3371 // typedef typename T::type T1;
3372 // typedef typename T1::type T2;
3373 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3374 NestedNameSpecifier *Prefix
3375 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3376 return NestedNameSpecifier::Create(*this, Prefix,
3377 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3378 }
3379
Douglas Gregor643f8432010-11-04 00:14:23 +00003380 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003381 if (const DependentTemplateSpecializationType *DTST
3382 = T->getAs<DependentTemplateSpecializationType>()) {
3383 NestedNameSpecifier *Prefix
3384 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003385
3386 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3387 Prefix, DTST->getIdentifier(),
3388 DTST->getNumArgs(),
3389 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003390 T = getCanonicalType(T);
3391 }
3392
John McCall3b657512011-01-19 10:06:00 +00003393 return NestedNameSpecifier::Create(*this, 0, false,
3394 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003395 }
3396
3397 case NestedNameSpecifier::Global:
3398 // The global specifier is canonical and unique.
3399 return NNS;
3400 }
3401
3402 // Required to silence a GCC warning
3403 return 0;
3404}
3405
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003406
Jay Foad4ba2a172011-01-12 09:06:06 +00003407const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003408 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003409 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003410 // Handle the common positive case fast.
3411 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3412 return AT;
3413 }
Mike Stump1eb44332009-09-09 15:08:12 +00003414
John McCall0953e762009-09-24 19:53:00 +00003415 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003416 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003417 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003418
John McCall0953e762009-09-24 19:53:00 +00003419 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003420 // implements C99 6.7.3p8: "If the specification of an array type includes
3421 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003422
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003423 // If we get here, we either have type qualifiers on the type, or we have
3424 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003425 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003426
John McCall3b657512011-01-19 10:06:00 +00003427 SplitQualType split = T.getSplitDesugaredType();
3428 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003430 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003431 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3432 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003433 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003434
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003435 // Otherwise, we have an array and we have qualifiers on it. Push the
3436 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003437 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003439 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3440 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3441 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003442 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003443 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3444 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3445 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003446 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003447
Mike Stump1eb44332009-09-09 15:08:12 +00003448 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003449 = dyn_cast<DependentSizedArrayType>(ATy))
3450 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003451 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003452 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003453 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003454 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003455 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003456
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003457 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003458 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003459 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003460 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003461 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003462 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003463}
3464
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003465QualType ASTContext::getAdjustedParameterType(QualType T) {
3466 // C99 6.7.5.3p7:
3467 // A declaration of a parameter as "array of type" shall be
3468 // adjusted to "qualified pointer to type", where the type
3469 // qualifiers (if any) are those specified within the [ and ] of
3470 // the array type derivation.
3471 if (T->isArrayType())
3472 return getArrayDecayedType(T);
3473
3474 // C99 6.7.5.3p8:
3475 // A declaration of a parameter as "function returning type"
3476 // shall be adjusted to "pointer to function returning type", as
3477 // in 6.3.2.1.
3478 if (T->isFunctionType())
3479 return getPointerType(T);
3480
3481 return T;
3482}
3483
3484QualType ASTContext::getSignatureParameterType(QualType T) {
3485 T = getVariableArrayDecayedType(T);
3486 T = getAdjustedParameterType(T);
3487 return T.getUnqualifiedType();
3488}
3489
Chris Lattnere6327742008-04-02 05:18:44 +00003490/// getArrayDecayedType - Return the properly qualified result of decaying the
3491/// specified array type to a pointer. This operation is non-trivial when
3492/// handling typedefs etc. The canonical type of "T" must be an array type,
3493/// this returns a pointer to a properly qualified element of the array.
3494///
3495/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003496QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003497 // Get the element type with 'getAsArrayType' so that we don't lose any
3498 // typedefs in the element type of the array. This also handles propagation
3499 // of type qualifiers from the array type into the element type if present
3500 // (C99 6.7.3p8).
3501 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3502 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003504 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003505
3506 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003507 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003508}
3509
John McCall3b657512011-01-19 10:06:00 +00003510QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3511 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003512}
3513
John McCall3b657512011-01-19 10:06:00 +00003514QualType ASTContext::getBaseElementType(QualType type) const {
3515 Qualifiers qs;
3516 while (true) {
3517 SplitQualType split = type.getSplitDesugaredType();
3518 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3519 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003520
John McCall3b657512011-01-19 10:06:00 +00003521 type = array->getElementType();
3522 qs.addConsistentQualifiers(split.second);
3523 }
Mike Stump1eb44332009-09-09 15:08:12 +00003524
John McCall3b657512011-01-19 10:06:00 +00003525 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003526}
3527
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003528/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003529uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003530ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3531 uint64_t ElementCount = 1;
3532 do {
3533 ElementCount *= CA->getSize().getZExtValue();
3534 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3535 } while (CA);
3536 return ElementCount;
3537}
3538
Reid Spencer5f016e22007-07-11 17:01:13 +00003539/// getFloatingRank - Return a relative rank for floating point types.
3540/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003541static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003542 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003543 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003544
John McCall183700f2009-09-21 23:43:11 +00003545 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3546 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003547 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003548 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003549 case BuiltinType::Float: return FloatRank;
3550 case BuiltinType::Double: return DoubleRank;
3551 case BuiltinType::LongDouble: return LongDoubleRank;
3552 }
3553}
3554
Mike Stump1eb44332009-09-09 15:08:12 +00003555/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3556/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003557/// 'typeDomain' is a real floating point or complex type.
3558/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003559QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3560 QualType Domain) const {
3561 FloatingRank EltRank = getFloatingRank(Size);
3562 if (Domain->isComplexType()) {
3563 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003564 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003565 case FloatRank: return FloatComplexTy;
3566 case DoubleRank: return DoubleComplexTy;
3567 case LongDoubleRank: return LongDoubleComplexTy;
3568 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003569 }
Chris Lattner1361b112008-04-06 23:58:54 +00003570
3571 assert(Domain->isRealFloatingType() && "Unknown domain!");
3572 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003573 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattner1361b112008-04-06 23:58:54 +00003574 case FloatRank: return FloatTy;
3575 case DoubleRank: return DoubleTy;
3576 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003577 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003578}
3579
Chris Lattner7cfeb082008-04-06 23:55:33 +00003580/// getFloatingTypeOrder - Compare the rank of the two specified floating
3581/// point types, ignoring the domain of the type (i.e. 'double' ==
3582/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003583/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003584int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003585 FloatingRank LHSR = getFloatingRank(LHS);
3586 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003587
Chris Lattnera75cea32008-04-06 23:38:49 +00003588 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003589 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003590 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003591 return 1;
3592 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003593}
3594
Chris Lattnerf52ab252008-04-06 22:59:24 +00003595/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3596/// routine will assert if passed a built-in type that isn't an integer or enum,
3597/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003598unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003599 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003600
Chris Lattnerf52ab252008-04-06 22:59:24 +00003601 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003602 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003603 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003604 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003605 case BuiltinType::Char_S:
3606 case BuiltinType::Char_U:
3607 case BuiltinType::SChar:
3608 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003609 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003610 case BuiltinType::Short:
3611 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003612 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003613 case BuiltinType::Int:
3614 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003615 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003616 case BuiltinType::Long:
3617 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003618 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003619 case BuiltinType::LongLong:
3620 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003621 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003622 case BuiltinType::Int128:
3623 case BuiltinType::UInt128:
3624 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003625 }
3626}
3627
Eli Friedman04e83572009-08-20 04:21:42 +00003628/// \brief Whether this is a promotable bitfield reference according
3629/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3630///
3631/// \returns the type this bit-field will promote to, or NULL if no
3632/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003633QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003634 if (E->isTypeDependent() || E->isValueDependent())
3635 return QualType();
3636
Eli Friedman04e83572009-08-20 04:21:42 +00003637 FieldDecl *Field = E->getBitField();
3638 if (!Field)
3639 return QualType();
3640
3641 QualType FT = Field->getType();
3642
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003643 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003644 uint64_t IntSize = getTypeSize(IntTy);
3645 // GCC extension compatibility: if the bit-field size is less than or equal
3646 // to the size of int, it gets promoted no matter what its type is.
3647 // For instance, unsigned long bf : 4 gets promoted to signed int.
3648 if (BitWidth < IntSize)
3649 return IntTy;
3650
3651 if (BitWidth == IntSize)
3652 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3653
3654 // Types bigger than int are not subject to promotions, and therefore act
3655 // like the base type.
3656 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3657 // is ridiculous.
3658 return QualType();
3659}
3660
Eli Friedmana95d7572009-08-19 07:44:53 +00003661/// getPromotedIntegerType - Returns the type that Promotable will
3662/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3663/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003664QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003665 assert(!Promotable.isNull());
3666 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003667 if (const EnumType *ET = Promotable->getAs<EnumType>())
3668 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003669
3670 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3671 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3672 // (3.9.1) can be converted to a prvalue of the first of the following
3673 // types that can represent all the values of its underlying type:
3674 // int, unsigned int, long int, unsigned long int, long long int, or
3675 // unsigned long long int [...]
3676 // FIXME: Is there some better way to compute this?
3677 if (BT->getKind() == BuiltinType::WChar_S ||
3678 BT->getKind() == BuiltinType::WChar_U ||
3679 BT->getKind() == BuiltinType::Char16 ||
3680 BT->getKind() == BuiltinType::Char32) {
3681 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3682 uint64_t FromSize = getTypeSize(BT);
3683 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3684 LongLongTy, UnsignedLongLongTy };
3685 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3686 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3687 if (FromSize < ToSize ||
3688 (FromSize == ToSize &&
3689 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3690 return PromoteTypes[Idx];
3691 }
3692 llvm_unreachable("char type should fit into long long");
3693 }
3694 }
3695
3696 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003697 if (Promotable->isSignedIntegerType())
3698 return IntTy;
3699 uint64_t PromotableSize = getTypeSize(Promotable);
3700 uint64_t IntSize = getTypeSize(IntTy);
3701 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3702 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3703}
3704
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003705/// \brief Recurses in pointer/array types until it finds an objc retainable
3706/// type and returns its ownership.
3707Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3708 while (!T.isNull()) {
3709 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3710 return T.getObjCLifetime();
3711 if (T->isArrayType())
3712 T = getBaseElementType(T);
3713 else if (const PointerType *PT = T->getAs<PointerType>())
3714 T = PT->getPointeeType();
3715 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003716 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003717 else
3718 break;
3719 }
3720
3721 return Qualifiers::OCL_None;
3722}
3723
Mike Stump1eb44332009-09-09 15:08:12 +00003724/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003725/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003726/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003727int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003728 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3729 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003730 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003731
Chris Lattnerf52ab252008-04-06 22:59:24 +00003732 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3733 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003734
Chris Lattner7cfeb082008-04-06 23:55:33 +00003735 unsigned LHSRank = getIntegerRank(LHSC);
3736 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Chris Lattner7cfeb082008-04-06 23:55:33 +00003738 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3739 if (LHSRank == RHSRank) return 0;
3740 return LHSRank > RHSRank ? 1 : -1;
3741 }
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Chris Lattner7cfeb082008-04-06 23:55:33 +00003743 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3744 if (LHSUnsigned) {
3745 // If the unsigned [LHS] type is larger, return it.
3746 if (LHSRank >= RHSRank)
3747 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Chris Lattner7cfeb082008-04-06 23:55:33 +00003749 // If the signed type can represent all values of the unsigned type, it
3750 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003751 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003752 return -1;
3753 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003754
Chris Lattner7cfeb082008-04-06 23:55:33 +00003755 // If the unsigned [RHS] type is larger, return it.
3756 if (RHSRank >= LHSRank)
3757 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003758
Chris Lattner7cfeb082008-04-06 23:55:33 +00003759 // If the signed type can represent all values of the unsigned type, it
3760 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003761 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003762 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003763}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003764
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003765static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003766CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3767 DeclContext *DC, IdentifierInfo *Id) {
3768 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003769 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003770 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003771 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003772 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003773}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003774
Mike Stump1eb44332009-09-09 15:08:12 +00003775// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003776QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003777 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003778 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003779 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003780 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003781 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003782
Anders Carlssonf06273f2007-11-19 00:25:30 +00003783 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003784
Anders Carlsson71993dd2007-08-17 05:31:46 +00003785 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003786 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003787 // int flags;
3788 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003789 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003790 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003791 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003792 FieldTypes[3] = LongTy;
3793
Anders Carlsson71993dd2007-08-17 05:31:46 +00003794 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003795 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003796 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003797 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003798 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003799 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003800 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003801 /*Mutable=*/false,
3802 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003803 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003804 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003805 }
3806
Douglas Gregor838db382010-02-11 01:19:42 +00003807 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003808 }
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Anders Carlsson71993dd2007-08-17 05:31:46 +00003810 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003811}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003812
Douglas Gregor319ac892009-04-23 22:29:11 +00003813void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003814 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003815 assert(Rec && "Invalid CFConstantStringType");
3816 CFConstantStringTypeDecl = Rec->getDecl();
3817}
3818
Jay Foad4ba2a172011-01-12 09:06:06 +00003819QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003820 if (BlockDescriptorType)
3821 return getTagDeclType(BlockDescriptorType);
3822
3823 RecordDecl *T;
3824 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003825 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003826 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003827 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003828
3829 QualType FieldTypes[] = {
3830 UnsignedLongTy,
3831 UnsignedLongTy,
3832 };
3833
3834 const char *FieldNames[] = {
3835 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003836 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003837 };
3838
3839 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003840 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003841 SourceLocation(),
3842 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003843 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003844 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003845 /*Mutable=*/false,
3846 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003847 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003848 T->addDecl(Field);
3849 }
3850
Douglas Gregor838db382010-02-11 01:19:42 +00003851 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003852
3853 BlockDescriptorType = T;
3854
3855 return getTagDeclType(BlockDescriptorType);
3856}
3857
Jay Foad4ba2a172011-01-12 09:06:06 +00003858QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003859 if (BlockDescriptorExtendedType)
3860 return getTagDeclType(BlockDescriptorExtendedType);
3861
3862 RecordDecl *T;
3863 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003864 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003865 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003866 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003867
3868 QualType FieldTypes[] = {
3869 UnsignedLongTy,
3870 UnsignedLongTy,
3871 getPointerType(VoidPtrTy),
3872 getPointerType(VoidPtrTy)
3873 };
3874
3875 const char *FieldNames[] = {
3876 "reserved",
3877 "Size",
3878 "CopyFuncPtr",
3879 "DestroyFuncPtr"
3880 };
3881
3882 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003883 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003884 SourceLocation(),
3885 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003886 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003887 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003888 /*Mutable=*/false,
3889 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003890 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003891 T->addDecl(Field);
3892 }
3893
Douglas Gregor838db382010-02-11 01:19:42 +00003894 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003895
3896 BlockDescriptorExtendedType = T;
3897
3898 return getTagDeclType(BlockDescriptorExtendedType);
3899}
3900
Jay Foad4ba2a172011-01-12 09:06:06 +00003901bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003902 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003903 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003904 if (getLangOptions().CPlusPlus) {
3905 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3906 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003907 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003908
3909 }
3910 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003911 return false;
3912}
3913
Jay Foad4ba2a172011-01-12 09:06:06 +00003914QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003915ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003916 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003917 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003918 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003919 // unsigned int __flags;
3920 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003921 // void *__copy_helper; // as needed
3922 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003923 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003924 // } *
3925
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003926 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3927
3928 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003929 llvm::SmallString<36> Name;
3930 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3931 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003932 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003933 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003934 T->startDefinition();
3935 QualType Int32Ty = IntTy;
3936 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3937 QualType FieldTypes[] = {
3938 getPointerType(VoidPtrTy),
3939 getPointerType(getTagDeclType(T)),
3940 Int32Ty,
3941 Int32Ty,
3942 getPointerType(VoidPtrTy),
3943 getPointerType(VoidPtrTy),
3944 Ty
3945 };
3946
Chris Lattner5f9e2722011-07-23 10:55:15 +00003947 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003948 "__isa",
3949 "__forwarding",
3950 "__flags",
3951 "__size",
3952 "__copy_helper",
3953 "__destroy_helper",
3954 DeclName,
3955 };
3956
3957 for (size_t i = 0; i < 7; ++i) {
3958 if (!HasCopyAndDispose && i >=4 && i <= 5)
3959 continue;
3960 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003961 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003962 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003963 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003964 /*BitWidth=*/0, /*Mutable=*/false,
3965 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003966 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003967 T->addDecl(Field);
3968 }
3969
Douglas Gregor838db382010-02-11 01:19:42 +00003970 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003971
3972 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003973}
3974
Douglas Gregore97179c2011-09-08 01:46:34 +00003975TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3976 if (!ObjCInstanceTypeDecl)
3977 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3978 getTranslationUnitDecl(),
3979 SourceLocation(),
3980 SourceLocation(),
3981 &Idents.get("instancetype"),
3982 getTrivialTypeSourceInfo(getObjCIdType()));
3983 return ObjCInstanceTypeDecl;
3984}
3985
Anders Carlssone8c49532007-10-29 06:33:42 +00003986// This returns true if a type has been typedefed to BOOL:
3987// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003988static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003989 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003990 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3991 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003993 return false;
3994}
3995
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003996/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003997/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003998CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003999 if (!type->isIncompleteArrayType() && type->isIncompleteType())
4000 return CharUnits::Zero();
4001
Ken Dyck199c3d62010-01-11 17:06:35 +00004002 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00004003
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004004 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004005 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004006 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004007 // Treat arrays as pointers, since that's how they're passed in.
4008 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00004009 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004010 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004011}
4012
4013static inline
4014std::string charUnitsToString(const CharUnits &CU) {
4015 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004016}
4017
John McCall6b5a61b2011-02-07 10:33:21 +00004018/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004019/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004020std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4021 std::string S;
4022
David Chisnall5e530af2009-11-17 19:33:30 +00004023 const BlockDecl *Decl = Expr->getBlockDecl();
4024 QualType BlockTy =
4025 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4026 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004027 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004028 // Compute size of all parameters.
4029 // Start with computing size of a pointer in number of bytes.
4030 // FIXME: There might(should) be a better way of doing this computation!
4031 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004032 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4033 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004034 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004035 E = Decl->param_end(); PI != E; ++PI) {
4036 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004037 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004038 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004039 ParmOffset += sz;
4040 }
4041 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004042 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004043 // Block pointer and offset.
4044 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004045
4046 // Argument types.
4047 ParmOffset = PtrSize;
4048 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4049 Decl->param_end(); PI != E; ++PI) {
4050 ParmVarDecl *PVDecl = *PI;
4051 QualType PType = PVDecl->getOriginalType();
4052 if (const ArrayType *AT =
4053 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4054 // Use array's original type only if it has known number of
4055 // elements.
4056 if (!isa<ConstantArrayType>(AT))
4057 PType = PVDecl->getType();
4058 } else if (PType->isFunctionType())
4059 PType = PVDecl->getType();
4060 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004061 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004062 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004063 }
John McCall6b5a61b2011-02-07 10:33:21 +00004064
4065 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004066}
4067
Douglas Gregorf968d832011-05-27 01:19:52 +00004068bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004069 std::string& S) {
4070 // Encode result type.
4071 getObjCEncodingForType(Decl->getResultType(), S);
4072 CharUnits ParmOffset;
4073 // Compute size of all parameters.
4074 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4075 E = Decl->param_end(); PI != E; ++PI) {
4076 QualType PType = (*PI)->getType();
4077 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004078 if (sz.isZero())
4079 return true;
4080
David Chisnall5389f482010-12-30 14:05:53 +00004081 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004082 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004083 ParmOffset += sz;
4084 }
4085 S += charUnitsToString(ParmOffset);
4086 ParmOffset = CharUnits::Zero();
4087
4088 // Argument types.
4089 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4090 E = Decl->param_end(); PI != E; ++PI) {
4091 ParmVarDecl *PVDecl = *PI;
4092 QualType PType = PVDecl->getOriginalType();
4093 if (const ArrayType *AT =
4094 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4095 // Use array's original type only if it has known number of
4096 // elements.
4097 if (!isa<ConstantArrayType>(AT))
4098 PType = PVDecl->getType();
4099 } else if (PType->isFunctionType())
4100 PType = PVDecl->getType();
4101 getObjCEncodingForType(PType, S);
4102 S += charUnitsToString(ParmOffset);
4103 ParmOffset += getObjCEncodingTypeSize(PType);
4104 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004105
4106 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004107}
4108
Bob Wilsondc8dab62011-11-30 01:57:58 +00004109/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4110/// method parameter or return type. If Extended, include class names and
4111/// block object types.
4112void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4113 QualType T, std::string& S,
4114 bool Extended) const {
4115 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4116 getObjCEncodingForTypeQualifier(QT, S);
4117 // Encode parameter type.
4118 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4119 true /*OutermostType*/,
4120 false /*EncodingProperty*/,
4121 false /*StructField*/,
4122 Extended /*EncodeBlockParameters*/,
4123 Extended /*EncodeClassNames*/);
4124}
4125
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004126/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004127/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004128bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004129 std::string& S,
4130 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004131 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004132 // Encode return type.
4133 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4134 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004135 // Compute size of all parameters.
4136 // Start with computing size of a pointer in number of bytes.
4137 // FIXME: There might(should) be a better way of doing this computation!
4138 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004139 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004140 // The first two arguments (self and _cmd) are pointers; account for
4141 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004142 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004143 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004144 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004145 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004146 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004147 if (sz.isZero())
4148 return true;
4149
Ken Dyck199c3d62010-01-11 17:06:35 +00004150 assert (sz.isPositive() &&
4151 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004152 ParmOffset += sz;
4153 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004154 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004155 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004156 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004157
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004158 // Argument types.
4159 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004160 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004161 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004162 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004163 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004164 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004165 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4166 // Use array's original type only if it has known number of
4167 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004168 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004169 PType = PVDecl->getType();
4170 } else if (PType->isFunctionType())
4171 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004172 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4173 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004174 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004175 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004176 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004177
4178 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004179}
4180
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004181/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004182/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004183/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4184/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004185/// Property attributes are stored as a comma-delimited C string. The simple
4186/// attributes readonly and bycopy are encoded as single characters. The
4187/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4188/// encoded as single characters, followed by an identifier. Property types
4189/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004190/// these attributes are defined by the following enumeration:
4191/// @code
4192/// enum PropertyAttributes {
4193/// kPropertyReadOnly = 'R', // property is read-only.
4194/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4195/// kPropertyByref = '&', // property is a reference to the value last assigned
4196/// kPropertyDynamic = 'D', // property is dynamic
4197/// kPropertyGetter = 'G', // followed by getter selector name
4198/// kPropertySetter = 'S', // followed by setter selector name
4199/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4200/// kPropertyType = 't' // followed by old-style type encoding.
4201/// kPropertyWeak = 'W' // 'weak' property
4202/// kPropertyStrong = 'P' // property GC'able
4203/// kPropertyNonAtomic = 'N' // property non-atomic
4204/// };
4205/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004206void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004207 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004208 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004209 // Collect information from the property implementation decl(s).
4210 bool Dynamic = false;
4211 ObjCPropertyImplDecl *SynthesizePID = 0;
4212
4213 // FIXME: Duplicated code due to poor abstraction.
4214 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004215 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004216 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4217 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004218 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004219 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004220 ObjCPropertyImplDecl *PID = *i;
4221 if (PID->getPropertyDecl() == PD) {
4222 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4223 Dynamic = true;
4224 } else {
4225 SynthesizePID = PID;
4226 }
4227 }
4228 }
4229 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004230 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004231 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004232 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004233 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004234 ObjCPropertyImplDecl *PID = *i;
4235 if (PID->getPropertyDecl() == PD) {
4236 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4237 Dynamic = true;
4238 } else {
4239 SynthesizePID = PID;
4240 }
4241 }
Mike Stump1eb44332009-09-09 15:08:12 +00004242 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004243 }
4244 }
4245
4246 // FIXME: This is not very efficient.
4247 S = "T";
4248
4249 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004250 // GCC has some special rules regarding encoding of properties which
4251 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004252 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004253 true /* outermost type */,
4254 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004255
4256 if (PD->isReadOnly()) {
4257 S += ",R";
4258 } else {
4259 switch (PD->getSetterKind()) {
4260 case ObjCPropertyDecl::Assign: break;
4261 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004262 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004263 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004264 }
4265 }
4266
4267 // It really isn't clear at all what this means, since properties
4268 // are "dynamic by default".
4269 if (Dynamic)
4270 S += ",D";
4271
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004272 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4273 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004274
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004275 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4276 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004277 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004278 }
4279
4280 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4281 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004282 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004283 }
4284
4285 if (SynthesizePID) {
4286 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4287 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004288 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004289 }
4290
4291 // FIXME: OBJCGC: weak & strong
4292}
4293
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004294/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004295/// Another legacy compatibility encoding: 32-bit longs are encoded as
4296/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004297/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4298///
4299void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004300 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004301 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004302 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004303 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004304 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004305 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004306 PointeeTy = IntTy;
4307 }
4308 }
4309}
4310
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004311void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004312 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004313 // We follow the behavior of gcc, expanding structures which are
4314 // directly pointed to, and expanding embedded structures. Note that
4315 // these rules are sufficient to prevent recursive encoding of the
4316 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004317 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004318 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004319}
4320
David Chisnall64fd7e82010-06-04 01:10:52 +00004321static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4322 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004323 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004324 case BuiltinType::Void: return 'v';
4325 case BuiltinType::Bool: return 'B';
4326 case BuiltinType::Char_U:
4327 case BuiltinType::UChar: return 'C';
4328 case BuiltinType::UShort: return 'S';
4329 case BuiltinType::UInt: return 'I';
4330 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004331 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004332 case BuiltinType::UInt128: return 'T';
4333 case BuiltinType::ULongLong: return 'Q';
4334 case BuiltinType::Char_S:
4335 case BuiltinType::SChar: return 'c';
4336 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004337 case BuiltinType::WChar_S:
4338 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004339 case BuiltinType::Int: return 'i';
4340 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004341 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004342 case BuiltinType::LongLong: return 'q';
4343 case BuiltinType::Int128: return 't';
4344 case BuiltinType::Float: return 'f';
4345 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004346 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004347 }
4348}
4349
Douglas Gregor5471bc82011-09-08 17:18:35 +00004350static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4351 EnumDecl *Enum = ET->getDecl();
4352
4353 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4354 if (!Enum->isFixed())
4355 return 'i';
4356
4357 // The encoding of a fixed enum type matches its fixed underlying type.
4358 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4359}
4360
Jay Foad4ba2a172011-01-12 09:06:06 +00004361static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004362 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004363 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004364 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004365 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4366 // The GNU runtime requires more information; bitfields are encoded as b,
4367 // then the offset (in bits) of the first element, then the type of the
4368 // bitfield, then the size in bits. For example, in this structure:
4369 //
4370 // struct
4371 // {
4372 // int integer;
4373 // int flags:2;
4374 // };
4375 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4376 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4377 // information is not especially sensible, but we're stuck with it for
4378 // compatibility with GCC, although providing it breaks anything that
4379 // actually uses runtime introspection and wants to work on both runtimes...
4380 if (!Ctx->getLangOptions().NeXTRuntime) {
4381 const RecordDecl *RD = FD->getParent();
4382 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004383 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004384 if (const EnumType *ET = T->getAs<EnumType>())
4385 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004386 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004387 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004388 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004389 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004390}
4391
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004392// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004393void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4394 bool ExpandPointedToStructures,
4395 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004396 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004397 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004398 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004399 bool StructField,
4400 bool EncodeBlockParameters,
4401 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004402 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004403 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004404 return EncodeBitField(this, S, T, FD);
4405 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004406 return;
4407 }
Mike Stump1eb44332009-09-09 15:08:12 +00004408
John McCall183700f2009-09-21 23:43:11 +00004409 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004410 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004411 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004412 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004413 return;
4414 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004415
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004416 // encoding for pointer or r3eference types.
4417 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004418 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004419 if (PT->isObjCSelType()) {
4420 S += ':';
4421 return;
4422 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004423 PointeeTy = PT->getPointeeType();
4424 }
4425 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4426 PointeeTy = RT->getPointeeType();
4427 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004428 bool isReadOnly = false;
4429 // For historical/compatibility reasons, the read-only qualifier of the
4430 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4431 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004432 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004433 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004434 if (OutermostType && T.isConstQualified()) {
4435 isReadOnly = true;
4436 S += 'r';
4437 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004438 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004439 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004440 while (P->getAs<PointerType>())
4441 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004442 if (P.isConstQualified()) {
4443 isReadOnly = true;
4444 S += 'r';
4445 }
4446 }
4447 if (isReadOnly) {
4448 // Another legacy compatibility encoding. Some ObjC qualifier and type
4449 // combinations need to be rearranged.
4450 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004451 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004452 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004453 }
Mike Stump1eb44332009-09-09 15:08:12 +00004454
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004455 if (PointeeTy->isCharType()) {
4456 // char pointer types should be encoded as '*' unless it is a
4457 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004458 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004459 S += '*';
4460 return;
4461 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004462 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004463 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4464 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4465 S += '#';
4466 return;
4467 }
4468 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4469 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4470 S += '@';
4471 return;
4472 }
4473 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004474 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004475 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004476 getLegacyIntegralTypeEncoding(PointeeTy);
4477
Mike Stump1eb44332009-09-09 15:08:12 +00004478 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004479 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004480 return;
4481 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004482
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004483 if (const ArrayType *AT =
4484 // Ignore type qualifiers etc.
4485 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004486 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004487 // Incomplete arrays are encoded as a pointer to the array element.
4488 S += '^';
4489
Mike Stump1eb44332009-09-09 15:08:12 +00004490 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004491 false, ExpandStructures, FD);
4492 } else {
4493 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004494
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004495 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4496 if (getTypeSize(CAT->getElementType()) == 0)
4497 S += '0';
4498 else
4499 S += llvm::utostr(CAT->getSize().getZExtValue());
4500 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004501 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004502 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4503 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004504 S += '0';
4505 }
Mike Stump1eb44332009-09-09 15:08:12 +00004506
4507 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004508 false, ExpandStructures, FD);
4509 S += ']';
4510 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004511 return;
4512 }
Mike Stump1eb44332009-09-09 15:08:12 +00004513
John McCall183700f2009-09-21 23:43:11 +00004514 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004515 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004516 return;
4517 }
Mike Stump1eb44332009-09-09 15:08:12 +00004518
Ted Kremenek6217b802009-07-29 21:53:49 +00004519 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004520 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004521 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004522 // Anonymous structures print as '?'
4523 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4524 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004525 if (ClassTemplateSpecializationDecl *Spec
4526 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4527 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4528 std::string TemplateArgsStr
4529 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004530 TemplateArgs.data(),
4531 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004532 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004533
4534 S += TemplateArgsStr;
4535 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004536 } else {
4537 S += '?';
4538 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004539 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004540 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004541 if (!RDecl->isUnion()) {
4542 getObjCEncodingForStructureImpl(RDecl, S, FD);
4543 } else {
4544 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4545 FieldEnd = RDecl->field_end();
4546 Field != FieldEnd; ++Field) {
4547 if (FD) {
4548 S += '"';
4549 S += Field->getNameAsString();
4550 S += '"';
4551 }
Mike Stump1eb44332009-09-09 15:08:12 +00004552
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004553 // Special case bit-fields.
4554 if (Field->isBitField()) {
4555 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4556 (*Field));
4557 } else {
4558 QualType qt = Field->getType();
4559 getLegacyIntegralTypeEncoding(qt);
4560 getObjCEncodingForTypeImpl(qt, S, false, true,
4561 FD, /*OutermostType*/false,
4562 /*EncodingProperty*/false,
4563 /*StructField*/true);
4564 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004565 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004566 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004567 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004568 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004569 return;
4570 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004571
Douglas Gregor5471bc82011-09-08 17:18:35 +00004572 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004573 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004574 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004575 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004576 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004577 return;
4578 }
Mike Stump1eb44332009-09-09 15:08:12 +00004579
Bob Wilsondc8dab62011-11-30 01:57:58 +00004580 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004581 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004582 if (EncodeBlockParameters) {
4583 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4584
4585 S += '<';
4586 // Block return type
4587 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4588 ExpandPointedToStructures, ExpandStructures,
4589 FD,
4590 false /* OutermostType */,
4591 EncodingProperty,
4592 false /* StructField */,
4593 EncodeBlockParameters,
4594 EncodeClassNames);
4595 // Block self
4596 S += "@?";
4597 // Block parameters
4598 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4599 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4600 E = FPT->arg_type_end(); I && (I != E); ++I) {
4601 getObjCEncodingForTypeImpl(*I, S,
4602 ExpandPointedToStructures,
4603 ExpandStructures,
4604 FD,
4605 false /* OutermostType */,
4606 EncodingProperty,
4607 false /* StructField */,
4608 EncodeBlockParameters,
4609 EncodeClassNames);
4610 }
4611 }
4612 S += '>';
4613 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004614 return;
4615 }
Mike Stump1eb44332009-09-09 15:08:12 +00004616
John McCallc12c5bb2010-05-15 11:32:37 +00004617 // Ignore protocol qualifiers when mangling at this level.
4618 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4619 T = OT->getBaseType();
4620
John McCall0953e762009-09-24 19:53:00 +00004621 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004622 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004623 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004624 S += '{';
4625 const IdentifierInfo *II = OI->getIdentifier();
4626 S += II->getName();
4627 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004628 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004629 DeepCollectObjCIvars(OI, true, Ivars);
4630 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004631 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004632 if (Field->isBitField())
4633 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004634 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004635 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004636 }
4637 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004638 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004639 }
Mike Stump1eb44332009-09-09 15:08:12 +00004640
John McCall183700f2009-09-21 23:43:11 +00004641 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004642 if (OPT->isObjCIdType()) {
4643 S += '@';
4644 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004645 }
Mike Stump1eb44332009-09-09 15:08:12 +00004646
Steve Naroff27d20a22009-10-28 22:03:49 +00004647 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4648 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4649 // Since this is a binary compatibility issue, need to consult with runtime
4650 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004651 S += '#';
4652 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004653 }
Mike Stump1eb44332009-09-09 15:08:12 +00004654
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004655 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004656 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004657 ExpandPointedToStructures,
4658 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004659 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004660 // Note that we do extended encoding of protocol qualifer list
4661 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004662 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004663 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4664 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004665 S += '<';
4666 S += (*I)->getNameAsString();
4667 S += '>';
4668 }
4669 S += '"';
4670 }
4671 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004672 }
Mike Stump1eb44332009-09-09 15:08:12 +00004673
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004674 QualType PointeeTy = OPT->getPointeeType();
4675 if (!EncodingProperty &&
4676 isa<TypedefType>(PointeeTy.getTypePtr())) {
4677 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004678 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004679 // {...};
4680 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004681 getObjCEncodingForTypeImpl(PointeeTy, S,
4682 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004683 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004684 return;
4685 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004686
4687 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004688 if (OPT->getInterfaceDecl() &&
4689 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004690 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004691 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004692 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4693 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004694 S += '<';
4695 S += (*I)->getNameAsString();
4696 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004697 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004698 S += '"';
4699 }
4700 return;
4701 }
Mike Stump1eb44332009-09-09 15:08:12 +00004702
John McCall532ec7b2010-05-17 23:56:34 +00004703 // gcc just blithely ignores member pointers.
4704 // TODO: maybe there should be a mangling for these
4705 if (T->getAs<MemberPointerType>())
4706 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004707
4708 if (T->isVectorType()) {
4709 // This matches gcc's encoding, even though technically it is
4710 // insufficient.
4711 // FIXME. We should do a better job than gcc.
4712 return;
4713 }
4714
David Blaikieb219cfc2011-09-23 05:06:16 +00004715 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004716}
4717
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004718void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4719 std::string &S,
4720 const FieldDecl *FD,
4721 bool includeVBases) const {
4722 assert(RDecl && "Expected non-null RecordDecl");
4723 assert(!RDecl->isUnion() && "Should not be called for unions");
4724 if (!RDecl->getDefinition())
4725 return;
4726
4727 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4728 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4729 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4730
4731 if (CXXRec) {
4732 for (CXXRecordDecl::base_class_iterator
4733 BI = CXXRec->bases_begin(),
4734 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4735 if (!BI->isVirtual()) {
4736 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004737 if (base->isEmpty())
4738 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004739 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4740 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4741 std::make_pair(offs, base));
4742 }
4743 }
4744 }
4745
4746 unsigned i = 0;
4747 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4748 FieldEnd = RDecl->field_end();
4749 Field != FieldEnd; ++Field, ++i) {
4750 uint64_t offs = layout.getFieldOffset(i);
4751 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4752 std::make_pair(offs, *Field));
4753 }
4754
4755 if (CXXRec && includeVBases) {
4756 for (CXXRecordDecl::base_class_iterator
4757 BI = CXXRec->vbases_begin(),
4758 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4759 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004760 if (base->isEmpty())
4761 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004762 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004763 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4764 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4765 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004766 }
4767 }
4768
4769 CharUnits size;
4770 if (CXXRec) {
4771 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4772 } else {
4773 size = layout.getSize();
4774 }
4775
4776 uint64_t CurOffs = 0;
4777 std::multimap<uint64_t, NamedDecl *>::iterator
4778 CurLayObj = FieldOrBaseOffsets.begin();
4779
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004780 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4781 (CurLayObj == FieldOrBaseOffsets.end() &&
4782 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004783 assert(CXXRec && CXXRec->isDynamicClass() &&
4784 "Offset 0 was empty but no VTable ?");
4785 if (FD) {
4786 S += "\"_vptr$";
4787 std::string recname = CXXRec->getNameAsString();
4788 if (recname.empty()) recname = "?";
4789 S += recname;
4790 S += '"';
4791 }
4792 S += "^^?";
4793 CurOffs += getTypeSize(VoidPtrTy);
4794 }
4795
4796 if (!RDecl->hasFlexibleArrayMember()) {
4797 // Mark the end of the structure.
4798 uint64_t offs = toBits(size);
4799 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4800 std::make_pair(offs, (NamedDecl*)0));
4801 }
4802
4803 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4804 assert(CurOffs <= CurLayObj->first);
4805
4806 if (CurOffs < CurLayObj->first) {
4807 uint64_t padding = CurLayObj->first - CurOffs;
4808 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4809 // packing/alignment of members is different that normal, in which case
4810 // the encoding will be out-of-sync with the real layout.
4811 // If the runtime switches to just consider the size of types without
4812 // taking into account alignment, we could make padding explicit in the
4813 // encoding (e.g. using arrays of chars). The encoding strings would be
4814 // longer then though.
4815 CurOffs += padding;
4816 }
4817
4818 NamedDecl *dcl = CurLayObj->second;
4819 if (dcl == 0)
4820 break; // reached end of structure.
4821
4822 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4823 // We expand the bases without their virtual bases since those are going
4824 // in the initial structure. Note that this differs from gcc which
4825 // expands virtual bases each time one is encountered in the hierarchy,
4826 // making the encoding type bigger than it really is.
4827 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004828 assert(!base->isEmpty());
4829 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004830 } else {
4831 FieldDecl *field = cast<FieldDecl>(dcl);
4832 if (FD) {
4833 S += '"';
4834 S += field->getNameAsString();
4835 S += '"';
4836 }
4837
4838 if (field->isBitField()) {
4839 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004840 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004841 } else {
4842 QualType qt = field->getType();
4843 getLegacyIntegralTypeEncoding(qt);
4844 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4845 /*OutermostType*/false,
4846 /*EncodingProperty*/false,
4847 /*StructField*/true);
4848 CurOffs += getTypeSize(field->getType());
4849 }
4850 }
4851 }
4852}
4853
Mike Stump1eb44332009-09-09 15:08:12 +00004854void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004855 std::string& S) const {
4856 if (QT & Decl::OBJC_TQ_In)
4857 S += 'n';
4858 if (QT & Decl::OBJC_TQ_Inout)
4859 S += 'N';
4860 if (QT & Decl::OBJC_TQ_Out)
4861 S += 'o';
4862 if (QT & Decl::OBJC_TQ_Bycopy)
4863 S += 'O';
4864 if (QT & Decl::OBJC_TQ_Byref)
4865 S += 'R';
4866 if (QT & Decl::OBJC_TQ_Oneway)
4867 S += 'V';
4868}
4869
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004870void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004871 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004872
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004873 BuiltinVaListType = T;
4874}
4875
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004876TypedefDecl *ASTContext::getObjCIdDecl() const {
4877 if (!ObjCIdDecl) {
4878 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4879 T = getObjCObjectPointerType(T);
4880 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4881 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4882 getTranslationUnitDecl(),
4883 SourceLocation(), SourceLocation(),
4884 &Idents.get("id"), IdInfo);
4885 }
4886
4887 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004888}
4889
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004890TypedefDecl *ASTContext::getObjCSelDecl() const {
4891 if (!ObjCSelDecl) {
4892 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4893 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4894 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4895 getTranslationUnitDecl(),
4896 SourceLocation(), SourceLocation(),
4897 &Idents.get("SEL"), SelInfo);
4898 }
4899 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004900}
4901
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004902void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004903 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004904}
4905
Douglas Gregor79d67262011-08-12 05:59:41 +00004906TypedefDecl *ASTContext::getObjCClassDecl() const {
4907 if (!ObjCClassDecl) {
4908 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4909 T = getObjCObjectPointerType(T);
4910 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4911 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4912 getTranslationUnitDecl(),
4913 SourceLocation(), SourceLocation(),
4914 &Idents.get("Class"), ClassInfo);
4915 }
4916
4917 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004918}
4919
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004920void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004921 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004922 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004923
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004924 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004925}
4926
John McCall0bd6feb2009-12-02 08:04:21 +00004927/// \brief Retrieve the template name that corresponds to a non-empty
4928/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004929TemplateName
4930ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4931 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004932 unsigned size = End - Begin;
4933 assert(size > 1 && "set is not overloaded!");
4934
4935 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4936 size * sizeof(FunctionTemplateDecl*));
4937 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4938
4939 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004940 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004941 NamedDecl *D = *I;
4942 assert(isa<FunctionTemplateDecl>(D) ||
4943 (isa<UsingShadowDecl>(D) &&
4944 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4945 *Storage++ = D;
4946 }
4947
4948 return TemplateName(OT);
4949}
4950
Douglas Gregor7532dc62009-03-30 22:58:21 +00004951/// \brief Retrieve the template name that represents a qualified
4952/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004953TemplateName
4954ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4955 bool TemplateKeyword,
4956 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004957 assert(NNS && "Missing nested-name-specifier in qualified template name");
4958
Douglas Gregor789b1f62010-02-04 18:10:26 +00004959 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004960 llvm::FoldingSetNodeID ID;
4961 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4962
4963 void *InsertPos = 0;
4964 QualifiedTemplateName *QTN =
4965 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4966 if (!QTN) {
4967 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4968 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4969 }
4970
4971 return TemplateName(QTN);
4972}
4973
4974/// \brief Retrieve the template name that represents a dependent
4975/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004976TemplateName
4977ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4978 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004979 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004980 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004981
4982 llvm::FoldingSetNodeID ID;
4983 DependentTemplateName::Profile(ID, NNS, Name);
4984
4985 void *InsertPos = 0;
4986 DependentTemplateName *QTN =
4987 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4988
4989 if (QTN)
4990 return TemplateName(QTN);
4991
4992 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4993 if (CanonNNS == NNS) {
4994 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4995 } else {
4996 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4997 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004998 DependentTemplateName *CheckQTN =
4999 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5000 assert(!CheckQTN && "Dependent type name canonicalization broken");
5001 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00005002 }
5003
5004 DependentTemplateNames.InsertNode(QTN, InsertPos);
5005 return TemplateName(QTN);
5006}
5007
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005008/// \brief Retrieve the template name that represents a dependent
5009/// template name such as \c MetaFun::template operator+.
5010TemplateName
5011ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005012 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005013 assert((!NNS || NNS->isDependent()) &&
5014 "Nested name specifier must be dependent");
5015
5016 llvm::FoldingSetNodeID ID;
5017 DependentTemplateName::Profile(ID, NNS, Operator);
5018
5019 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005020 DependentTemplateName *QTN
5021 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005022
5023 if (QTN)
5024 return TemplateName(QTN);
5025
5026 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5027 if (CanonNNS == NNS) {
5028 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5029 } else {
5030 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5031 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005032
5033 DependentTemplateName *CheckQTN
5034 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5035 assert(!CheckQTN && "Dependent template name canonicalization broken");
5036 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005037 }
5038
5039 DependentTemplateNames.InsertNode(QTN, InsertPos);
5040 return TemplateName(QTN);
5041}
5042
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005043TemplateName
John McCall14606042011-06-30 08:33:18 +00005044ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5045 TemplateName replacement) const {
5046 llvm::FoldingSetNodeID ID;
5047 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5048
5049 void *insertPos = 0;
5050 SubstTemplateTemplateParmStorage *subst
5051 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5052
5053 if (!subst) {
5054 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5055 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5056 }
5057
5058 return TemplateName(subst);
5059}
5060
5061TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005062ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5063 const TemplateArgument &ArgPack) const {
5064 ASTContext &Self = const_cast<ASTContext &>(*this);
5065 llvm::FoldingSetNodeID ID;
5066 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5067
5068 void *InsertPos = 0;
5069 SubstTemplateTemplateParmPackStorage *Subst
5070 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5071
5072 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005073 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005074 ArgPack.pack_size(),
5075 ArgPack.pack_begin());
5076 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5077 }
5078
5079 return TemplateName(Subst);
5080}
5081
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005082/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005083/// TargetInfo, produce the corresponding type. The unsigned @p Type
5084/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005085CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005086 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005087 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005088 case TargetInfo::SignedShort: return ShortTy;
5089 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5090 case TargetInfo::SignedInt: return IntTy;
5091 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5092 case TargetInfo::SignedLong: return LongTy;
5093 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5094 case TargetInfo::SignedLongLong: return LongLongTy;
5095 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5096 }
5097
David Blaikieb219cfc2011-09-23 05:06:16 +00005098 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005099}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005100
5101//===----------------------------------------------------------------------===//
5102// Type Predicates.
5103//===----------------------------------------------------------------------===//
5104
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005105/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5106/// garbage collection attribute.
5107///
John McCallae278a32011-01-12 00:34:59 +00005108Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005109 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005110 return Qualifiers::GCNone;
5111
5112 assert(getLangOptions().ObjC1);
5113 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5114
5115 // Default behaviour under objective-C's gc is for ObjC pointers
5116 // (or pointers to them) be treated as though they were declared
5117 // as __strong.
5118 if (GCAttrs == Qualifiers::GCNone) {
5119 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5120 return Qualifiers::Strong;
5121 else if (Ty->isPointerType())
5122 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5123 } else {
5124 // It's not valid to set GC attributes on anything that isn't a
5125 // pointer.
5126#ifndef NDEBUG
5127 QualType CT = Ty->getCanonicalTypeInternal();
5128 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5129 CT = AT->getElementType();
5130 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5131#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005132 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005133 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005134}
5135
Chris Lattner6ac46a42008-04-07 06:51:04 +00005136//===----------------------------------------------------------------------===//
5137// Type Compatibility Testing
5138//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005139
Mike Stump1eb44332009-09-09 15:08:12 +00005140/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005141/// compatible.
5142static bool areCompatVectorTypes(const VectorType *LHS,
5143 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005144 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005145 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005146 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005147}
5148
Douglas Gregor255210e2010-08-06 10:14:59 +00005149bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5150 QualType SecondVec) {
5151 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5152 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5153
5154 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5155 return true;
5156
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005157 // Treat Neon vector types and most AltiVec vector types as if they are the
5158 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005159 const VectorType *First = FirstVec->getAs<VectorType>();
5160 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005161 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005162 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005163 First->getVectorKind() != VectorType::AltiVecPixel &&
5164 First->getVectorKind() != VectorType::AltiVecBool &&
5165 Second->getVectorKind() != VectorType::AltiVecPixel &&
5166 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005167 return true;
5168
5169 return false;
5170}
5171
Steve Naroff4084c302009-07-23 01:01:38 +00005172//===----------------------------------------------------------------------===//
5173// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5174//===----------------------------------------------------------------------===//
5175
5176/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5177/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005178bool
5179ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5180 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00005181 if (lProto == rProto)
5182 return true;
5183 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5184 E = rProto->protocol_end(); PI != E; ++PI)
5185 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5186 return true;
5187 return false;
5188}
5189
Steve Naroff4084c302009-07-23 01:01:38 +00005190/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5191/// return true if lhs's protocols conform to rhs's protocol; false
5192/// otherwise.
5193bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5194 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5195 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5196 return false;
5197}
5198
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005199/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5200/// Class<p1, ...>.
5201bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5202 QualType rhs) {
5203 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5204 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5205 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5206
5207 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5208 E = lhsQID->qual_end(); I != E; ++I) {
5209 bool match = false;
5210 ObjCProtocolDecl *lhsProto = *I;
5211 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5212 E = rhsOPT->qual_end(); J != E; ++J) {
5213 ObjCProtocolDecl *rhsProto = *J;
5214 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5215 match = true;
5216 break;
5217 }
5218 }
5219 if (!match)
5220 return false;
5221 }
5222 return true;
5223}
5224
Steve Naroff4084c302009-07-23 01:01:38 +00005225/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5226/// ObjCQualifiedIDType.
5227bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5228 bool compare) {
5229 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005230 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005231 lhs->isObjCIdType() || lhs->isObjCClassType())
5232 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005233 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005234 rhs->isObjCIdType() || rhs->isObjCClassType())
5235 return true;
5236
5237 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005238 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005239
Steve Naroff4084c302009-07-23 01:01:38 +00005240 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005241
Steve Naroff4084c302009-07-23 01:01:38 +00005242 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005243 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005244 // make sure we check the class hierarchy.
5245 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5246 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5247 E = lhsQID->qual_end(); I != E; ++I) {
5248 // when comparing an id<P> on lhs with a static type on rhs,
5249 // see if static class implements all of id's protocols, directly or
5250 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005251 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005252 return false;
5253 }
5254 }
5255 // If there are no qualifiers and no interface, we have an 'id'.
5256 return true;
5257 }
Mike Stump1eb44332009-09-09 15:08:12 +00005258 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005259 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5260 E = lhsQID->qual_end(); I != E; ++I) {
5261 ObjCProtocolDecl *lhsProto = *I;
5262 bool match = false;
5263
5264 // when comparing an id<P> on lhs with a static type on rhs,
5265 // see if static class implements all of id's protocols, directly or
5266 // through its super class and categories.
5267 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5268 E = rhsOPT->qual_end(); J != E; ++J) {
5269 ObjCProtocolDecl *rhsProto = *J;
5270 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5271 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5272 match = true;
5273 break;
5274 }
5275 }
Mike Stump1eb44332009-09-09 15:08:12 +00005276 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005277 // make sure we check the class hierarchy.
5278 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5279 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5280 E = lhsQID->qual_end(); I != E; ++I) {
5281 // when comparing an id<P> on lhs with a static type on rhs,
5282 // see if static class implements all of id's protocols, directly or
5283 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005284 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005285 match = true;
5286 break;
5287 }
5288 }
5289 }
5290 if (!match)
5291 return false;
5292 }
Mike Stump1eb44332009-09-09 15:08:12 +00005293
Steve Naroff4084c302009-07-23 01:01:38 +00005294 return true;
5295 }
Mike Stump1eb44332009-09-09 15:08:12 +00005296
Steve Naroff4084c302009-07-23 01:01:38 +00005297 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5298 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5299
Mike Stump1eb44332009-09-09 15:08:12 +00005300 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005301 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005302 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005303 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5304 E = lhsOPT->qual_end(); I != E; ++I) {
5305 ObjCProtocolDecl *lhsProto = *I;
5306 bool match = false;
5307
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005308 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005309 // see if static class implements all of id's protocols, directly or
5310 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005311 // First, lhs protocols in the qualifier list must be found, direct
5312 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005313 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5314 E = rhsQID->qual_end(); J != E; ++J) {
5315 ObjCProtocolDecl *rhsProto = *J;
5316 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5317 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5318 match = true;
5319 break;
5320 }
5321 }
5322 if (!match)
5323 return false;
5324 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005325
5326 // Static class's protocols, or its super class or category protocols
5327 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5328 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5329 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5330 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5331 // This is rather dubious but matches gcc's behavior. If lhs has
5332 // no type qualifier and its class has no static protocol(s)
5333 // assume that it is mismatch.
5334 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5335 return false;
5336 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5337 LHSInheritedProtocols.begin(),
5338 E = LHSInheritedProtocols.end(); I != E; ++I) {
5339 bool match = false;
5340 ObjCProtocolDecl *lhsProto = (*I);
5341 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5342 E = rhsQID->qual_end(); J != E; ++J) {
5343 ObjCProtocolDecl *rhsProto = *J;
5344 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5345 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5346 match = true;
5347 break;
5348 }
5349 }
5350 if (!match)
5351 return false;
5352 }
5353 }
Steve Naroff4084c302009-07-23 01:01:38 +00005354 return true;
5355 }
5356 return false;
5357}
5358
Eli Friedman3d815e72008-08-22 00:56:42 +00005359/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005360/// compatible for assignment from RHS to LHS. This handles validation of any
5361/// protocol qualifiers on the LHS or RHS.
5362///
Steve Naroff14108da2009-07-10 23:34:53 +00005363bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5364 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005365 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5366 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5367
Steve Naroffde2e22d2009-07-15 18:40:39 +00005368 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005369 if (LHS->isObjCUnqualifiedIdOrClass() ||
5370 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005371 return true;
5372
John McCallc12c5bb2010-05-15 11:32:37 +00005373 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005374 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5375 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005376 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005377
5378 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5379 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5380 QualType(RHSOPT,0));
5381
John McCallc12c5bb2010-05-15 11:32:37 +00005382 // If we have 2 user-defined types, fall into that path.
5383 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005384 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005385
Steve Naroff4084c302009-07-23 01:01:38 +00005386 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005387}
5388
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005389/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005390/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005391/// arguments in block literals. When passed as arguments, passing 'A*' where
5392/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5393/// not OK. For the return type, the opposite is not OK.
5394bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5395 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005396 const ObjCObjectPointerType *RHSOPT,
5397 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005398 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005399 return true;
5400
5401 if (LHSOPT->isObjCBuiltinType()) {
5402 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5403 }
5404
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005405 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005406 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5407 QualType(RHSOPT,0),
5408 false);
5409
5410 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5411 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5412 if (LHS && RHS) { // We have 2 user-defined types.
5413 if (LHS != RHS) {
5414 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005415 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005416 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005417 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005418 }
5419 else
5420 return true;
5421 }
5422 return false;
5423}
5424
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005425/// getIntersectionOfProtocols - This routine finds the intersection of set
5426/// of protocols inherited from two distinct objective-c pointer objects.
5427/// It is used to build composite qualifier list of the composite type of
5428/// the conditional expression involving two objective-c pointer objects.
5429static
5430void getIntersectionOfProtocols(ASTContext &Context,
5431 const ObjCObjectPointerType *LHSOPT,
5432 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005433 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005434
John McCallc12c5bb2010-05-15 11:32:37 +00005435 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5436 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5437 assert(LHS->getInterface() && "LHS must have an interface base");
5438 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005439
5440 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5441 unsigned LHSNumProtocols = LHS->getNumProtocols();
5442 if (LHSNumProtocols > 0)
5443 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5444 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005445 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005446 Context.CollectInheritedProtocols(LHS->getInterface(),
5447 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005448 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5449 LHSInheritedProtocols.end());
5450 }
5451
5452 unsigned RHSNumProtocols = RHS->getNumProtocols();
5453 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005454 ObjCProtocolDecl **RHSProtocols =
5455 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005456 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5457 if (InheritedProtocolSet.count(RHSProtocols[i]))
5458 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005459 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005460 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005461 Context.CollectInheritedProtocols(RHS->getInterface(),
5462 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005463 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5464 RHSInheritedProtocols.begin(),
5465 E = RHSInheritedProtocols.end(); I != E; ++I)
5466 if (InheritedProtocolSet.count((*I)))
5467 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005468 }
5469}
5470
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005471/// areCommonBaseCompatible - Returns common base class of the two classes if
5472/// one found. Note that this is O'2 algorithm. But it will be called as the
5473/// last type comparison in a ?-exp of ObjC pointer types before a
5474/// warning is issued. So, its invokation is extremely rare.
5475QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005476 const ObjCObjectPointerType *Lptr,
5477 const ObjCObjectPointerType *Rptr) {
5478 const ObjCObjectType *LHS = Lptr->getObjectType();
5479 const ObjCObjectType *RHS = Rptr->getObjectType();
5480 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5481 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregor60ef3082011-12-15 00:29:59 +00005482 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005483 return QualType();
5484
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005485 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005486 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005487 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005488 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005489 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5490
5491 QualType Result = QualType(LHS, 0);
5492 if (!Protocols.empty())
5493 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5494 Result = getObjCObjectPointerType(Result);
5495 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005496 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005497 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005498
5499 return QualType();
5500}
5501
John McCallc12c5bb2010-05-15 11:32:37 +00005502bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5503 const ObjCObjectType *RHS) {
5504 assert(LHS->getInterface() && "LHS is not an interface type");
5505 assert(RHS->getInterface() && "RHS is not an interface type");
5506
Chris Lattner6ac46a42008-04-07 06:51:04 +00005507 // Verify that the base decls are compatible: the RHS must be a subclass of
5508 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005509 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005510 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005511
Chris Lattner6ac46a42008-04-07 06:51:04 +00005512 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5513 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005514 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005515 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005516
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005517 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5518 // more detailed analysis is required.
5519 if (RHS->getNumProtocols() == 0) {
5520 // OK, if LHS is a superclass of RHS *and*
5521 // this superclass is assignment compatible with LHS.
5522 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005523 bool IsSuperClass =
5524 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5525 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005526 // OK if conversion of LHS to SuperClass results in narrowing of types
5527 // ; i.e., SuperClass may implement at least one of the protocols
5528 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5529 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5530 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005531 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005532 // If super class has no protocols, it is not a match.
5533 if (SuperClassInheritedProtocols.empty())
5534 return false;
5535
5536 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5537 LHSPE = LHS->qual_end();
5538 LHSPI != LHSPE; LHSPI++) {
5539 bool SuperImplementsProtocol = false;
5540 ObjCProtocolDecl *LHSProto = (*LHSPI);
5541
5542 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5543 SuperClassInheritedProtocols.begin(),
5544 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5545 ObjCProtocolDecl *SuperClassProto = (*I);
5546 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5547 SuperImplementsProtocol = true;
5548 break;
5549 }
5550 }
5551 if (!SuperImplementsProtocol)
5552 return false;
5553 }
5554 return true;
5555 }
5556 return false;
5557 }
Mike Stump1eb44332009-09-09 15:08:12 +00005558
John McCallc12c5bb2010-05-15 11:32:37 +00005559 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5560 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005561 LHSPI != LHSPE; LHSPI++) {
5562 bool RHSImplementsProtocol = false;
5563
5564 // If the RHS doesn't implement the protocol on the left, the types
5565 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005566 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5567 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005568 RHSPI != RHSPE; RHSPI++) {
5569 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005570 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005571 break;
5572 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005573 }
5574 // FIXME: For better diagnostics, consider passing back the protocol name.
5575 if (!RHSImplementsProtocol)
5576 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005577 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005578 // The RHS implements all protocols listed on the LHS.
5579 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005580}
5581
Steve Naroff389bf462009-02-12 17:52:19 +00005582bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5583 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005584 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5585 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005586
Steve Naroff14108da2009-07-10 23:34:53 +00005587 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005588 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005589
5590 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5591 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005592}
5593
Douglas Gregor569c3162010-08-07 11:51:51 +00005594bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5595 return canAssignObjCInterfaces(
5596 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5597 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5598}
5599
Mike Stump1eb44332009-09-09 15:08:12 +00005600/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005601/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005602/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005603/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005604bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5605 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005606 if (getLangOptions().CPlusPlus)
5607 return hasSameType(LHS, RHS);
5608
Douglas Gregor447234d2010-07-29 15:18:02 +00005609 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005610}
5611
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005612bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005613 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005614}
5615
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005616bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5617 return !mergeTypes(LHS, RHS, true).isNull();
5618}
5619
Peter Collingbourne48466752010-10-24 18:30:18 +00005620/// mergeTransparentUnionType - if T is a transparent union type and a member
5621/// of T is compatible with SubType, return the merged type, else return
5622/// QualType()
5623QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5624 bool OfBlockPointer,
5625 bool Unqualified) {
5626 if (const RecordType *UT = T->getAsUnionType()) {
5627 RecordDecl *UD = UT->getDecl();
5628 if (UD->hasAttr<TransparentUnionAttr>()) {
5629 for (RecordDecl::field_iterator it = UD->field_begin(),
5630 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005631 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005632 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5633 if (!MT.isNull())
5634 return MT;
5635 }
5636 }
5637 }
5638
5639 return QualType();
5640}
5641
5642/// mergeFunctionArgumentTypes - merge two types which appear as function
5643/// argument types
5644QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5645 bool OfBlockPointer,
5646 bool Unqualified) {
5647 // GNU extension: two types are compatible if they appear as a function
5648 // argument, one of the types is a transparent union type and the other
5649 // type is compatible with a union member
5650 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5651 Unqualified);
5652 if (!lmerge.isNull())
5653 return lmerge;
5654
5655 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5656 Unqualified);
5657 if (!rmerge.isNull())
5658 return rmerge;
5659
5660 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5661}
5662
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005663QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005664 bool OfBlockPointer,
5665 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005666 const FunctionType *lbase = lhs->getAs<FunctionType>();
5667 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005668 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5669 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005670 bool allLTypes = true;
5671 bool allRTypes = true;
5672
5673 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005674 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005675 if (OfBlockPointer) {
5676 QualType RHS = rbase->getResultType();
5677 QualType LHS = lbase->getResultType();
5678 bool UnqualifiedResult = Unqualified;
5679 if (!UnqualifiedResult)
5680 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005681 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005682 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005683 else
John McCall8cc246c2010-12-15 01:06:38 +00005684 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5685 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005686 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005687
5688 if (Unqualified)
5689 retType = retType.getUnqualifiedType();
5690
5691 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5692 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5693 if (Unqualified) {
5694 LRetType = LRetType.getUnqualifiedType();
5695 RRetType = RRetType.getUnqualifiedType();
5696 }
5697
5698 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005699 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005700 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005701 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005702
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005703 // FIXME: double check this
5704 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5705 // rbase->getRegParmAttr() != 0 &&
5706 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005707 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5708 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005709
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005710 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005711 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005712 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005713
John McCall8cc246c2010-12-15 01:06:38 +00005714 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005715 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5716 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005717 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5718 return QualType();
5719
John McCallf85e1932011-06-15 23:02:42 +00005720 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5721 return QualType();
5722
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005723 // functypes which return are preferred over those that do not.
5724 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5725 allLTypes = false;
5726 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5727 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005728 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5729 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005730
John McCallf85e1932011-06-15 23:02:42 +00005731 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005732
Eli Friedman3d815e72008-08-22 00:56:42 +00005733 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005734 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5735 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005736 unsigned lproto_nargs = lproto->getNumArgs();
5737 unsigned rproto_nargs = rproto->getNumArgs();
5738
5739 // Compatible functions must have the same number of arguments
5740 if (lproto_nargs != rproto_nargs)
5741 return QualType();
5742
5743 // Variadic and non-variadic functions aren't compatible
5744 if (lproto->isVariadic() != rproto->isVariadic())
5745 return QualType();
5746
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005747 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5748 return QualType();
5749
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005750 if (LangOpts.ObjCAutoRefCount &&
5751 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5752 return QualType();
5753
Eli Friedman3d815e72008-08-22 00:56:42 +00005754 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005755 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005756 for (unsigned i = 0; i < lproto_nargs; i++) {
5757 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5758 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005759 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5760 OfBlockPointer,
5761 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005762 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005763
5764 if (Unqualified)
5765 argtype = argtype.getUnqualifiedType();
5766
Eli Friedman3d815e72008-08-22 00:56:42 +00005767 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005768 if (Unqualified) {
5769 largtype = largtype.getUnqualifiedType();
5770 rargtype = rargtype.getUnqualifiedType();
5771 }
5772
Chris Lattner61710852008-10-05 17:34:18 +00005773 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5774 allLTypes = false;
5775 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5776 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005777 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005778
Eli Friedman3d815e72008-08-22 00:56:42 +00005779 if (allLTypes) return lhs;
5780 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005781
5782 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5783 EPI.ExtInfo = einfo;
5784 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005785 }
5786
5787 if (lproto) allRTypes = false;
5788 if (rproto) allLTypes = false;
5789
Douglas Gregor72564e72009-02-26 23:50:07 +00005790 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005791 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005792 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005793 if (proto->isVariadic()) return QualType();
5794 // Check that the types are compatible with the types that
5795 // would result from default argument promotions (C99 6.7.5.3p15).
5796 // The only types actually affected are promotable integer
5797 // types and floats, which would be passed as a different
5798 // type depending on whether the prototype is visible.
5799 unsigned proto_nargs = proto->getNumArgs();
5800 for (unsigned i = 0; i < proto_nargs; ++i) {
5801 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005802
5803 // Look at the promotion type of enum types, since that is the type used
5804 // to pass enum values.
5805 if (const EnumType *Enum = argTy->getAs<EnumType>())
5806 argTy = Enum->getDecl()->getPromotionType();
5807
Eli Friedman3d815e72008-08-22 00:56:42 +00005808 if (argTy->isPromotableIntegerType() ||
5809 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5810 return QualType();
5811 }
5812
5813 if (allLTypes) return lhs;
5814 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005815
5816 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5817 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005818 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005819 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005820 }
5821
5822 if (allLTypes) return lhs;
5823 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005824 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005825}
5826
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005827QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005828 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005829 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005830 // C++ [expr]: If an expression initially has the type "reference to T", the
5831 // type is adjusted to "T" prior to any further analysis, the expression
5832 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005833 // expression is an lvalue unless the reference is an rvalue reference and
5834 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005835 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5836 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005837
5838 if (Unqualified) {
5839 LHS = LHS.getUnqualifiedType();
5840 RHS = RHS.getUnqualifiedType();
5841 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005842
Eli Friedman3d815e72008-08-22 00:56:42 +00005843 QualType LHSCan = getCanonicalType(LHS),
5844 RHSCan = getCanonicalType(RHS);
5845
5846 // If two types are identical, they are compatible.
5847 if (LHSCan == RHSCan)
5848 return LHS;
5849
John McCall0953e762009-09-24 19:53:00 +00005850 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005851 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5852 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005853 if (LQuals != RQuals) {
5854 // If any of these qualifiers are different, we have a type
5855 // mismatch.
5856 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005857 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5858 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005859 return QualType();
5860
5861 // Exactly one GC qualifier difference is allowed: __strong is
5862 // okay if the other type has no GC qualifier but is an Objective
5863 // C object pointer (i.e. implicitly strong by default). We fix
5864 // this by pretending that the unqualified type was actually
5865 // qualified __strong.
5866 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5867 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5868 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5869
5870 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5871 return QualType();
5872
5873 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5874 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5875 }
5876 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5877 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5878 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005879 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005880 }
5881
5882 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005883
Eli Friedman852d63b2009-06-01 01:22:52 +00005884 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5885 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005886
Chris Lattner1adb8832008-01-14 05:45:46 +00005887 // We want to consider the two function types to be the same for these
5888 // comparisons, just force one to the other.
5889 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5890 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005891
5892 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005893 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5894 LHSClass = Type::ConstantArray;
5895 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5896 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005897
John McCallc12c5bb2010-05-15 11:32:37 +00005898 // ObjCInterfaces are just specialized ObjCObjects.
5899 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5900 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5901
Nate Begeman213541a2008-04-18 23:10:10 +00005902 // Canonicalize ExtVector -> Vector.
5903 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5904 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005905
Chris Lattnera36a61f2008-04-07 05:43:21 +00005906 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005907 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005908 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005909 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005910 // Compatibility is based on the underlying type, not the promotion
5911 // type.
John McCall183700f2009-09-21 23:43:11 +00005912 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005913 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5914 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005915 }
John McCall183700f2009-09-21 23:43:11 +00005916 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005917 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5918 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005919 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005920
Eli Friedman3d815e72008-08-22 00:56:42 +00005921 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005922 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005923
Steve Naroff4a746782008-01-09 22:43:08 +00005924 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005925 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005926#define TYPE(Class, Base)
5927#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005928#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005929#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5930#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5931#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005932 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005933
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005934 case Type::LValueReference:
5935 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005936 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005937 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005938
John McCallc12c5bb2010-05-15 11:32:37 +00005939 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005940 case Type::IncompleteArray:
5941 case Type::VariableArray:
5942 case Type::FunctionProto:
5943 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005944 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005945
Chris Lattner1adb8832008-01-14 05:45:46 +00005946 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005947 {
5948 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005949 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5950 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005951 if (Unqualified) {
5952 LHSPointee = LHSPointee.getUnqualifiedType();
5953 RHSPointee = RHSPointee.getUnqualifiedType();
5954 }
5955 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5956 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005957 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005958 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005959 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005960 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005961 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005962 return getPointerType(ResultType);
5963 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005964 case Type::BlockPointer:
5965 {
5966 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005967 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5968 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005969 if (Unqualified) {
5970 LHSPointee = LHSPointee.getUnqualifiedType();
5971 RHSPointee = RHSPointee.getUnqualifiedType();
5972 }
5973 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5974 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005975 if (ResultType.isNull()) return QualType();
5976 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5977 return LHS;
5978 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5979 return RHS;
5980 return getBlockPointerType(ResultType);
5981 }
Eli Friedmanb001de72011-10-06 23:00:33 +00005982 case Type::Atomic:
5983 {
5984 // Merge two pointer types, while trying to preserve typedef info
5985 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5986 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5987 if (Unqualified) {
5988 LHSValue = LHSValue.getUnqualifiedType();
5989 RHSValue = RHSValue.getUnqualifiedType();
5990 }
5991 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5992 Unqualified);
5993 if (ResultType.isNull()) return QualType();
5994 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5995 return LHS;
5996 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5997 return RHS;
5998 return getAtomicType(ResultType);
5999 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006000 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00006001 {
6002 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6003 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6004 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6005 return QualType();
6006
6007 QualType LHSElem = getAsArrayType(LHS)->getElementType();
6008 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00006009 if (Unqualified) {
6010 LHSElem = LHSElem.getUnqualifiedType();
6011 RHSElem = RHSElem.getUnqualifiedType();
6012 }
6013
6014 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006015 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006016 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6017 return LHS;
6018 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6019 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006020 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6021 ArrayType::ArraySizeModifier(), 0);
6022 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6023 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006024 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6025 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006026 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6027 return LHS;
6028 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6029 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006030 if (LVAT) {
6031 // FIXME: This isn't correct! But tricky to implement because
6032 // the array's size has to be the size of LHS, but the type
6033 // has to be different.
6034 return LHS;
6035 }
6036 if (RVAT) {
6037 // FIXME: This isn't correct! But tricky to implement because
6038 // the array's size has to be the size of RHS, but the type
6039 // has to be different.
6040 return RHS;
6041 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006042 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6043 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006044 return getIncompleteArrayType(ResultType,
6045 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006046 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006047 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006048 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006049 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006050 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006051 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006052 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006053 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006054 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006055 case Type::Complex:
6056 // Distinct complex types are incompatible.
6057 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006058 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006059 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006060 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6061 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006062 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006063 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006064 case Type::ObjCObject: {
6065 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006066 // FIXME: This should be type compatibility, e.g. whether
6067 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006068 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6069 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6070 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006071 return LHS;
6072
Eli Friedman3d815e72008-08-22 00:56:42 +00006073 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006074 }
Steve Naroff14108da2009-07-10 23:34:53 +00006075 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006076 if (OfBlockPointer) {
6077 if (canAssignObjCInterfacesInBlockPointer(
6078 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006079 RHS->getAs<ObjCObjectPointerType>(),
6080 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006081 return LHS;
6082 return QualType();
6083 }
John McCall183700f2009-09-21 23:43:11 +00006084 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6085 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006086 return LHS;
6087
Steve Naroffbc76dd02008-12-10 22:14:21 +00006088 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006089 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006090 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006091
6092 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006093}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006094
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006095bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6096 const FunctionProtoType *FromFunctionType,
6097 const FunctionProtoType *ToFunctionType) {
6098 if (FromFunctionType->hasAnyConsumedArgs() !=
6099 ToFunctionType->hasAnyConsumedArgs())
6100 return false;
6101 FunctionProtoType::ExtProtoInfo FromEPI =
6102 FromFunctionType->getExtProtoInfo();
6103 FunctionProtoType::ExtProtoInfo ToEPI =
6104 ToFunctionType->getExtProtoInfo();
6105 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6106 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6107 ArgIdx != NumArgs; ++ArgIdx) {
6108 if (FromEPI.ConsumedArguments[ArgIdx] !=
6109 ToEPI.ConsumedArguments[ArgIdx])
6110 return false;
6111 }
6112 return true;
6113}
6114
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006115/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6116/// 'RHS' attributes and returns the merged version; including for function
6117/// return types.
6118QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6119 QualType LHSCan = getCanonicalType(LHS),
6120 RHSCan = getCanonicalType(RHS);
6121 // If two types are identical, they are compatible.
6122 if (LHSCan == RHSCan)
6123 return LHS;
6124 if (RHSCan->isFunctionType()) {
6125 if (!LHSCan->isFunctionType())
6126 return QualType();
6127 QualType OldReturnType =
6128 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6129 QualType NewReturnType =
6130 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6131 QualType ResReturnType =
6132 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6133 if (ResReturnType.isNull())
6134 return QualType();
6135 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6136 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6137 // In either case, use OldReturnType to build the new function type.
6138 const FunctionType *F = LHS->getAs<FunctionType>();
6139 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006140 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6141 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006142 QualType ResultType
6143 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006144 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006145 return ResultType;
6146 }
6147 }
6148 return QualType();
6149 }
6150
6151 // If the qualifiers are different, the types can still be merged.
6152 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6153 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6154 if (LQuals != RQuals) {
6155 // If any of these qualifiers are different, we have a type mismatch.
6156 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6157 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6158 return QualType();
6159
6160 // Exactly one GC qualifier difference is allowed: __strong is
6161 // okay if the other type has no GC qualifier but is an Objective
6162 // C object pointer (i.e. implicitly strong by default). We fix
6163 // this by pretending that the unqualified type was actually
6164 // qualified __strong.
6165 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6166 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6167 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6168
6169 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6170 return QualType();
6171
6172 if (GC_L == Qualifiers::Strong)
6173 return LHS;
6174 if (GC_R == Qualifiers::Strong)
6175 return RHS;
6176 return QualType();
6177 }
6178
6179 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6180 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6181 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6182 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6183 if (ResQT == LHSBaseQT)
6184 return LHS;
6185 if (ResQT == RHSBaseQT)
6186 return RHS;
6187 }
6188 return QualType();
6189}
6190
Chris Lattner5426bf62008-04-07 07:01:58 +00006191//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006192// Integer Predicates
6193//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006194
Jay Foad4ba2a172011-01-12 09:06:06 +00006195unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006196 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006197 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006198 if (T->isBooleanType())
6199 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006200 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006201 return (unsigned)getTypeSize(T);
6202}
6203
6204QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006205 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006206
6207 // Turn <4 x signed int> -> <4 x unsigned int>
6208 if (const VectorType *VTy = T->getAs<VectorType>())
6209 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006210 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006211
6212 // For enums, we return the unsigned version of the base type.
6213 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006214 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006215
6216 const BuiltinType *BTy = T->getAs<BuiltinType>();
6217 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006218 switch (BTy->getKind()) {
6219 case BuiltinType::Char_S:
6220 case BuiltinType::SChar:
6221 return UnsignedCharTy;
6222 case BuiltinType::Short:
6223 return UnsignedShortTy;
6224 case BuiltinType::Int:
6225 return UnsignedIntTy;
6226 case BuiltinType::Long:
6227 return UnsignedLongTy;
6228 case BuiltinType::LongLong:
6229 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006230 case BuiltinType::Int128:
6231 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006232 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006233 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006234 }
6235}
6236
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006237ASTMutationListener::~ASTMutationListener() { }
6238
Chris Lattner86df27b2009-06-14 00:45:47 +00006239
6240//===----------------------------------------------------------------------===//
6241// Builtin Type Computation
6242//===----------------------------------------------------------------------===//
6243
6244/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006245/// pointer over the consumed characters. This returns the resultant type. If
6246/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6247/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6248/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006249///
6250/// RequiresICE is filled in on return to indicate whether the value is required
6251/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006252static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006253 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006254 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006255 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006256 // Modifiers.
6257 int HowLong = 0;
6258 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006259 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006260
Chris Lattner33daae62010-10-01 22:42:38 +00006261 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006262 bool Done = false;
6263 while (!Done) {
6264 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006265 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006266 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006267 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006268 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006269 case 'S':
6270 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6271 assert(!Signed && "Can't use 'S' modifier multiple times!");
6272 Signed = true;
6273 break;
6274 case 'U':
6275 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6276 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6277 Unsigned = true;
6278 break;
6279 case 'L':
6280 assert(HowLong <= 2 && "Can't have LLLL modifier");
6281 ++HowLong;
6282 break;
6283 }
6284 }
6285
6286 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006287
Chris Lattner86df27b2009-06-14 00:45:47 +00006288 // Read the base type.
6289 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006290 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006291 case 'v':
6292 assert(HowLong == 0 && !Signed && !Unsigned &&
6293 "Bad modifiers used with 'v'!");
6294 Type = Context.VoidTy;
6295 break;
6296 case 'f':
6297 assert(HowLong == 0 && !Signed && !Unsigned &&
6298 "Bad modifiers used with 'f'!");
6299 Type = Context.FloatTy;
6300 break;
6301 case 'd':
6302 assert(HowLong < 2 && !Signed && !Unsigned &&
6303 "Bad modifiers used with 'd'!");
6304 if (HowLong)
6305 Type = Context.LongDoubleTy;
6306 else
6307 Type = Context.DoubleTy;
6308 break;
6309 case 's':
6310 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6311 if (Unsigned)
6312 Type = Context.UnsignedShortTy;
6313 else
6314 Type = Context.ShortTy;
6315 break;
6316 case 'i':
6317 if (HowLong == 3)
6318 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6319 else if (HowLong == 2)
6320 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6321 else if (HowLong == 1)
6322 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6323 else
6324 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6325 break;
6326 case 'c':
6327 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6328 if (Signed)
6329 Type = Context.SignedCharTy;
6330 else if (Unsigned)
6331 Type = Context.UnsignedCharTy;
6332 else
6333 Type = Context.CharTy;
6334 break;
6335 case 'b': // boolean
6336 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6337 Type = Context.BoolTy;
6338 break;
6339 case 'z': // size_t.
6340 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6341 Type = Context.getSizeType();
6342 break;
6343 case 'F':
6344 Type = Context.getCFConstantStringType();
6345 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006346 case 'G':
6347 Type = Context.getObjCIdType();
6348 break;
6349 case 'H':
6350 Type = Context.getObjCSelType();
6351 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006352 case 'a':
6353 Type = Context.getBuiltinVaListType();
6354 assert(!Type.isNull() && "builtin va list type not initialized!");
6355 break;
6356 case 'A':
6357 // This is a "reference" to a va_list; however, what exactly
6358 // this means depends on how va_list is defined. There are two
6359 // different kinds of va_list: ones passed by value, and ones
6360 // passed by reference. An example of a by-value va_list is
6361 // x86, where va_list is a char*. An example of by-ref va_list
6362 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6363 // we want this argument to be a char*&; for x86-64, we want
6364 // it to be a __va_list_tag*.
6365 Type = Context.getBuiltinVaListType();
6366 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006367 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006368 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006369 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006370 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006371 break;
6372 case 'V': {
6373 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006374 unsigned NumElements = strtoul(Str, &End, 10);
6375 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006376 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006377
Chris Lattner14e0e742010-10-01 22:53:11 +00006378 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6379 RequiresICE, false);
6380 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006381
6382 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006383 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006384 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006385 break;
6386 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006387 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006388 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6389 false);
6390 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006391 Type = Context.getComplexType(ElementType);
6392 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006393 }
6394 case 'Y' : {
6395 Type = Context.getPointerDiffType();
6396 break;
6397 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006398 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006399 Type = Context.getFILEType();
6400 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006401 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006402 return QualType();
6403 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006404 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006405 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006406 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006407 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006408 else
6409 Type = Context.getjmp_bufType();
6410
Mike Stumpfd612db2009-07-28 23:47:15 +00006411 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006412 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006413 return QualType();
6414 }
6415 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006416 case 'K':
6417 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6418 Type = Context.getucontext_tType();
6419
6420 if (Type.isNull()) {
6421 Error = ASTContext::GE_Missing_ucontext;
6422 return QualType();
6423 }
6424 break;
Mike Stump782fa302009-07-28 02:25:19 +00006425 }
Mike Stump1eb44332009-09-09 15:08:12 +00006426
Chris Lattner33daae62010-10-01 22:42:38 +00006427 // If there are modifiers and if we're allowed to parse them, go for it.
6428 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006429 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006430 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006431 default: Done = true; --Str; break;
6432 case '*':
6433 case '&': {
6434 // Both pointers and references can have their pointee types
6435 // qualified with an address space.
6436 char *End;
6437 unsigned AddrSpace = strtoul(Str, &End, 10);
6438 if (End != Str && AddrSpace != 0) {
6439 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6440 Str = End;
6441 }
6442 if (c == '*')
6443 Type = Context.getPointerType(Type);
6444 else
6445 Type = Context.getLValueReferenceType(Type);
6446 break;
6447 }
6448 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6449 case 'C':
6450 Type = Type.withConst();
6451 break;
6452 case 'D':
6453 Type = Context.getVolatileType(Type);
6454 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006455 }
6456 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006457
Chris Lattner14e0e742010-10-01 22:53:11 +00006458 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006459 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006460
Chris Lattner86df27b2009-06-14 00:45:47 +00006461 return Type;
6462}
6463
6464/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006465QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006466 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006467 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006468 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006469
Chris Lattner5f9e2722011-07-23 10:55:15 +00006470 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006471
Chris Lattner14e0e742010-10-01 22:53:11 +00006472 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006473 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006474 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6475 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006476 if (Error != GE_None)
6477 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006478
6479 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6480
Chris Lattner86df27b2009-06-14 00:45:47 +00006481 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006482 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006483 if (Error != GE_None)
6484 return QualType();
6485
Chris Lattner14e0e742010-10-01 22:53:11 +00006486 // If this argument is required to be an IntegerConstantExpression and the
6487 // caller cares, fill in the bitmask we return.
6488 if (RequiresICE && IntegerConstantArgs)
6489 *IntegerConstantArgs |= 1 << ArgTypes.size();
6490
Chris Lattner86df27b2009-06-14 00:45:47 +00006491 // Do array -> pointer decay. The builtin should use the decayed type.
6492 if (Ty->isArrayType())
6493 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006494
Chris Lattner86df27b2009-06-14 00:45:47 +00006495 ArgTypes.push_back(Ty);
6496 }
6497
6498 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6499 "'.' should only occur at end of builtin type list!");
6500
John McCall00ccbef2010-12-21 00:44:39 +00006501 FunctionType::ExtInfo EI;
6502 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6503
6504 bool Variadic = (TypeStr[0] == '.');
6505
6506 // We really shouldn't be making a no-proto type here, especially in C++.
6507 if (ArgTypes.empty() && Variadic)
6508 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006509
John McCalle23cf432010-12-14 08:05:40 +00006510 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006511 EPI.ExtInfo = EI;
6512 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006513
6514 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006515}
Eli Friedmana95d7572009-08-19 07:44:53 +00006516
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006517GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6518 GVALinkage External = GVA_StrongExternal;
6519
6520 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006521 switch (L) {
6522 case NoLinkage:
6523 case InternalLinkage:
6524 case UniqueExternalLinkage:
6525 return GVA_Internal;
6526
6527 case ExternalLinkage:
6528 switch (FD->getTemplateSpecializationKind()) {
6529 case TSK_Undeclared:
6530 case TSK_ExplicitSpecialization:
6531 External = GVA_StrongExternal;
6532 break;
6533
6534 case TSK_ExplicitInstantiationDefinition:
6535 return GVA_ExplicitTemplateInstantiation;
6536
6537 case TSK_ExplicitInstantiationDeclaration:
6538 case TSK_ImplicitInstantiation:
6539 External = GVA_TemplateInstantiation;
6540 break;
6541 }
6542 }
6543
6544 if (!FD->isInlined())
6545 return External;
6546
6547 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6548 // GNU or C99 inline semantics. Determine whether this symbol should be
6549 // externally visible.
6550 if (FD->isInlineDefinitionExternallyVisible())
6551 return External;
6552
6553 // C99 inline semantics, where the symbol is not externally visible.
6554 return GVA_C99Inline;
6555 }
6556
6557 // C++0x [temp.explicit]p9:
6558 // [ Note: The intent is that an inline function that is the subject of
6559 // an explicit instantiation declaration will still be implicitly
6560 // instantiated when used so that the body can be considered for
6561 // inlining, but that no out-of-line copy of the inline function would be
6562 // generated in the translation unit. -- end note ]
6563 if (FD->getTemplateSpecializationKind()
6564 == TSK_ExplicitInstantiationDeclaration)
6565 return GVA_C99Inline;
6566
6567 return GVA_CXXInline;
6568}
6569
6570GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6571 // If this is a static data member, compute the kind of template
6572 // specialization. Otherwise, this variable is not part of a
6573 // template.
6574 TemplateSpecializationKind TSK = TSK_Undeclared;
6575 if (VD->isStaticDataMember())
6576 TSK = VD->getTemplateSpecializationKind();
6577
6578 Linkage L = VD->getLinkage();
6579 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6580 VD->getType()->getLinkage() == UniqueExternalLinkage)
6581 L = UniqueExternalLinkage;
6582
6583 switch (L) {
6584 case NoLinkage:
6585 case InternalLinkage:
6586 case UniqueExternalLinkage:
6587 return GVA_Internal;
6588
6589 case ExternalLinkage:
6590 switch (TSK) {
6591 case TSK_Undeclared:
6592 case TSK_ExplicitSpecialization:
6593 return GVA_StrongExternal;
6594
6595 case TSK_ExplicitInstantiationDeclaration:
6596 llvm_unreachable("Variable should not be instantiated");
6597 // Fall through to treat this like any other instantiation.
6598
6599 case TSK_ExplicitInstantiationDefinition:
6600 return GVA_ExplicitTemplateInstantiation;
6601
6602 case TSK_ImplicitInstantiation:
6603 return GVA_TemplateInstantiation;
6604 }
6605 }
6606
6607 return GVA_StrongExternal;
6608}
6609
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006610bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006611 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6612 if (!VD->isFileVarDecl())
6613 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006614 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006615 return false;
6616
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006617 // Weak references don't produce any output by themselves.
6618 if (D->hasAttr<WeakRefAttr>())
6619 return false;
6620
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006621 // Aliases and used decls are required.
6622 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6623 return true;
6624
6625 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6626 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006627 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006628 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006629
6630 // Constructors and destructors are required.
6631 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6632 return true;
6633
6634 // The key function for a class is required.
6635 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6636 const CXXRecordDecl *RD = MD->getParent();
6637 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6638 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6639 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6640 return true;
6641 }
6642 }
6643
6644 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6645
6646 // static, static inline, always_inline, and extern inline functions can
6647 // always be deferred. Normal inline functions can be deferred in C99/C++.
6648 // Implicit template instantiations can also be deferred in C++.
6649 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6650 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6651 return false;
6652 return true;
6653 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006654
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006655 const VarDecl *VD = cast<VarDecl>(D);
6656 assert(VD->isFileVarDecl() && "Expected file scoped var");
6657
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006658 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6659 return false;
6660
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006661 // Structs that have non-trivial constructors or destructors are required.
6662
6663 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006664 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006665 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6666 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006667 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6668 RD->hasTrivialCopyConstructor() &&
6669 RD->hasTrivialMoveConstructor() &&
6670 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006671 return true;
6672 }
6673 }
6674
6675 GVALinkage L = GetGVALinkageForVariable(VD);
6676 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6677 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6678 return false;
6679 }
6680
6681 return true;
6682}
Charles Davis071cc7d2010-08-16 03:33:14 +00006683
Charles Davisee743f92010-11-09 18:04:24 +00006684CallingConv ASTContext::getDefaultMethodCallConv() {
6685 // Pass through to the C++ ABI object
6686 return ABI->getDefaultMethodCallConv();
6687}
6688
Jay Foad4ba2a172011-01-12 09:06:06 +00006689bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006690 // Pass through to the C++ ABI object
6691 return ABI->isNearlyEmpty(RD);
6692}
6693
Peter Collingbourne14110472011-01-13 18:57:25 +00006694MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006695 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006696 case CXXABI_ARM:
6697 case CXXABI_Itanium:
6698 return createItaniumMangleContext(*this, getDiagnostics());
6699 case CXXABI_Microsoft:
6700 return createMicrosoftMangleContext(*this, getDiagnostics());
6701 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006702 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006703}
6704
Charles Davis071cc7d2010-08-16 03:33:14 +00006705CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006706
6707size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006708 return ASTRecordLayouts.getMemorySize()
6709 + llvm::capacity_in_bytes(ObjCLayouts)
6710 + llvm::capacity_in_bytes(KeyFunctions)
6711 + llvm::capacity_in_bytes(ObjCImpls)
6712 + llvm::capacity_in_bytes(BlockVarCopyInits)
6713 + llvm::capacity_in_bytes(DeclAttrs)
6714 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6715 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6716 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6717 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6718 + llvm::capacity_in_bytes(OverriddenMethods)
6719 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006720 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006721 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006722}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006723
6724void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6725 ParamIndices[D] = index;
6726}
6727
6728unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6729 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6730 assert(I != ParamIndices.end() &&
6731 "ParmIndices lacks entry set by ParmVarDecl");
6732 return I->second;
6733}