blob: 32ef0b9c602e264771a8765f94985a3dc6247116 [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.
Jay Foad4ba2a172011-01-12 09:06:06 +00002811QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002812 if (Decl->TypeForDecl)
2813 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002815 // FIXME: redeclarations?
2816 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2817 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2818 Decl->TypeForDecl = T;
2819 Types.push_back(T);
2820 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002821}
2822
Douglas Gregor72564e72009-02-26 23:50:07 +00002823/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2824/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002825/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002826/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002827/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002828QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002829 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002830 if (tofExpr->isTypeDependent()) {
2831 llvm::FoldingSetNodeID ID;
2832 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002833
Douglas Gregorb1975722009-07-30 23:18:24 +00002834 void *InsertPos = 0;
2835 DependentTypeOfExprType *Canon
2836 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2837 if (Canon) {
2838 // We already have a "canonical" version of an identical, dependent
2839 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002840 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002841 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002842 } else {
Douglas Gregorb1975722009-07-30 23:18:24 +00002843 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002844 Canon
2845 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002846 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2847 toe = Canon;
2848 }
2849 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002850 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002851 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002852 }
Steve Naroff9752f252007-08-01 18:02:17 +00002853 Types.push_back(toe);
2854 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002855}
2856
Steve Naroff9752f252007-08-01 18:02:17 +00002857/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2858/// TypeOfType AST's. The only motivation to unique these nodes would be
2859/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002860/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002861/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002862QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002863 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002864 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002865 Types.push_back(tot);
2866 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002867}
2868
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002869/// getDecltypeForExpr - Given an expr, will return the decltype for that
2870/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002871static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002872 if (e->isTypeDependent())
2873 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002875 // If e is an id expression or a class member access, decltype(e) is defined
2876 // as the type of the entity named by e.
2877 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2878 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2879 return VD->getType();
2880 }
2881 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2882 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2883 return FD->getType();
2884 }
2885 // If e is a function call or an invocation of an overloaded operator,
2886 // (parentheses around e are ignored), decltype(e) is defined as the
2887 // return type of that function.
2888 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2889 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002890
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002891 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002892
2893 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002894 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002895 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002896 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002898 return T;
2899}
2900
Anders Carlsson395b4752009-06-24 19:06:50 +00002901/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2902/// DecltypeType AST's. The only motivation to unique these nodes would be
2903/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002904/// an issue. This doesn't effect the type checker, since it operates
David Blaikie39e02032011-11-06 22:28:03 +00002905/// on canonical types (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002906QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002907 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002908
2909 // C++0x [temp.type]p2:
2910 // If an expression e involves a template parameter, decltype(e) denotes a
2911 // unique dependent type. Two such decltype-specifiers refer to the same
2912 // type only if their expressions are equivalent (14.5.6.1).
2913 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002914 llvm::FoldingSetNodeID ID;
2915 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002916
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002917 void *InsertPos = 0;
2918 DependentDecltypeType *Canon
2919 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2920 if (Canon) {
2921 // We already have a "canonical" version of an equivalent, dependent
2922 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002923 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002924 QualType((DecltypeType*)Canon, 0));
Chad Rosier30601782011-08-17 23:08:45 +00002925 } else {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002926 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002927 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002928 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2929 dt = Canon;
2930 }
2931 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002932 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002933 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002934 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002935 Types.push_back(dt);
2936 return QualType(dt, 0);
2937}
2938
Sean Huntca63c202011-05-24 22:41:36 +00002939/// getUnaryTransformationType - We don't unique these, since the memory
2940/// savings are minimal and these are rare.
2941QualType ASTContext::getUnaryTransformType(QualType BaseType,
2942 QualType UnderlyingType,
2943 UnaryTransformType::UTTKind Kind)
2944 const {
2945 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002946 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2947 Kind,
2948 UnderlyingType->isDependentType() ?
2949 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002950 Types.push_back(Ty);
2951 return QualType(Ty, 0);
2952}
2953
Richard Smith483b9f32011-02-21 20:05:19 +00002954/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002955QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002956 void *InsertPos = 0;
2957 if (!DeducedType.isNull()) {
2958 // Look in the folding set for an existing type.
2959 llvm::FoldingSetNodeID ID;
2960 AutoType::Profile(ID, DeducedType);
2961 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2962 return QualType(AT, 0);
2963 }
2964
2965 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2966 Types.push_back(AT);
2967 if (InsertPos)
2968 AutoTypes.InsertNode(AT, InsertPos);
2969 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002970}
2971
Eli Friedmanb001de72011-10-06 23:00:33 +00002972/// getAtomicType - Return the uniqued reference to the atomic type for
2973/// the given value type.
2974QualType ASTContext::getAtomicType(QualType T) const {
2975 // Unique pointers, to guarantee there is only one pointer of a particular
2976 // structure.
2977 llvm::FoldingSetNodeID ID;
2978 AtomicType::Profile(ID, T);
2979
2980 void *InsertPos = 0;
2981 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2982 return QualType(AT, 0);
2983
2984 // If the atomic value type isn't canonical, this won't be a canonical type
2985 // either, so fill in the canonical type field.
2986 QualType Canonical;
2987 if (!T.isCanonical()) {
2988 Canonical = getAtomicType(getCanonicalType(T));
2989
2990 // Get the new insert position for the node we care about.
2991 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
2992 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2993 }
2994 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
2995 Types.push_back(New);
2996 AtomicTypes.InsertNode(New, InsertPos);
2997 return QualType(New, 0);
2998}
2999
Richard Smithad762fc2011-04-14 22:09:26 +00003000/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3001QualType ASTContext::getAutoDeductType() const {
3002 if (AutoDeductTy.isNull())
3003 AutoDeductTy = getAutoType(QualType());
3004 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3005 return AutoDeductTy;
3006}
3007
3008/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3009QualType ASTContext::getAutoRRefDeductType() const {
3010 if (AutoRRefDeductTy.isNull())
3011 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3012 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3013 return AutoRRefDeductTy;
3014}
3015
Reid Spencer5f016e22007-07-11 17:01:13 +00003016/// getTagDeclType - Return the unique reference to the type for the
3017/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00003018QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00003019 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00003020 // FIXME: What is the design on getTagDeclType when it requires casting
3021 // away const? mutable?
3022 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003023}
3024
Mike Stump1eb44332009-09-09 15:08:12 +00003025/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3026/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3027/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00003028CanQualType ASTContext::getSizeType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003029 return getFromTargetType(Target->getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00003030}
3031
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003032/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3033CanQualType ASTContext::getIntMaxType() const {
3034 return getFromTargetType(Target->getIntMaxType());
3035}
3036
3037/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3038CanQualType ASTContext::getUIntMaxType() const {
3039 return getFromTargetType(Target->getUIntMaxType());
3040}
3041
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00003042/// getSignedWCharType - Return the type of "signed wchar_t".
3043/// Used when in C++, as a GCC extension.
3044QualType ASTContext::getSignedWCharType() const {
3045 // FIXME: derive from "Target" ?
3046 return WCharTy;
3047}
3048
3049/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3050/// Used when in C++, as a GCC extension.
3051QualType ASTContext::getUnsignedWCharType() const {
3052 // FIXME: derive from "Target" ?
3053 return UnsignedIntTy;
3054}
3055
Hans Wennborg29e97cb2011-10-27 08:29:09 +00003056/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattner8b9023b2007-07-13 03:05:23 +00003057/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3058QualType ASTContext::getPointerDiffType() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003059 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00003060}
3061
Chris Lattnere6327742008-04-02 05:18:44 +00003062//===----------------------------------------------------------------------===//
3063// Type Operators
3064//===----------------------------------------------------------------------===//
3065
Jay Foad4ba2a172011-01-12 09:06:06 +00003066CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00003067 // Push qualifiers into arrays, and then discard any remaining
3068 // qualifiers.
3069 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00003070 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00003071 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00003072 QualType Result;
3073 if (isa<ArrayType>(Ty)) {
3074 Result = getArrayDecayedType(QualType(Ty,0));
3075 } else if (isa<FunctionType>(Ty)) {
3076 Result = getPointerType(QualType(Ty, 0));
3077 } else {
3078 Result = QualType(Ty, 0);
3079 }
3080
3081 return CanQualType::CreateUnsafe(Result);
3082}
3083
John McCall62c28c82011-01-18 07:41:22 +00003084QualType ASTContext::getUnqualifiedArrayType(QualType type,
3085 Qualifiers &quals) {
3086 SplitQualType splitType = type.getSplitUnqualifiedType();
3087
3088 // FIXME: getSplitUnqualifiedType() actually walks all the way to
3089 // the unqualified desugared type and then drops it on the floor.
3090 // We then have to strip that sugar back off with
3091 // getUnqualifiedDesugaredType(), which is silly.
3092 const ArrayType *AT =
3093 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
3094
3095 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00003096 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00003097 quals = splitType.second;
3098 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003099 }
3100
John McCall62c28c82011-01-18 07:41:22 +00003101 // Otherwise, recurse on the array's element type.
3102 QualType elementType = AT->getElementType();
3103 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3104
3105 // If that didn't change the element type, AT has no qualifiers, so we
3106 // can just use the results in splitType.
3107 if (elementType == unqualElementType) {
3108 assert(quals.empty()); // from the recursive call
3109 quals = splitType.second;
3110 return QualType(splitType.first, 0);
3111 }
3112
3113 // Otherwise, add in the qualifiers from the outermost type, then
3114 // build the type back up.
3115 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003116
Douglas Gregor9dadd942010-05-17 18:45:21 +00003117 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003118 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003119 CAT->getSizeModifier(), 0);
3120 }
3121
Douglas Gregor9dadd942010-05-17 18:45:21 +00003122 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003123 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003124 }
3125
Douglas Gregor9dadd942010-05-17 18:45:21 +00003126 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00003127 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00003128 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00003129 VAT->getSizeModifier(),
3130 VAT->getIndexTypeCVRQualifiers(),
3131 VAT->getBracketsRange());
3132 }
3133
3134 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00003135 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00003136 DSAT->getSizeModifier(), 0,
3137 SourceRange());
3138}
3139
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003140/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
3141/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3142/// they point to and return true. If T1 and T2 aren't pointer types
3143/// or pointer-to-member types, or if they are not similar at this
3144/// level, returns false and leaves T1 and T2 unchanged. Top-level
3145/// qualifiers on T1 and T2 are ignored. This function will typically
3146/// be called in a loop that successively "unwraps" pointer and
3147/// pointer-to-member types to compare them at each level.
3148bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3149 const PointerType *T1PtrType = T1->getAs<PointerType>(),
3150 *T2PtrType = T2->getAs<PointerType>();
3151 if (T1PtrType && T2PtrType) {
3152 T1 = T1PtrType->getPointeeType();
3153 T2 = T2PtrType->getPointeeType();
3154 return true;
3155 }
3156
3157 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3158 *T2MPType = T2->getAs<MemberPointerType>();
3159 if (T1MPType && T2MPType &&
3160 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3161 QualType(T2MPType->getClass(), 0))) {
3162 T1 = T1MPType->getPointeeType();
3163 T2 = T2MPType->getPointeeType();
3164 return true;
3165 }
3166
3167 if (getLangOptions().ObjC1) {
3168 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3169 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3170 if (T1OPType && T2OPType) {
3171 T1 = T1OPType->getPointeeType();
3172 T2 = T2OPType->getPointeeType();
3173 return true;
3174 }
3175 }
3176
3177 // FIXME: Block pointers, too?
3178
3179 return false;
3180}
3181
Jay Foad4ba2a172011-01-12 09:06:06 +00003182DeclarationNameInfo
3183ASTContext::getNameForTemplate(TemplateName Name,
3184 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003185 switch (Name.getKind()) {
3186 case TemplateName::QualifiedTemplate:
3187 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003188 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003189 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3190 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003191
John McCall14606042011-06-30 08:33:18 +00003192 case TemplateName::OverloadedTemplate: {
3193 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3194 // DNInfo work in progress: CHECKME: what about DNLoc?
3195 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3196 }
3197
3198 case TemplateName::DependentTemplate: {
3199 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003200 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003201 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003202 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3203 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003204 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003205 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3206 // DNInfo work in progress: FIXME: source locations?
3207 DeclarationNameLoc DNLoc;
3208 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3209 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3210 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003211 }
3212 }
3213
John McCall14606042011-06-30 08:33:18 +00003214 case TemplateName::SubstTemplateTemplateParm: {
3215 SubstTemplateTemplateParmStorage *subst
3216 = Name.getAsSubstTemplateTemplateParm();
3217 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3218 NameLoc);
3219 }
3220
3221 case TemplateName::SubstTemplateTemplateParmPack: {
3222 SubstTemplateTemplateParmPackStorage *subst
3223 = Name.getAsSubstTemplateTemplateParmPack();
3224 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3225 NameLoc);
3226 }
3227 }
3228
3229 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003230}
3231
Jay Foad4ba2a172011-01-12 09:06:06 +00003232TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003233 switch (Name.getKind()) {
3234 case TemplateName::QualifiedTemplate:
3235 case TemplateName::Template: {
3236 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003237 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003238 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003239 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3240
3241 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003242 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003243 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003244
John McCall14606042011-06-30 08:33:18 +00003245 case TemplateName::OverloadedTemplate:
3246 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003247
John McCall14606042011-06-30 08:33:18 +00003248 case TemplateName::DependentTemplate: {
3249 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3250 assert(DTN && "Non-dependent template names must refer to template decls.");
3251 return DTN->CanonicalTemplateName;
3252 }
3253
3254 case TemplateName::SubstTemplateTemplateParm: {
3255 SubstTemplateTemplateParmStorage *subst
3256 = Name.getAsSubstTemplateTemplateParm();
3257 return getCanonicalTemplateName(subst->getReplacement());
3258 }
3259
3260 case TemplateName::SubstTemplateTemplateParmPack: {
3261 SubstTemplateTemplateParmPackStorage *subst
3262 = Name.getAsSubstTemplateTemplateParmPack();
3263 TemplateTemplateParmDecl *canonParameter
3264 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3265 TemplateArgument canonArgPack
3266 = getCanonicalTemplateArgument(subst->getArgumentPack());
3267 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3268 }
3269 }
3270
3271 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003272}
3273
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003274bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3275 X = getCanonicalTemplateName(X);
3276 Y = getCanonicalTemplateName(Y);
3277 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3278}
3279
Mike Stump1eb44332009-09-09 15:08:12 +00003280TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003281ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003282 switch (Arg.getKind()) {
3283 case TemplateArgument::Null:
3284 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003285
Douglas Gregor1275ae02009-07-28 23:00:59 +00003286 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003287 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003288
Douglas Gregor1275ae02009-07-28 23:00:59 +00003289 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003290 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003291
Douglas Gregor788cd062009-11-11 01:00:40 +00003292 case TemplateArgument::Template:
3293 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003294
3295 case TemplateArgument::TemplateExpansion:
3296 return TemplateArgument(getCanonicalTemplateName(
3297 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003298 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003299
Douglas Gregor1275ae02009-07-28 23:00:59 +00003300 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003301 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003302 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Douglas Gregor1275ae02009-07-28 23:00:59 +00003304 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003305 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003306
Douglas Gregor1275ae02009-07-28 23:00:59 +00003307 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003308 if (Arg.pack_size() == 0)
3309 return Arg;
3310
Douglas Gregor910f8002010-11-07 23:05:16 +00003311 TemplateArgument *CanonArgs
3312 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003313 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003314 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003315 AEnd = Arg.pack_end();
3316 A != AEnd; (void)++A, ++Idx)
3317 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003318
Douglas Gregor910f8002010-11-07 23:05:16 +00003319 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003320 }
3321 }
3322
3323 // Silence GCC warning
David Blaikieb219cfc2011-09-23 05:06:16 +00003324 llvm_unreachable("Unhandled template argument kind");
Douglas Gregor1275ae02009-07-28 23:00:59 +00003325}
3326
Douglas Gregord57959a2009-03-27 23:10:48 +00003327NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003328ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003329 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003330 return 0;
3331
3332 switch (NNS->getKind()) {
3333 case NestedNameSpecifier::Identifier:
3334 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003335 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003336 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3337 NNS->getAsIdentifier());
3338
3339 case NestedNameSpecifier::Namespace:
3340 // A namespace is canonical; build a nested-name-specifier with
3341 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003342 return NestedNameSpecifier::Create(*this, 0,
3343 NNS->getAsNamespace()->getOriginalNamespace());
3344
3345 case NestedNameSpecifier::NamespaceAlias:
3346 // A namespace is canonical; build a nested-name-specifier with
3347 // this namespace and no prefix.
3348 return NestedNameSpecifier::Create(*this, 0,
3349 NNS->getAsNamespaceAlias()->getNamespace()
3350 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003351
3352 case NestedNameSpecifier::TypeSpec:
3353 case NestedNameSpecifier::TypeSpecWithTemplate: {
3354 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003355
3356 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3357 // break it apart into its prefix and identifier, then reconsititute those
3358 // as the canonical nested-name-specifier. This is required to canonicalize
3359 // a dependent nested-name-specifier involving typedefs of dependent-name
3360 // types, e.g.,
3361 // typedef typename T::type T1;
3362 // typedef typename T1::type T2;
3363 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3364 NestedNameSpecifier *Prefix
3365 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3366 return NestedNameSpecifier::Create(*this, Prefix,
3367 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3368 }
3369
Douglas Gregor643f8432010-11-04 00:14:23 +00003370 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003371 if (const DependentTemplateSpecializationType *DTST
3372 = T->getAs<DependentTemplateSpecializationType>()) {
3373 NestedNameSpecifier *Prefix
3374 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003375
3376 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3377 Prefix, DTST->getIdentifier(),
3378 DTST->getNumArgs(),
3379 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003380 T = getCanonicalType(T);
3381 }
3382
John McCall3b657512011-01-19 10:06:00 +00003383 return NestedNameSpecifier::Create(*this, 0, false,
3384 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003385 }
3386
3387 case NestedNameSpecifier::Global:
3388 // The global specifier is canonical and unique.
3389 return NNS;
3390 }
3391
3392 // Required to silence a GCC warning
3393 return 0;
3394}
3395
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003396
Jay Foad4ba2a172011-01-12 09:06:06 +00003397const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003398 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003399 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003400 // Handle the common positive case fast.
3401 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3402 return AT;
3403 }
Mike Stump1eb44332009-09-09 15:08:12 +00003404
John McCall0953e762009-09-24 19:53:00 +00003405 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003406 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003407 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003408
John McCall0953e762009-09-24 19:53:00 +00003409 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003410 // implements C99 6.7.3p8: "If the specification of an array type includes
3411 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003413 // If we get here, we either have type qualifiers on the type, or we have
3414 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003415 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003416
John McCall3b657512011-01-19 10:06:00 +00003417 SplitQualType split = T.getSplitDesugaredType();
3418 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003420 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003421 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3422 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003423 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003425 // Otherwise, we have an array and we have qualifiers on it. Push the
3426 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003427 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003429 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3430 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3431 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003432 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003433 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3434 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3435 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003436 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003437
Mike Stump1eb44332009-09-09 15:08:12 +00003438 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003439 = dyn_cast<DependentSizedArrayType>(ATy))
3440 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003441 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003442 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003443 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003444 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003445 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003447 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003448 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003449 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003450 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003451 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003452 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003453}
3454
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003455QualType ASTContext::getAdjustedParameterType(QualType T) {
3456 // C99 6.7.5.3p7:
3457 // A declaration of a parameter as "array of type" shall be
3458 // adjusted to "qualified pointer to type", where the type
3459 // qualifiers (if any) are those specified within the [ and ] of
3460 // the array type derivation.
3461 if (T->isArrayType())
3462 return getArrayDecayedType(T);
3463
3464 // C99 6.7.5.3p8:
3465 // A declaration of a parameter as "function returning type"
3466 // shall be adjusted to "pointer to function returning type", as
3467 // in 6.3.2.1.
3468 if (T->isFunctionType())
3469 return getPointerType(T);
3470
3471 return T;
3472}
3473
3474QualType ASTContext::getSignatureParameterType(QualType T) {
3475 T = getVariableArrayDecayedType(T);
3476 T = getAdjustedParameterType(T);
3477 return T.getUnqualifiedType();
3478}
3479
Chris Lattnere6327742008-04-02 05:18:44 +00003480/// getArrayDecayedType - Return the properly qualified result of decaying the
3481/// specified array type to a pointer. This operation is non-trivial when
3482/// handling typedefs etc. The canonical type of "T" must be an array type,
3483/// this returns a pointer to a properly qualified element of the array.
3484///
3485/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003486QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003487 // Get the element type with 'getAsArrayType' so that we don't lose any
3488 // typedefs in the element type of the array. This also handles propagation
3489 // of type qualifiers from the array type into the element type if present
3490 // (C99 6.7.3p8).
3491 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3492 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003493
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003494 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003495
3496 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003497 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003498}
3499
John McCall3b657512011-01-19 10:06:00 +00003500QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3501 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003502}
3503
John McCall3b657512011-01-19 10:06:00 +00003504QualType ASTContext::getBaseElementType(QualType type) const {
3505 Qualifiers qs;
3506 while (true) {
3507 SplitQualType split = type.getSplitDesugaredType();
3508 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3509 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003510
John McCall3b657512011-01-19 10:06:00 +00003511 type = array->getElementType();
3512 qs.addConsistentQualifiers(split.second);
3513 }
Mike Stump1eb44332009-09-09 15:08:12 +00003514
John McCall3b657512011-01-19 10:06:00 +00003515 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003516}
3517
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003518/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003519uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003520ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3521 uint64_t ElementCount = 1;
3522 do {
3523 ElementCount *= CA->getSize().getZExtValue();
3524 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3525 } while (CA);
3526 return ElementCount;
3527}
3528
Reid Spencer5f016e22007-07-11 17:01:13 +00003529/// getFloatingRank - Return a relative rank for floating point types.
3530/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003531static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003532 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003533 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003534
John McCall183700f2009-09-21 23:43:11 +00003535 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3536 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003537 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00003538 case BuiltinType::Half: return HalfRank;
Reid Spencer5f016e22007-07-11 17:01:13 +00003539 case BuiltinType::Float: return FloatRank;
3540 case BuiltinType::Double: return DoubleRank;
3541 case BuiltinType::LongDouble: return LongDoubleRank;
3542 }
3543}
3544
Mike Stump1eb44332009-09-09 15:08:12 +00003545/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3546/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003547/// 'typeDomain' is a real floating point or complex type.
3548/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003549QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3550 QualType Domain) const {
3551 FloatingRank EltRank = getFloatingRank(Size);
3552 if (Domain->isComplexType()) {
3553 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003554 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003555 case FloatRank: return FloatComplexTy;
3556 case DoubleRank: return DoubleComplexTy;
3557 case LongDoubleRank: return LongDoubleComplexTy;
3558 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003559 }
Chris Lattner1361b112008-04-06 23:58:54 +00003560
3561 assert(Domain->isRealFloatingType() && "Unknown domain!");
3562 switch (EltRank) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003563 default: llvm_unreachable("getFloatingRank(): illegal value for rank");
Chris Lattner1361b112008-04-06 23:58:54 +00003564 case FloatRank: return FloatTy;
3565 case DoubleRank: return DoubleTy;
3566 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003567 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003568}
3569
Chris Lattner7cfeb082008-04-06 23:55:33 +00003570/// getFloatingTypeOrder - Compare the rank of the two specified floating
3571/// point types, ignoring the domain of the type (i.e. 'double' ==
3572/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003573/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003574int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003575 FloatingRank LHSR = getFloatingRank(LHS);
3576 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003577
Chris Lattnera75cea32008-04-06 23:38:49 +00003578 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003579 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003580 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003581 return 1;
3582 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003583}
3584
Chris Lattnerf52ab252008-04-06 22:59:24 +00003585/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3586/// routine will assert if passed a built-in type that isn't an integer or enum,
3587/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003588unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003589 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003590
Chris Lattnerf52ab252008-04-06 22:59:24 +00003591 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00003592 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattner7cfeb082008-04-06 23:55:33 +00003593 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003594 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003595 case BuiltinType::Char_S:
3596 case BuiltinType::Char_U:
3597 case BuiltinType::SChar:
3598 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003599 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003600 case BuiltinType::Short:
3601 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003602 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003603 case BuiltinType::Int:
3604 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003605 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003606 case BuiltinType::Long:
3607 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003608 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003609 case BuiltinType::LongLong:
3610 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003611 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003612 case BuiltinType::Int128:
3613 case BuiltinType::UInt128:
3614 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003615 }
3616}
3617
Eli Friedman04e83572009-08-20 04:21:42 +00003618/// \brief Whether this is a promotable bitfield reference according
3619/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3620///
3621/// \returns the type this bit-field will promote to, or NULL if no
3622/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003623QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003624 if (E->isTypeDependent() || E->isValueDependent())
3625 return QualType();
3626
Eli Friedman04e83572009-08-20 04:21:42 +00003627 FieldDecl *Field = E->getBitField();
3628 if (!Field)
3629 return QualType();
3630
3631 QualType FT = Field->getType();
3632
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003633 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman04e83572009-08-20 04:21:42 +00003634 uint64_t IntSize = getTypeSize(IntTy);
3635 // GCC extension compatibility: if the bit-field size is less than or equal
3636 // to the size of int, it gets promoted no matter what its type is.
3637 // For instance, unsigned long bf : 4 gets promoted to signed int.
3638 if (BitWidth < IntSize)
3639 return IntTy;
3640
3641 if (BitWidth == IntSize)
3642 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3643
3644 // Types bigger than int are not subject to promotions, and therefore act
3645 // like the base type.
3646 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3647 // is ridiculous.
3648 return QualType();
3649}
3650
Eli Friedmana95d7572009-08-19 07:44:53 +00003651/// getPromotedIntegerType - Returns the type that Promotable will
3652/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3653/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003654QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003655 assert(!Promotable.isNull());
3656 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003657 if (const EnumType *ET = Promotable->getAs<EnumType>())
3658 return ET->getDecl()->getPromotionType();
Eli Friedman68a2dc42011-10-26 07:22:48 +00003659
3660 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3661 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3662 // (3.9.1) can be converted to a prvalue of the first of the following
3663 // types that can represent all the values of its underlying type:
3664 // int, unsigned int, long int, unsigned long int, long long int, or
3665 // unsigned long long int [...]
3666 // FIXME: Is there some better way to compute this?
3667 if (BT->getKind() == BuiltinType::WChar_S ||
3668 BT->getKind() == BuiltinType::WChar_U ||
3669 BT->getKind() == BuiltinType::Char16 ||
3670 BT->getKind() == BuiltinType::Char32) {
3671 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3672 uint64_t FromSize = getTypeSize(BT);
3673 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3674 LongLongTy, UnsignedLongLongTy };
3675 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3676 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3677 if (FromSize < ToSize ||
3678 (FromSize == ToSize &&
3679 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3680 return PromoteTypes[Idx];
3681 }
3682 llvm_unreachable("char type should fit into long long");
3683 }
3684 }
3685
3686 // At this point, we should have a signed or unsigned integer type.
Eli Friedmana95d7572009-08-19 07:44:53 +00003687 if (Promotable->isSignedIntegerType())
3688 return IntTy;
3689 uint64_t PromotableSize = getTypeSize(Promotable);
3690 uint64_t IntSize = getTypeSize(IntTy);
3691 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3692 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3693}
3694
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003695/// \brief Recurses in pointer/array types until it finds an objc retainable
3696/// type and returns its ownership.
3697Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3698 while (!T.isNull()) {
3699 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3700 return T.getObjCLifetime();
3701 if (T->isArrayType())
3702 T = getBaseElementType(T);
3703 else if (const PointerType *PT = T->getAs<PointerType>())
3704 T = PT->getPointeeType();
3705 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003706 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003707 else
3708 break;
3709 }
3710
3711 return Qualifiers::OCL_None;
3712}
3713
Mike Stump1eb44332009-09-09 15:08:12 +00003714/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003715/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003716/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003717int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003718 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3719 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003720 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Chris Lattnerf52ab252008-04-06 22:59:24 +00003722 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3723 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Chris Lattner7cfeb082008-04-06 23:55:33 +00003725 unsigned LHSRank = getIntegerRank(LHSC);
3726 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003727
Chris Lattner7cfeb082008-04-06 23:55:33 +00003728 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3729 if (LHSRank == RHSRank) return 0;
3730 return LHSRank > RHSRank ? 1 : -1;
3731 }
Mike Stump1eb44332009-09-09 15:08:12 +00003732
Chris Lattner7cfeb082008-04-06 23:55:33 +00003733 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3734 if (LHSUnsigned) {
3735 // If the unsigned [LHS] type is larger, return it.
3736 if (LHSRank >= RHSRank)
3737 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Chris Lattner7cfeb082008-04-06 23:55:33 +00003739 // If the signed type can represent all values of the unsigned type, it
3740 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003741 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003742 return -1;
3743 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003744
Chris Lattner7cfeb082008-04-06 23:55:33 +00003745 // If the unsigned [RHS] type is larger, return it.
3746 if (RHSRank >= LHSRank)
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;
Reid Spencer5f016e22007-07-11 17:01:13 +00003753}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003754
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003755static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003756CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3757 DeclContext *DC, IdentifierInfo *Id) {
3758 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003759 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003760 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003761 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003762 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003763}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003764
Mike Stump1eb44332009-09-09 15:08:12 +00003765// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003766QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003767 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003768 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003769 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003770 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003771 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003772
Anders Carlssonf06273f2007-11-19 00:25:30 +00003773 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Anders Carlsson71993dd2007-08-17 05:31:46 +00003775 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003776 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003777 // int flags;
3778 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003779 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003780 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003781 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003782 FieldTypes[3] = LongTy;
3783
Anders Carlsson71993dd2007-08-17 05:31:46 +00003784 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003785 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003786 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003787 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003788 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003789 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003790 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003791 /*Mutable=*/false,
3792 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003793 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003794 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003795 }
3796
Douglas Gregor838db382010-02-11 01:19:42 +00003797 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003798 }
Mike Stump1eb44332009-09-09 15:08:12 +00003799
Anders Carlsson71993dd2007-08-17 05:31:46 +00003800 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003801}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003802
Douglas Gregor319ac892009-04-23 22:29:11 +00003803void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003804 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003805 assert(Rec && "Invalid CFConstantStringType");
3806 CFConstantStringTypeDecl = Rec->getDecl();
3807}
3808
Jay Foad4ba2a172011-01-12 09:06:06 +00003809QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003810 if (BlockDescriptorType)
3811 return getTagDeclType(BlockDescriptorType);
3812
3813 RecordDecl *T;
3814 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003815 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003816 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003817 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003818
3819 QualType FieldTypes[] = {
3820 UnsignedLongTy,
3821 UnsignedLongTy,
3822 };
3823
3824 const char *FieldNames[] = {
3825 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003826 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003827 };
3828
3829 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003830 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003831 SourceLocation(),
3832 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003833 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003834 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003835 /*Mutable=*/false,
3836 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003837 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003838 T->addDecl(Field);
3839 }
3840
Douglas Gregor838db382010-02-11 01:19:42 +00003841 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003842
3843 BlockDescriptorType = T;
3844
3845 return getTagDeclType(BlockDescriptorType);
3846}
3847
Jay Foad4ba2a172011-01-12 09:06:06 +00003848QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003849 if (BlockDescriptorExtendedType)
3850 return getTagDeclType(BlockDescriptorExtendedType);
3851
3852 RecordDecl *T;
3853 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003854 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003855 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003856 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003857
3858 QualType FieldTypes[] = {
3859 UnsignedLongTy,
3860 UnsignedLongTy,
3861 getPointerType(VoidPtrTy),
3862 getPointerType(VoidPtrTy)
3863 };
3864
3865 const char *FieldNames[] = {
3866 "reserved",
3867 "Size",
3868 "CopyFuncPtr",
3869 "DestroyFuncPtr"
3870 };
3871
3872 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003873 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003874 SourceLocation(),
3875 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003876 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003877 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003878 /*Mutable=*/false,
3879 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003880 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003881 T->addDecl(Field);
3882 }
3883
Douglas Gregor838db382010-02-11 01:19:42 +00003884 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003885
3886 BlockDescriptorExtendedType = T;
3887
3888 return getTagDeclType(BlockDescriptorExtendedType);
3889}
3890
Jay Foad4ba2a172011-01-12 09:06:06 +00003891bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003892 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003893 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003894 if (getLangOptions().CPlusPlus) {
3895 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3896 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003897 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003898
3899 }
3900 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003901 return false;
3902}
3903
Jay Foad4ba2a172011-01-12 09:06:06 +00003904QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003905ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003906 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003907 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003908 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003909 // unsigned int __flags;
3910 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003911 // void *__copy_helper; // as needed
3912 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003913 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003914 // } *
3915
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003916 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3917
3918 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003919 llvm::SmallString<36> Name;
3920 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3921 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003922 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003923 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003924 T->startDefinition();
3925 QualType Int32Ty = IntTy;
3926 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3927 QualType FieldTypes[] = {
3928 getPointerType(VoidPtrTy),
3929 getPointerType(getTagDeclType(T)),
3930 Int32Ty,
3931 Int32Ty,
3932 getPointerType(VoidPtrTy),
3933 getPointerType(VoidPtrTy),
3934 Ty
3935 };
3936
Chris Lattner5f9e2722011-07-23 10:55:15 +00003937 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003938 "__isa",
3939 "__forwarding",
3940 "__flags",
3941 "__size",
3942 "__copy_helper",
3943 "__destroy_helper",
3944 DeclName,
3945 };
3946
3947 for (size_t i = 0; i < 7; ++i) {
3948 if (!HasCopyAndDispose && i >=4 && i <= 5)
3949 continue;
3950 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003951 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003952 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003953 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003954 /*BitWidth=*/0, /*Mutable=*/false,
3955 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003956 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003957 T->addDecl(Field);
3958 }
3959
Douglas Gregor838db382010-02-11 01:19:42 +00003960 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003961
3962 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003963}
3964
Douglas Gregore97179c2011-09-08 01:46:34 +00003965TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3966 if (!ObjCInstanceTypeDecl)
3967 ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3968 getTranslationUnitDecl(),
3969 SourceLocation(),
3970 SourceLocation(),
3971 &Idents.get("instancetype"),
3972 getTrivialTypeSourceInfo(getObjCIdType()));
3973 return ObjCInstanceTypeDecl;
3974}
3975
Anders Carlssone8c49532007-10-29 06:33:42 +00003976// This returns true if a type has been typedefed to BOOL:
3977// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003978static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003979 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003980 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3981 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003982
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003983 return false;
3984}
3985
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003986/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003987/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003988CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003989 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3990 return CharUnits::Zero();
3991
Ken Dyck199c3d62010-01-11 17:06:35 +00003992 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003993
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003994 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003995 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003996 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003997 // Treat arrays as pointers, since that's how they're passed in.
3998 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003999 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004000 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00004001}
4002
4003static inline
4004std::string charUnitsToString(const CharUnits &CU) {
4005 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004006}
4007
John McCall6b5a61b2011-02-07 10:33:21 +00004008/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00004009/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00004010std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4011 std::string S;
4012
David Chisnall5e530af2009-11-17 19:33:30 +00004013 const BlockDecl *Decl = Expr->getBlockDecl();
4014 QualType BlockTy =
4015 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4016 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00004017 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00004018 // Compute size of all parameters.
4019 // Start with computing size of a pointer in number of bytes.
4020 // FIXME: There might(should) be a better way of doing this computation!
4021 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004022 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4023 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00004024 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00004025 E = Decl->param_end(); PI != E; ++PI) {
4026 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004027 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00004028 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00004029 ParmOffset += sz;
4030 }
4031 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00004032 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00004033 // Block pointer and offset.
4034 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00004035
4036 // Argument types.
4037 ParmOffset = PtrSize;
4038 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4039 Decl->param_end(); PI != E; ++PI) {
4040 ParmVarDecl *PVDecl = *PI;
4041 QualType PType = PVDecl->getOriginalType();
4042 if (const ArrayType *AT =
4043 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4044 // Use array's original type only if it has known number of
4045 // elements.
4046 if (!isa<ConstantArrayType>(AT))
4047 PType = PVDecl->getType();
4048 } else if (PType->isFunctionType())
4049 PType = PVDecl->getType();
4050 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00004051 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004052 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00004053 }
John McCall6b5a61b2011-02-07 10:33:21 +00004054
4055 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00004056}
4057
Douglas Gregorf968d832011-05-27 01:19:52 +00004058bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00004059 std::string& S) {
4060 // Encode result type.
4061 getObjCEncodingForType(Decl->getResultType(), S);
4062 CharUnits ParmOffset;
4063 // Compute size of all parameters.
4064 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4065 E = Decl->param_end(); PI != E; ++PI) {
4066 QualType PType = (*PI)->getType();
4067 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004068 if (sz.isZero())
4069 return true;
4070
David Chisnall5389f482010-12-30 14:05:53 +00004071 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00004072 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00004073 ParmOffset += sz;
4074 }
4075 S += charUnitsToString(ParmOffset);
4076 ParmOffset = CharUnits::Zero();
4077
4078 // Argument types.
4079 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4080 E = Decl->param_end(); PI != E; ++PI) {
4081 ParmVarDecl *PVDecl = *PI;
4082 QualType PType = PVDecl->getOriginalType();
4083 if (const ArrayType *AT =
4084 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4085 // Use array's original type only if it has known number of
4086 // elements.
4087 if (!isa<ConstantArrayType>(AT))
4088 PType = PVDecl->getType();
4089 } else if (PType->isFunctionType())
4090 PType = PVDecl->getType();
4091 getObjCEncodingForType(PType, S);
4092 S += charUnitsToString(ParmOffset);
4093 ParmOffset += getObjCEncodingTypeSize(PType);
4094 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004095
4096 return false;
David Chisnall5389f482010-12-30 14:05:53 +00004097}
4098
Bob Wilsondc8dab62011-11-30 01:57:58 +00004099/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4100/// method parameter or return type. If Extended, include class names and
4101/// block object types.
4102void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4103 QualType T, std::string& S,
4104 bool Extended) const {
4105 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4106 getObjCEncodingForTypeQualifier(QT, S);
4107 // Encode parameter type.
4108 getObjCEncodingForTypeImpl(T, S, true, true, 0,
4109 true /*OutermostType*/,
4110 false /*EncodingProperty*/,
4111 false /*StructField*/,
4112 Extended /*EncodeBlockParameters*/,
4113 Extended /*EncodeClassNames*/);
4114}
4115
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004116/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004117/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00004118bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004119 std::string& S,
4120 bool Extended) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004121 // FIXME: This is not very efficient.
Bob Wilsondc8dab62011-11-30 01:57:58 +00004122 // Encode return type.
4123 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4124 Decl->getResultType(), S, Extended);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004125 // Compute size of all parameters.
4126 // Start with computing size of a pointer in number of bytes.
4127 // FIXME: There might(should) be a better way of doing this computation!
4128 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00004129 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004130 // The first two arguments (self and _cmd) are pointers; account for
4131 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00004132 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004133 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004134 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00004135 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00004136 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00004137 if (sz.isZero())
4138 return true;
4139
Ken Dyck199c3d62010-01-11 17:06:35 +00004140 assert (sz.isPositive() &&
4141 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004142 ParmOffset += sz;
4143 }
Ken Dyck199c3d62010-01-11 17:06:35 +00004144 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004145 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00004146 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00004147
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004148 // Argument types.
4149 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004150 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00004151 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00004152 const ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00004153 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00004154 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00004155 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4156 // Use array's original type only if it has known number of
4157 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00004158 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00004159 PType = PVDecl->getType();
4160 } else if (PType->isFunctionType())
4161 PType = PVDecl->getType();
Bob Wilsondc8dab62011-11-30 01:57:58 +00004162 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4163 PType, S, Extended);
Ken Dyck199c3d62010-01-11 17:06:35 +00004164 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00004165 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004166 }
Douglas Gregorf968d832011-05-27 01:19:52 +00004167
4168 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00004169}
4170
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004171/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004172/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004173/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4174/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00004175/// Property attributes are stored as a comma-delimited C string. The simple
4176/// attributes readonly and bycopy are encoded as single characters. The
4177/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4178/// encoded as single characters, followed by an identifier. Property types
4179/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00004180/// these attributes are defined by the following enumeration:
4181/// @code
4182/// enum PropertyAttributes {
4183/// kPropertyReadOnly = 'R', // property is read-only.
4184/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
4185/// kPropertyByref = '&', // property is a reference to the value last assigned
4186/// kPropertyDynamic = 'D', // property is dynamic
4187/// kPropertyGetter = 'G', // followed by getter selector name
4188/// kPropertySetter = 'S', // followed by setter selector name
4189/// kPropertyInstanceVariable = 'V' // followed by instance variable name
4190/// kPropertyType = 't' // followed by old-style type encoding.
4191/// kPropertyWeak = 'W' // 'weak' property
4192/// kPropertyStrong = 'P' // property GC'able
4193/// kPropertyNonAtomic = 'N' // property non-atomic
4194/// };
4195/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00004196void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004197 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004198 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004199 // Collect information from the property implementation decl(s).
4200 bool Dynamic = false;
4201 ObjCPropertyImplDecl *SynthesizePID = 0;
4202
4203 // FIXME: Duplicated code due to poor abstraction.
4204 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004205 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004206 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4207 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004208 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004209 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004210 ObjCPropertyImplDecl *PID = *i;
4211 if (PID->getPropertyDecl() == PD) {
4212 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4213 Dynamic = true;
4214 } else {
4215 SynthesizePID = PID;
4216 }
4217 }
4218 }
4219 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004220 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004221 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004222 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004223 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004224 ObjCPropertyImplDecl *PID = *i;
4225 if (PID->getPropertyDecl() == PD) {
4226 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4227 Dynamic = true;
4228 } else {
4229 SynthesizePID = PID;
4230 }
4231 }
Mike Stump1eb44332009-09-09 15:08:12 +00004232 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004233 }
4234 }
4235
4236 // FIXME: This is not very efficient.
4237 S = "T";
4238
4239 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004240 // GCC has some special rules regarding encoding of properties which
4241 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004242 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004243 true /* outermost type */,
4244 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004245
4246 if (PD->isReadOnly()) {
4247 S += ",R";
4248 } else {
4249 switch (PD->getSetterKind()) {
4250 case ObjCPropertyDecl::Assign: break;
4251 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004252 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian3a02b442011-08-12 20:47:08 +00004253 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004254 }
4255 }
4256
4257 // It really isn't clear at all what this means, since properties
4258 // are "dynamic by default".
4259 if (Dynamic)
4260 S += ",D";
4261
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004262 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4263 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004264
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004265 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4266 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004267 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004268 }
4269
4270 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4271 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004272 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004273 }
4274
4275 if (SynthesizePID) {
4276 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4277 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004278 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004279 }
4280
4281 // FIXME: OBJCGC: weak & strong
4282}
4283
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004284/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004285/// Another legacy compatibility encoding: 32-bit longs are encoded as
4286/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004287/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4288///
4289void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004290 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004291 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004292 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004293 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004294 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004295 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004296 PointeeTy = IntTy;
4297 }
4298 }
4299}
4300
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004301void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004302 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004303 // We follow the behavior of gcc, expanding structures which are
4304 // directly pointed to, and expanding embedded structures. Note that
4305 // these rules are sufficient to prevent recursive encoding of the
4306 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004307 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004308 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004309}
4310
David Chisnall64fd7e82010-06-04 01:10:52 +00004311static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4312 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00004313 default: llvm_unreachable("Unhandled builtin type kind");
David Chisnall64fd7e82010-06-04 01:10:52 +00004314 case BuiltinType::Void: return 'v';
4315 case BuiltinType::Bool: return 'B';
4316 case BuiltinType::Char_U:
4317 case BuiltinType::UChar: return 'C';
4318 case BuiltinType::UShort: return 'S';
4319 case BuiltinType::UInt: return 'I';
4320 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004321 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004322 case BuiltinType::UInt128: return 'T';
4323 case BuiltinType::ULongLong: return 'Q';
4324 case BuiltinType::Char_S:
4325 case BuiltinType::SChar: return 'c';
4326 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004327 case BuiltinType::WChar_S:
4328 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004329 case BuiltinType::Int: return 'i';
4330 case BuiltinType::Long:
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::LongLong: return 'q';
4333 case BuiltinType::Int128: return 't';
4334 case BuiltinType::Float: return 'f';
4335 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004336 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004337 }
4338}
4339
Douglas Gregor5471bc82011-09-08 17:18:35 +00004340static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4341 EnumDecl *Enum = ET->getDecl();
4342
4343 // The encoding of an non-fixed enum type is always 'i', regardless of size.
4344 if (!Enum->isFixed())
4345 return 'i';
4346
4347 // The encoding of a fixed enum type matches its fixed underlying type.
4348 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4349}
4350
Jay Foad4ba2a172011-01-12 09:06:06 +00004351static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004352 QualType T, const FieldDecl *FD) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004353 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004354 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004355 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4356 // The GNU runtime requires more information; bitfields are encoded as b,
4357 // then the offset (in bits) of the first element, then the type of the
4358 // bitfield, then the size in bits. For example, in this structure:
4359 //
4360 // struct
4361 // {
4362 // int integer;
4363 // int flags:2;
4364 // };
4365 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4366 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4367 // information is not especially sensible, but we're stuck with it for
4368 // compatibility with GCC, although providing it breaks anything that
4369 // actually uses runtime introspection and wants to work on both runtimes...
4370 if (!Ctx->getLangOptions().NeXTRuntime) {
4371 const RecordDecl *RD = FD->getParent();
4372 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004373 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor5471bc82011-09-08 17:18:35 +00004374 if (const EnumType *ET = T->getAs<EnumType>())
4375 S += ObjCEncodingForEnumType(Ctx, ET);
David Chisnallc7ff82c2010-12-26 20:12:30 +00004376 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004377 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004378 }
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004379 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004380}
4381
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004382// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004383void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4384 bool ExpandPointedToStructures,
4385 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004386 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004387 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004388 bool EncodingProperty,
Bob Wilsondc8dab62011-11-30 01:57:58 +00004389 bool StructField,
4390 bool EncodeBlockParameters,
4391 bool EncodeClassNames) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004392 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004393 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004394 return EncodeBitField(this, S, T, FD);
4395 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004396 return;
4397 }
Mike Stump1eb44332009-09-09 15:08:12 +00004398
John McCall183700f2009-09-21 23:43:11 +00004399 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004400 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004401 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004402 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004403 return;
4404 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004405
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004406 // encoding for pointer or r3eference types.
4407 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004408 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004409 if (PT->isObjCSelType()) {
4410 S += ':';
4411 return;
4412 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004413 PointeeTy = PT->getPointeeType();
4414 }
4415 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4416 PointeeTy = RT->getPointeeType();
4417 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004418 bool isReadOnly = false;
4419 // For historical/compatibility reasons, the read-only qualifier of the
4420 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4421 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004422 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004423 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004424 if (OutermostType && T.isConstQualified()) {
4425 isReadOnly = true;
4426 S += 'r';
4427 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004428 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004429 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004430 while (P->getAs<PointerType>())
4431 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004432 if (P.isConstQualified()) {
4433 isReadOnly = true;
4434 S += 'r';
4435 }
4436 }
4437 if (isReadOnly) {
4438 // Another legacy compatibility encoding. Some ObjC qualifier and type
4439 // combinations need to be rearranged.
4440 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004441 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004442 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004443 }
Mike Stump1eb44332009-09-09 15:08:12 +00004444
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004445 if (PointeeTy->isCharType()) {
4446 // char pointer types should be encoded as '*' unless it is a
4447 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004448 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004449 S += '*';
4450 return;
4451 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004452 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004453 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4454 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4455 S += '#';
4456 return;
4457 }
4458 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4459 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4460 S += '@';
4461 return;
4462 }
4463 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004464 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004465 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004466 getLegacyIntegralTypeEncoding(PointeeTy);
4467
Mike Stump1eb44332009-09-09 15:08:12 +00004468 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004469 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004470 return;
4471 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004472
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004473 if (const ArrayType *AT =
4474 // Ignore type qualifiers etc.
4475 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004476 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004477 // Incomplete arrays are encoded as a pointer to the array element.
4478 S += '^';
4479
Mike Stump1eb44332009-09-09 15:08:12 +00004480 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004481 false, ExpandStructures, FD);
4482 } else {
4483 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004485 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4486 if (getTypeSize(CAT->getElementType()) == 0)
4487 S += '0';
4488 else
4489 S += llvm::utostr(CAT->getSize().getZExtValue());
4490 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004491 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004492 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4493 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004494 S += '0';
4495 }
Mike Stump1eb44332009-09-09 15:08:12 +00004496
4497 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004498 false, ExpandStructures, FD);
4499 S += ']';
4500 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004501 return;
4502 }
Mike Stump1eb44332009-09-09 15:08:12 +00004503
John McCall183700f2009-09-21 23:43:11 +00004504 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004505 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004506 return;
4507 }
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Ted Kremenek6217b802009-07-29 21:53:49 +00004509 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004510 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004511 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004512 // Anonymous structures print as '?'
4513 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4514 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004515 if (ClassTemplateSpecializationDecl *Spec
4516 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4517 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4518 std::string TemplateArgsStr
4519 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004520 TemplateArgs.data(),
4521 TemplateArgs.size(),
Douglas Gregor30c42402011-09-27 22:38:19 +00004522 (*this).getPrintingPolicy());
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004523
4524 S += TemplateArgsStr;
4525 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004526 } else {
4527 S += '?';
4528 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004529 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004530 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004531 if (!RDecl->isUnion()) {
4532 getObjCEncodingForStructureImpl(RDecl, S, FD);
4533 } else {
4534 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4535 FieldEnd = RDecl->field_end();
4536 Field != FieldEnd; ++Field) {
4537 if (FD) {
4538 S += '"';
4539 S += Field->getNameAsString();
4540 S += '"';
4541 }
Mike Stump1eb44332009-09-09 15:08:12 +00004542
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004543 // Special case bit-fields.
4544 if (Field->isBitField()) {
4545 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4546 (*Field));
4547 } else {
4548 QualType qt = Field->getType();
4549 getLegacyIntegralTypeEncoding(qt);
4550 getObjCEncodingForTypeImpl(qt, S, false, true,
4551 FD, /*OutermostType*/false,
4552 /*EncodingProperty*/false,
4553 /*StructField*/true);
4554 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004555 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004556 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004557 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004558 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004559 return;
4560 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004561
Douglas Gregor5471bc82011-09-08 17:18:35 +00004562 if (const EnumType *ET = T->getAs<EnumType>()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004563 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004564 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004565 else
Douglas Gregor5471bc82011-09-08 17:18:35 +00004566 S += ObjCEncodingForEnumType(this, ET);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004567 return;
4568 }
Mike Stump1eb44332009-09-09 15:08:12 +00004569
Bob Wilsondc8dab62011-11-30 01:57:58 +00004570 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004571 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilsondc8dab62011-11-30 01:57:58 +00004572 if (EncodeBlockParameters) {
4573 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4574
4575 S += '<';
4576 // Block return type
4577 getObjCEncodingForTypeImpl(FT->getResultType(), S,
4578 ExpandPointedToStructures, ExpandStructures,
4579 FD,
4580 false /* OutermostType */,
4581 EncodingProperty,
4582 false /* StructField */,
4583 EncodeBlockParameters,
4584 EncodeClassNames);
4585 // Block self
4586 S += "@?";
4587 // Block parameters
4588 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4589 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4590 E = FPT->arg_type_end(); I && (I != E); ++I) {
4591 getObjCEncodingForTypeImpl(*I, S,
4592 ExpandPointedToStructures,
4593 ExpandStructures,
4594 FD,
4595 false /* OutermostType */,
4596 EncodingProperty,
4597 false /* StructField */,
4598 EncodeBlockParameters,
4599 EncodeClassNames);
4600 }
4601 }
4602 S += '>';
4603 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004604 return;
4605 }
Mike Stump1eb44332009-09-09 15:08:12 +00004606
John McCallc12c5bb2010-05-15 11:32:37 +00004607 // Ignore protocol qualifiers when mangling at this level.
4608 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4609 T = OT->getBaseType();
4610
John McCall0953e762009-09-24 19:53:00 +00004611 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004612 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004613 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004614 S += '{';
4615 const IdentifierInfo *II = OI->getIdentifier();
4616 S += II->getName();
4617 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004618 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004619 DeepCollectObjCIvars(OI, true, Ivars);
4620 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004621 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004622 if (Field->isBitField())
4623 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004624 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004625 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004626 }
4627 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004628 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004629 }
Mike Stump1eb44332009-09-09 15:08:12 +00004630
John McCall183700f2009-09-21 23:43:11 +00004631 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004632 if (OPT->isObjCIdType()) {
4633 S += '@';
4634 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004635 }
Mike Stump1eb44332009-09-09 15:08:12 +00004636
Steve Naroff27d20a22009-10-28 22:03:49 +00004637 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4638 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4639 // Since this is a binary compatibility issue, need to consult with runtime
4640 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004641 S += '#';
4642 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004643 }
Mike Stump1eb44332009-09-09 15:08:12 +00004644
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004645 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004646 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004647 ExpandPointedToStructures,
4648 ExpandStructures, FD);
Bob Wilsondc8dab62011-11-30 01:57:58 +00004649 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff14108da2009-07-10 23:34:53 +00004650 // Note that we do extended encoding of protocol qualifer list
4651 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004652 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004653 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4654 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004655 S += '<';
4656 S += (*I)->getNameAsString();
4657 S += '>';
4658 }
4659 S += '"';
4660 }
4661 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004662 }
Mike Stump1eb44332009-09-09 15:08:12 +00004663
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004664 QualType PointeeTy = OPT->getPointeeType();
4665 if (!EncodingProperty &&
4666 isa<TypedefType>(PointeeTy.getTypePtr())) {
4667 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004668 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004669 // {...};
4670 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004671 getObjCEncodingForTypeImpl(PointeeTy, S,
4672 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004673 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004674 return;
4675 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004676
4677 S += '@';
Bob Wilsondc8dab62011-11-30 01:57:58 +00004678 if (OPT->getInterfaceDecl() &&
4679 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004680 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004681 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004682 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4683 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004684 S += '<';
4685 S += (*I)->getNameAsString();
4686 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004687 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004688 S += '"';
4689 }
4690 return;
4691 }
Mike Stump1eb44332009-09-09 15:08:12 +00004692
John McCall532ec7b2010-05-17 23:56:34 +00004693 // gcc just blithely ignores member pointers.
4694 // TODO: maybe there should be a mangling for these
4695 if (T->getAs<MemberPointerType>())
4696 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004697
4698 if (T->isVectorType()) {
4699 // This matches gcc's encoding, even though technically it is
4700 // insufficient.
4701 // FIXME. We should do a better job than gcc.
4702 return;
4703 }
4704
David Blaikieb219cfc2011-09-23 05:06:16 +00004705 llvm_unreachable("@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004706}
4707
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004708void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4709 std::string &S,
4710 const FieldDecl *FD,
4711 bool includeVBases) const {
4712 assert(RDecl && "Expected non-null RecordDecl");
4713 assert(!RDecl->isUnion() && "Should not be called for unions");
4714 if (!RDecl->getDefinition())
4715 return;
4716
4717 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4718 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4719 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4720
4721 if (CXXRec) {
4722 for (CXXRecordDecl::base_class_iterator
4723 BI = CXXRec->bases_begin(),
4724 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4725 if (!BI->isVirtual()) {
4726 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004727 if (base->isEmpty())
4728 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004729 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4730 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4731 std::make_pair(offs, base));
4732 }
4733 }
4734 }
4735
4736 unsigned i = 0;
4737 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4738 FieldEnd = RDecl->field_end();
4739 Field != FieldEnd; ++Field, ++i) {
4740 uint64_t offs = layout.getFieldOffset(i);
4741 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4742 std::make_pair(offs, *Field));
4743 }
4744
4745 if (CXXRec && includeVBases) {
4746 for (CXXRecordDecl::base_class_iterator
4747 BI = CXXRec->vbases_begin(),
4748 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4749 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004750 if (base->isEmpty())
4751 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004752 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
Argyrios Kyrtzidis19aa8602011-09-26 18:14:24 +00004753 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4754 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4755 std::make_pair(offs, base));
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004756 }
4757 }
4758
4759 CharUnits size;
4760 if (CXXRec) {
4761 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4762 } else {
4763 size = layout.getSize();
4764 }
4765
4766 uint64_t CurOffs = 0;
4767 std::multimap<uint64_t, NamedDecl *>::iterator
4768 CurLayObj = FieldOrBaseOffsets.begin();
4769
Argyrios Kyrtzidiscb8061e2011-08-22 16:03:14 +00004770 if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4771 (CurLayObj == FieldOrBaseOffsets.end() &&
4772 CXXRec && CXXRec->isDynamicClass())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004773 assert(CXXRec && CXXRec->isDynamicClass() &&
4774 "Offset 0 was empty but no VTable ?");
4775 if (FD) {
4776 S += "\"_vptr$";
4777 std::string recname = CXXRec->getNameAsString();
4778 if (recname.empty()) recname = "?";
4779 S += recname;
4780 S += '"';
4781 }
4782 S += "^^?";
4783 CurOffs += getTypeSize(VoidPtrTy);
4784 }
4785
4786 if (!RDecl->hasFlexibleArrayMember()) {
4787 // Mark the end of the structure.
4788 uint64_t offs = toBits(size);
4789 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4790 std::make_pair(offs, (NamedDecl*)0));
4791 }
4792
4793 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4794 assert(CurOffs <= CurLayObj->first);
4795
4796 if (CurOffs < CurLayObj->first) {
4797 uint64_t padding = CurLayObj->first - CurOffs;
4798 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4799 // packing/alignment of members is different that normal, in which case
4800 // the encoding will be out-of-sync with the real layout.
4801 // If the runtime switches to just consider the size of types without
4802 // taking into account alignment, we could make padding explicit in the
4803 // encoding (e.g. using arrays of chars). The encoding strings would be
4804 // longer then though.
4805 CurOffs += padding;
4806 }
4807
4808 NamedDecl *dcl = CurLayObj->second;
4809 if (dcl == 0)
4810 break; // reached end of structure.
4811
4812 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4813 // We expand the bases without their virtual bases since those are going
4814 // in the initial structure. Note that this differs from gcc which
4815 // expands virtual bases each time one is encountered in the hierarchy,
4816 // making the encoding type bigger than it really is.
4817 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004818 assert(!base->isEmpty());
4819 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004820 } else {
4821 FieldDecl *field = cast<FieldDecl>(dcl);
4822 if (FD) {
4823 S += '"';
4824 S += field->getNameAsString();
4825 S += '"';
4826 }
4827
4828 if (field->isBitField()) {
4829 EncodeBitField(this, S, field->getType(), field);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004830 CurOffs += field->getBitWidthValue(*this);
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004831 } else {
4832 QualType qt = field->getType();
4833 getLegacyIntegralTypeEncoding(qt);
4834 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4835 /*OutermostType*/false,
4836 /*EncodingProperty*/false,
4837 /*StructField*/true);
4838 CurOffs += getTypeSize(field->getType());
4839 }
4840 }
4841 }
4842}
4843
Mike Stump1eb44332009-09-09 15:08:12 +00004844void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004845 std::string& S) const {
4846 if (QT & Decl::OBJC_TQ_In)
4847 S += 'n';
4848 if (QT & Decl::OBJC_TQ_Inout)
4849 S += 'N';
4850 if (QT & Decl::OBJC_TQ_Out)
4851 S += 'o';
4852 if (QT & Decl::OBJC_TQ_Bycopy)
4853 S += 'O';
4854 if (QT & Decl::OBJC_TQ_Byref)
4855 S += 'R';
4856 if (QT & Decl::OBJC_TQ_Oneway)
4857 S += 'V';
4858}
4859
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004860void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004861 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004862
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004863 BuiltinVaListType = T;
4864}
4865
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004866TypedefDecl *ASTContext::getObjCIdDecl() const {
4867 if (!ObjCIdDecl) {
4868 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4869 T = getObjCObjectPointerType(T);
4870 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4871 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4872 getTranslationUnitDecl(),
4873 SourceLocation(), SourceLocation(),
4874 &Idents.get("id"), IdInfo);
4875 }
4876
4877 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004878}
4879
Douglas Gregor7a27ea52011-08-12 06:17:30 +00004880TypedefDecl *ASTContext::getObjCSelDecl() const {
4881 if (!ObjCSelDecl) {
4882 QualType SelT = getPointerType(ObjCBuiltinSelTy);
4883 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4884 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4885 getTranslationUnitDecl(),
4886 SourceLocation(), SourceLocation(),
4887 &Idents.get("SEL"), SelInfo);
4888 }
4889 return ObjCSelDecl;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004890}
4891
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004892void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004893 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004894}
4895
Douglas Gregor79d67262011-08-12 05:59:41 +00004896TypedefDecl *ASTContext::getObjCClassDecl() const {
4897 if (!ObjCClassDecl) {
4898 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4899 T = getObjCObjectPointerType(T);
4900 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4901 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4902 getTranslationUnitDecl(),
4903 SourceLocation(), SourceLocation(),
4904 &Idents.get("Class"), ClassInfo);
4905 }
4906
4907 return ObjCClassDecl;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004908}
4909
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004910void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004911 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004912 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004913
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004914 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004915}
4916
John McCall0bd6feb2009-12-02 08:04:21 +00004917/// \brief Retrieve the template name that corresponds to a non-empty
4918/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004919TemplateName
4920ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4921 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004922 unsigned size = End - Begin;
4923 assert(size > 1 && "set is not overloaded!");
4924
4925 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4926 size * sizeof(FunctionTemplateDecl*));
4927 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4928
4929 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004930 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004931 NamedDecl *D = *I;
4932 assert(isa<FunctionTemplateDecl>(D) ||
4933 (isa<UsingShadowDecl>(D) &&
4934 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4935 *Storage++ = D;
4936 }
4937
4938 return TemplateName(OT);
4939}
4940
Douglas Gregor7532dc62009-03-30 22:58:21 +00004941/// \brief Retrieve the template name that represents a qualified
4942/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004943TemplateName
4944ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4945 bool TemplateKeyword,
4946 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004947 assert(NNS && "Missing nested-name-specifier in qualified template name");
4948
Douglas Gregor789b1f62010-02-04 18:10:26 +00004949 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004950 llvm::FoldingSetNodeID ID;
4951 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4952
4953 void *InsertPos = 0;
4954 QualifiedTemplateName *QTN =
4955 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4956 if (!QTN) {
4957 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4958 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4959 }
4960
4961 return TemplateName(QTN);
4962}
4963
4964/// \brief Retrieve the template name that represents a dependent
4965/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004966TemplateName
4967ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4968 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004969 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004970 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004971
4972 llvm::FoldingSetNodeID ID;
4973 DependentTemplateName::Profile(ID, NNS, Name);
4974
4975 void *InsertPos = 0;
4976 DependentTemplateName *QTN =
4977 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4978
4979 if (QTN)
4980 return TemplateName(QTN);
4981
4982 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4983 if (CanonNNS == NNS) {
4984 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4985 } else {
4986 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4987 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004988 DependentTemplateName *CheckQTN =
4989 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4990 assert(!CheckQTN && "Dependent type name canonicalization broken");
4991 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004992 }
4993
4994 DependentTemplateNames.InsertNode(QTN, InsertPos);
4995 return TemplateName(QTN);
4996}
4997
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004998/// \brief Retrieve the template name that represents a dependent
4999/// template name such as \c MetaFun::template operator+.
5000TemplateName
5001ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00005002 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005003 assert((!NNS || NNS->isDependent()) &&
5004 "Nested name specifier must be dependent");
5005
5006 llvm::FoldingSetNodeID ID;
5007 DependentTemplateName::Profile(ID, NNS, Operator);
5008
5009 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00005010 DependentTemplateName *QTN
5011 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005012
5013 if (QTN)
5014 return TemplateName(QTN);
5015
5016 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5017 if (CanonNNS == NNS) {
5018 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5019 } else {
5020 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5021 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00005022
5023 DependentTemplateName *CheckQTN
5024 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5025 assert(!CheckQTN && "Dependent template name canonicalization broken");
5026 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00005027 }
5028
5029 DependentTemplateNames.InsertNode(QTN, InsertPos);
5030 return TemplateName(QTN);
5031}
5032
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005033TemplateName
John McCall14606042011-06-30 08:33:18 +00005034ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5035 TemplateName replacement) const {
5036 llvm::FoldingSetNodeID ID;
5037 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5038
5039 void *insertPos = 0;
5040 SubstTemplateTemplateParmStorage *subst
5041 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5042
5043 if (!subst) {
5044 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5045 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5046 }
5047
5048 return TemplateName(subst);
5049}
5050
5051TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005052ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5053 const TemplateArgument &ArgPack) const {
5054 ASTContext &Self = const_cast<ASTContext &>(*this);
5055 llvm::FoldingSetNodeID ID;
5056 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5057
5058 void *InsertPos = 0;
5059 SubstTemplateTemplateParmPackStorage *Subst
5060 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5061
5062 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00005063 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00005064 ArgPack.pack_size(),
5065 ArgPack.pack_begin());
5066 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5067 }
5068
5069 return TemplateName(Subst);
5070}
5071
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005072/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00005073/// TargetInfo, produce the corresponding type. The unsigned @p Type
5074/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00005075CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005076 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00005077 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005078 case TargetInfo::SignedShort: return ShortTy;
5079 case TargetInfo::UnsignedShort: return UnsignedShortTy;
5080 case TargetInfo::SignedInt: return IntTy;
5081 case TargetInfo::UnsignedInt: return UnsignedIntTy;
5082 case TargetInfo::SignedLong: return LongTy;
5083 case TargetInfo::UnsignedLong: return UnsignedLongTy;
5084 case TargetInfo::SignedLongLong: return LongLongTy;
5085 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5086 }
5087
David Blaikieb219cfc2011-09-23 05:06:16 +00005088 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregorb4e66d52008-11-03 14:12:49 +00005089}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00005090
5091//===----------------------------------------------------------------------===//
5092// Type Predicates.
5093//===----------------------------------------------------------------------===//
5094
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005095/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5096/// garbage collection attribute.
5097///
John McCallae278a32011-01-12 00:34:59 +00005098Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
Douglas Gregore289d812011-09-13 17:21:33 +00005099 if (getLangOptions().getGC() == LangOptions::NonGC)
John McCallae278a32011-01-12 00:34:59 +00005100 return Qualifiers::GCNone;
5101
5102 assert(getLangOptions().ObjC1);
5103 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5104
5105 // Default behaviour under objective-C's gc is for ObjC pointers
5106 // (or pointers to them) be treated as though they were declared
5107 // as __strong.
5108 if (GCAttrs == Qualifiers::GCNone) {
5109 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5110 return Qualifiers::Strong;
5111 else if (Ty->isPointerType())
5112 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5113 } else {
5114 // It's not valid to set GC attributes on anything that isn't a
5115 // pointer.
5116#ifndef NDEBUG
5117 QualType CT = Ty->getCanonicalTypeInternal();
5118 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5119 CT = AT->getElementType();
5120 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5121#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005122 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00005123 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00005124}
5125
Chris Lattner6ac46a42008-04-07 06:51:04 +00005126//===----------------------------------------------------------------------===//
5127// Type Compatibility Testing
5128//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00005129
Mike Stump1eb44332009-09-09 15:08:12 +00005130/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005131/// compatible.
5132static bool areCompatVectorTypes(const VectorType *LHS,
5133 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00005134 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00005135 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00005136 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00005137}
5138
Douglas Gregor255210e2010-08-06 10:14:59 +00005139bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5140 QualType SecondVec) {
5141 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5142 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5143
5144 if (hasSameUnqualifiedType(FirstVec, SecondVec))
5145 return true;
5146
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005147 // Treat Neon vector types and most AltiVec vector types as if they are the
5148 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00005149 const VectorType *First = FirstVec->getAs<VectorType>();
5150 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005151 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00005152 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00005153 First->getVectorKind() != VectorType::AltiVecPixel &&
5154 First->getVectorKind() != VectorType::AltiVecBool &&
5155 Second->getVectorKind() != VectorType::AltiVecPixel &&
5156 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00005157 return true;
5158
5159 return false;
5160}
5161
Steve Naroff4084c302009-07-23 01:01:38 +00005162//===----------------------------------------------------------------------===//
5163// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5164//===----------------------------------------------------------------------===//
5165
5166/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5167/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00005168bool
5169ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5170 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00005171 if (lProto == rProto)
5172 return true;
5173 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5174 E = rProto->protocol_end(); PI != E; ++PI)
5175 if (ProtocolCompatibleWithProtocol(lProto, *PI))
5176 return true;
5177 return false;
5178}
5179
Steve Naroff4084c302009-07-23 01:01:38 +00005180/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5181/// return true if lhs's protocols conform to rhs's protocol; false
5182/// otherwise.
5183bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5184 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5185 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5186 return false;
5187}
5188
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005189/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
5190/// Class<p1, ...>.
5191bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5192 QualType rhs) {
5193 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5194 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5195 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5196
5197 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5198 E = lhsQID->qual_end(); I != E; ++I) {
5199 bool match = false;
5200 ObjCProtocolDecl *lhsProto = *I;
5201 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5202 E = rhsOPT->qual_end(); J != E; ++J) {
5203 ObjCProtocolDecl *rhsProto = *J;
5204 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5205 match = true;
5206 break;
5207 }
5208 }
5209 if (!match)
5210 return false;
5211 }
5212 return true;
5213}
5214
Steve Naroff4084c302009-07-23 01:01:38 +00005215/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5216/// ObjCQualifiedIDType.
5217bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5218 bool compare) {
5219 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00005220 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005221 lhs->isObjCIdType() || lhs->isObjCClassType())
5222 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005223 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00005224 rhs->isObjCIdType() || rhs->isObjCClassType())
5225 return true;
5226
5227 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00005228 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005229
Steve Naroff4084c302009-07-23 01:01:38 +00005230 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005231
Steve Naroff4084c302009-07-23 01:01:38 +00005232 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005233 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00005234 // make sure we check the class hierarchy.
5235 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5236 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5237 E = lhsQID->qual_end(); I != E; ++I) {
5238 // when comparing an id<P> on lhs with a static type on rhs,
5239 // see if static class implements all of id's protocols, directly or
5240 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005241 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00005242 return false;
5243 }
5244 }
5245 // If there are no qualifiers and no interface, we have an 'id'.
5246 return true;
5247 }
Mike Stump1eb44332009-09-09 15:08:12 +00005248 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005249 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5250 E = lhsQID->qual_end(); I != E; ++I) {
5251 ObjCProtocolDecl *lhsProto = *I;
5252 bool match = false;
5253
5254 // when comparing an id<P> on lhs with a static type on rhs,
5255 // see if static class implements all of id's protocols, directly or
5256 // through its super class and categories.
5257 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5258 E = rhsOPT->qual_end(); J != E; ++J) {
5259 ObjCProtocolDecl *rhsProto = *J;
5260 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5261 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5262 match = true;
5263 break;
5264 }
5265 }
Mike Stump1eb44332009-09-09 15:08:12 +00005266 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005267 // make sure we check the class hierarchy.
5268 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5269 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5270 E = lhsQID->qual_end(); I != E; ++I) {
5271 // when comparing an id<P> on lhs with a static type on rhs,
5272 // see if static class implements all of id's protocols, directly or
5273 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005274 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005275 match = true;
5276 break;
5277 }
5278 }
5279 }
5280 if (!match)
5281 return false;
5282 }
Mike Stump1eb44332009-09-09 15:08:12 +00005283
Steve Naroff4084c302009-07-23 01:01:38 +00005284 return true;
5285 }
Mike Stump1eb44332009-09-09 15:08:12 +00005286
Steve Naroff4084c302009-07-23 01:01:38 +00005287 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5288 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5289
Mike Stump1eb44332009-09-09 15:08:12 +00005290 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005291 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005292 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005293 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5294 E = lhsOPT->qual_end(); I != E; ++I) {
5295 ObjCProtocolDecl *lhsProto = *I;
5296 bool match = false;
5297
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005298 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005299 // see if static class implements all of id's protocols, directly or
5300 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005301 // First, lhs protocols in the qualifier list must be found, direct
5302 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005303 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5304 E = rhsQID->qual_end(); J != E; ++J) {
5305 ObjCProtocolDecl *rhsProto = *J;
5306 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5307 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5308 match = true;
5309 break;
5310 }
5311 }
5312 if (!match)
5313 return false;
5314 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005315
5316 // Static class's protocols, or its super class or category protocols
5317 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5318 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5319 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5320 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5321 // This is rather dubious but matches gcc's behavior. If lhs has
5322 // no type qualifier and its class has no static protocol(s)
5323 // assume that it is mismatch.
5324 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5325 return false;
5326 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5327 LHSInheritedProtocols.begin(),
5328 E = LHSInheritedProtocols.end(); I != E; ++I) {
5329 bool match = false;
5330 ObjCProtocolDecl *lhsProto = (*I);
5331 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5332 E = rhsQID->qual_end(); J != E; ++J) {
5333 ObjCProtocolDecl *rhsProto = *J;
5334 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5335 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5336 match = true;
5337 break;
5338 }
5339 }
5340 if (!match)
5341 return false;
5342 }
5343 }
Steve Naroff4084c302009-07-23 01:01:38 +00005344 return true;
5345 }
5346 return false;
5347}
5348
Eli Friedman3d815e72008-08-22 00:56:42 +00005349/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005350/// compatible for assignment from RHS to LHS. This handles validation of any
5351/// protocol qualifiers on the LHS or RHS.
5352///
Steve Naroff14108da2009-07-10 23:34:53 +00005353bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5354 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005355 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5356 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5357
Steve Naroffde2e22d2009-07-15 18:40:39 +00005358 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005359 if (LHS->isObjCUnqualifiedIdOrClass() ||
5360 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005361 return true;
5362
John McCallc12c5bb2010-05-15 11:32:37 +00005363 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005364 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5365 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005366 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005367
5368 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5369 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5370 QualType(RHSOPT,0));
5371
John McCallc12c5bb2010-05-15 11:32:37 +00005372 // If we have 2 user-defined types, fall into that path.
5373 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005374 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005375
Steve Naroff4084c302009-07-23 01:01:38 +00005376 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005377}
5378
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005379/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005380/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005381/// arguments in block literals. When passed as arguments, passing 'A*' where
5382/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5383/// not OK. For the return type, the opposite is not OK.
5384bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5385 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005386 const ObjCObjectPointerType *RHSOPT,
5387 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005388 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005389 return true;
5390
5391 if (LHSOPT->isObjCBuiltinType()) {
5392 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5393 }
5394
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005395 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005396 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5397 QualType(RHSOPT,0),
5398 false);
5399
5400 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5401 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5402 if (LHS && RHS) { // We have 2 user-defined types.
5403 if (LHS != RHS) {
5404 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005405 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005406 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005407 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005408 }
5409 else
5410 return true;
5411 }
5412 return false;
5413}
5414
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005415/// getIntersectionOfProtocols - This routine finds the intersection of set
5416/// of protocols inherited from two distinct objective-c pointer objects.
5417/// It is used to build composite qualifier list of the composite type of
5418/// the conditional expression involving two objective-c pointer objects.
5419static
5420void getIntersectionOfProtocols(ASTContext &Context,
5421 const ObjCObjectPointerType *LHSOPT,
5422 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005423 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005424
John McCallc12c5bb2010-05-15 11:32:37 +00005425 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5426 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5427 assert(LHS->getInterface() && "LHS must have an interface base");
5428 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005429
5430 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5431 unsigned LHSNumProtocols = LHS->getNumProtocols();
5432 if (LHSNumProtocols > 0)
5433 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5434 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005435 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005436 Context.CollectInheritedProtocols(LHS->getInterface(),
5437 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005438 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5439 LHSInheritedProtocols.end());
5440 }
5441
5442 unsigned RHSNumProtocols = RHS->getNumProtocols();
5443 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005444 ObjCProtocolDecl **RHSProtocols =
5445 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005446 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5447 if (InheritedProtocolSet.count(RHSProtocols[i]))
5448 IntersectionOfProtocols.push_back(RHSProtocols[i]);
Chad Rosier30601782011-08-17 23:08:45 +00005449 } else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005450 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005451 Context.CollectInheritedProtocols(RHS->getInterface(),
5452 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005453 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5454 RHSInheritedProtocols.begin(),
5455 E = RHSInheritedProtocols.end(); I != E; ++I)
5456 if (InheritedProtocolSet.count((*I)))
5457 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005458 }
5459}
5460
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005461/// areCommonBaseCompatible - Returns common base class of the two classes if
5462/// one found. Note that this is O'2 algorithm. But it will be called as the
5463/// last type comparison in a ?-exp of ObjC pointer types before a
5464/// warning is issued. So, its invokation is extremely rare.
5465QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005466 const ObjCObjectPointerType *Lptr,
5467 const ObjCObjectPointerType *Rptr) {
5468 const ObjCObjectType *LHS = Lptr->getObjectType();
5469 const ObjCObjectType *RHS = Rptr->getObjectType();
5470 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5471 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005472 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005473 return QualType();
5474
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005475 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005476 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005477 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005478 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005479 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5480
5481 QualType Result = QualType(LHS, 0);
5482 if (!Protocols.empty())
5483 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5484 Result = getObjCObjectPointerType(Result);
5485 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005486 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005487 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005488
5489 return QualType();
5490}
5491
John McCallc12c5bb2010-05-15 11:32:37 +00005492bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5493 const ObjCObjectType *RHS) {
5494 assert(LHS->getInterface() && "LHS is not an interface type");
5495 assert(RHS->getInterface() && "RHS is not an interface type");
5496
Chris Lattner6ac46a42008-04-07 06:51:04 +00005497 // Verify that the base decls are compatible: the RHS must be a subclass of
5498 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005499 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005500 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005501
Chris Lattner6ac46a42008-04-07 06:51:04 +00005502 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5503 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005504 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005505 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005506
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005507 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5508 // more detailed analysis is required.
5509 if (RHS->getNumProtocols() == 0) {
5510 // OK, if LHS is a superclass of RHS *and*
5511 // this superclass is assignment compatible with LHS.
5512 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005513 bool IsSuperClass =
5514 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5515 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005516 // OK if conversion of LHS to SuperClass results in narrowing of types
5517 // ; i.e., SuperClass may implement at least one of the protocols
5518 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5519 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5520 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005521 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005522 // If super class has no protocols, it is not a match.
5523 if (SuperClassInheritedProtocols.empty())
5524 return false;
5525
5526 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5527 LHSPE = LHS->qual_end();
5528 LHSPI != LHSPE; LHSPI++) {
5529 bool SuperImplementsProtocol = false;
5530 ObjCProtocolDecl *LHSProto = (*LHSPI);
5531
5532 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5533 SuperClassInheritedProtocols.begin(),
5534 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5535 ObjCProtocolDecl *SuperClassProto = (*I);
5536 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5537 SuperImplementsProtocol = true;
5538 break;
5539 }
5540 }
5541 if (!SuperImplementsProtocol)
5542 return false;
5543 }
5544 return true;
5545 }
5546 return false;
5547 }
Mike Stump1eb44332009-09-09 15:08:12 +00005548
John McCallc12c5bb2010-05-15 11:32:37 +00005549 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5550 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005551 LHSPI != LHSPE; LHSPI++) {
5552 bool RHSImplementsProtocol = false;
5553
5554 // If the RHS doesn't implement the protocol on the left, the types
5555 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005556 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5557 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005558 RHSPI != RHSPE; RHSPI++) {
5559 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005560 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005561 break;
5562 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005563 }
5564 // FIXME: For better diagnostics, consider passing back the protocol name.
5565 if (!RHSImplementsProtocol)
5566 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005567 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005568 // The RHS implements all protocols listed on the LHS.
5569 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005570}
5571
Steve Naroff389bf462009-02-12 17:52:19 +00005572bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5573 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005574 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5575 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005576
Steve Naroff14108da2009-07-10 23:34:53 +00005577 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005578 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005579
5580 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5581 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005582}
5583
Douglas Gregor569c3162010-08-07 11:51:51 +00005584bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5585 return canAssignObjCInterfaces(
5586 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5587 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5588}
5589
Mike Stump1eb44332009-09-09 15:08:12 +00005590/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005591/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005592/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005593/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005594bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5595 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005596 if (getLangOptions().CPlusPlus)
5597 return hasSameType(LHS, RHS);
5598
Douglas Gregor447234d2010-07-29 15:18:02 +00005599 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005600}
5601
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005602bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005603 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005604}
5605
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005606bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5607 return !mergeTypes(LHS, RHS, true).isNull();
5608}
5609
Peter Collingbourne48466752010-10-24 18:30:18 +00005610/// mergeTransparentUnionType - if T is a transparent union type and a member
5611/// of T is compatible with SubType, return the merged type, else return
5612/// QualType()
5613QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5614 bool OfBlockPointer,
5615 bool Unqualified) {
5616 if (const RecordType *UT = T->getAsUnionType()) {
5617 RecordDecl *UD = UT->getDecl();
5618 if (UD->hasAttr<TransparentUnionAttr>()) {
5619 for (RecordDecl::field_iterator it = UD->field_begin(),
5620 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005621 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005622 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5623 if (!MT.isNull())
5624 return MT;
5625 }
5626 }
5627 }
5628
5629 return QualType();
5630}
5631
5632/// mergeFunctionArgumentTypes - merge two types which appear as function
5633/// argument types
5634QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5635 bool OfBlockPointer,
5636 bool Unqualified) {
5637 // GNU extension: two types are compatible if they appear as a function
5638 // argument, one of the types is a transparent union type and the other
5639 // type is compatible with a union member
5640 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5641 Unqualified);
5642 if (!lmerge.isNull())
5643 return lmerge;
5644
5645 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5646 Unqualified);
5647 if (!rmerge.isNull())
5648 return rmerge;
5649
5650 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5651}
5652
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005653QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005654 bool OfBlockPointer,
5655 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005656 const FunctionType *lbase = lhs->getAs<FunctionType>();
5657 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005658 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5659 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005660 bool allLTypes = true;
5661 bool allRTypes = true;
5662
5663 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005664 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005665 if (OfBlockPointer) {
5666 QualType RHS = rbase->getResultType();
5667 QualType LHS = lbase->getResultType();
5668 bool UnqualifiedResult = Unqualified;
5669 if (!UnqualifiedResult)
5670 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005671 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005672 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005673 else
John McCall8cc246c2010-12-15 01:06:38 +00005674 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5675 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005676 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005677
5678 if (Unqualified)
5679 retType = retType.getUnqualifiedType();
5680
5681 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5682 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5683 if (Unqualified) {
5684 LRetType = LRetType.getUnqualifiedType();
5685 RRetType = RRetType.getUnqualifiedType();
5686 }
5687
5688 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005689 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005690 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005691 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005692
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005693 // FIXME: double check this
5694 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5695 // rbase->getRegParmAttr() != 0 &&
5696 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005697 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5698 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005699
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005700 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005701 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005702 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005703
John McCall8cc246c2010-12-15 01:06:38 +00005704 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005705 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5706 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005707 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5708 return QualType();
5709
John McCallf85e1932011-06-15 23:02:42 +00005710 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5711 return QualType();
5712
Fariborz Jahanian53c81672011-10-05 00:05:34 +00005713 // functypes which return are preferred over those that do not.
5714 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5715 allLTypes = false;
5716 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5717 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005718 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5719 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8cc246c2010-12-15 01:06:38 +00005720
John McCallf85e1932011-06-15 23:02:42 +00005721 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005722
Eli Friedman3d815e72008-08-22 00:56:42 +00005723 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005724 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5725 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005726 unsigned lproto_nargs = lproto->getNumArgs();
5727 unsigned rproto_nargs = rproto->getNumArgs();
5728
5729 // Compatible functions must have the same number of arguments
5730 if (lproto_nargs != rproto_nargs)
5731 return QualType();
5732
5733 // Variadic and non-variadic functions aren't compatible
5734 if (lproto->isVariadic() != rproto->isVariadic())
5735 return QualType();
5736
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005737 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5738 return QualType();
5739
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005740 if (LangOpts.ObjCAutoRefCount &&
5741 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5742 return QualType();
5743
Eli Friedman3d815e72008-08-22 00:56:42 +00005744 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005745 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005746 for (unsigned i = 0; i < lproto_nargs; i++) {
5747 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5748 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005749 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5750 OfBlockPointer,
5751 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005752 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005753
5754 if (Unqualified)
5755 argtype = argtype.getUnqualifiedType();
5756
Eli Friedman3d815e72008-08-22 00:56:42 +00005757 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005758 if (Unqualified) {
5759 largtype = largtype.getUnqualifiedType();
5760 rargtype = rargtype.getUnqualifiedType();
5761 }
5762
Chris Lattner61710852008-10-05 17:34:18 +00005763 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5764 allLTypes = false;
5765 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5766 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005767 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00005768
Eli Friedman3d815e72008-08-22 00:56:42 +00005769 if (allLTypes) return lhs;
5770 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005771
5772 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5773 EPI.ExtInfo = einfo;
5774 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005775 }
5776
5777 if (lproto) allRTypes = false;
5778 if (rproto) allLTypes = false;
5779
Douglas Gregor72564e72009-02-26 23:50:07 +00005780 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005781 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005782 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005783 if (proto->isVariadic()) return QualType();
5784 // Check that the types are compatible with the types that
5785 // would result from default argument promotions (C99 6.7.5.3p15).
5786 // The only types actually affected are promotable integer
5787 // types and floats, which would be passed as a different
5788 // type depending on whether the prototype is visible.
5789 unsigned proto_nargs = proto->getNumArgs();
5790 for (unsigned i = 0; i < proto_nargs; ++i) {
5791 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005792
5793 // Look at the promotion type of enum types, since that is the type used
5794 // to pass enum values.
5795 if (const EnumType *Enum = argTy->getAs<EnumType>())
5796 argTy = Enum->getDecl()->getPromotionType();
5797
Eli Friedman3d815e72008-08-22 00:56:42 +00005798 if (argTy->isPromotableIntegerType() ||
5799 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5800 return QualType();
5801 }
5802
5803 if (allLTypes) return lhs;
5804 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005805
5806 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5807 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005808 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005809 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005810 }
5811
5812 if (allLTypes) return lhs;
5813 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005814 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005815}
5816
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005817QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005818 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005819 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005820 // C++ [expr]: If an expression initially has the type "reference to T", the
5821 // type is adjusted to "T" prior to any further analysis, the expression
5822 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005823 // expression is an lvalue unless the reference is an rvalue reference and
5824 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005825 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5826 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005827
5828 if (Unqualified) {
5829 LHS = LHS.getUnqualifiedType();
5830 RHS = RHS.getUnqualifiedType();
5831 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005832
Eli Friedman3d815e72008-08-22 00:56:42 +00005833 QualType LHSCan = getCanonicalType(LHS),
5834 RHSCan = getCanonicalType(RHS);
5835
5836 // If two types are identical, they are compatible.
5837 if (LHSCan == RHSCan)
5838 return LHS;
5839
John McCall0953e762009-09-24 19:53:00 +00005840 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005841 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5842 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005843 if (LQuals != RQuals) {
5844 // If any of these qualifiers are different, we have a type
5845 // mismatch.
5846 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005847 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5848 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005849 return QualType();
5850
5851 // Exactly one GC qualifier difference is allowed: __strong is
5852 // okay if the other type has no GC qualifier but is an Objective
5853 // C object pointer (i.e. implicitly strong by default). We fix
5854 // this by pretending that the unqualified type was actually
5855 // qualified __strong.
5856 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5857 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5858 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5859
5860 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5861 return QualType();
5862
5863 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5864 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5865 }
5866 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5867 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5868 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005869 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005870 }
5871
5872 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005873
Eli Friedman852d63b2009-06-01 01:22:52 +00005874 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5875 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005876
Chris Lattner1adb8832008-01-14 05:45:46 +00005877 // We want to consider the two function types to be the same for these
5878 // comparisons, just force one to the other.
5879 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5880 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005881
5882 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005883 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5884 LHSClass = Type::ConstantArray;
5885 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5886 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005887
John McCallc12c5bb2010-05-15 11:32:37 +00005888 // ObjCInterfaces are just specialized ObjCObjects.
5889 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5890 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5891
Nate Begeman213541a2008-04-18 23:10:10 +00005892 // Canonicalize ExtVector -> Vector.
5893 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5894 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005895
Chris Lattnera36a61f2008-04-07 05:43:21 +00005896 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005897 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005898 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005899 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005900 // Compatibility is based on the underlying type, not the promotion
5901 // type.
John McCall183700f2009-09-21 23:43:11 +00005902 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005903 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5904 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005905 }
John McCall183700f2009-09-21 23:43:11 +00005906 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005907 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5908 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005909 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005910
Eli Friedman3d815e72008-08-22 00:56:42 +00005911 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005912 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005913
Steve Naroff4a746782008-01-09 22:43:08 +00005914 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005915 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005916#define TYPE(Class, Base)
5917#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005918#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005919#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5920#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5921#include "clang/AST/TypeNodes.def"
David Blaikieb219cfc2011-09-23 05:06:16 +00005922 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregor72564e72009-02-26 23:50:07 +00005923
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005924 case Type::LValueReference:
5925 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005926 case Type::MemberPointer:
David Blaikieb219cfc2011-09-23 05:06:16 +00005927 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregor72564e72009-02-26 23:50:07 +00005928
John McCallc12c5bb2010-05-15 11:32:37 +00005929 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005930 case Type::IncompleteArray:
5931 case Type::VariableArray:
5932 case Type::FunctionProto:
5933 case Type::ExtVector:
David Blaikieb219cfc2011-09-23 05:06:16 +00005934 llvm_unreachable("Types are eliminated above");
Douglas Gregor72564e72009-02-26 23:50:07 +00005935
Chris Lattner1adb8832008-01-14 05:45:46 +00005936 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005937 {
5938 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005939 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5940 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005941 if (Unqualified) {
5942 LHSPointee = LHSPointee.getUnqualifiedType();
5943 RHSPointee = RHSPointee.getUnqualifiedType();
5944 }
5945 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5946 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005947 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005948 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005949 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005950 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005951 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005952 return getPointerType(ResultType);
5953 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005954 case Type::BlockPointer:
5955 {
5956 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005957 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5958 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005959 if (Unqualified) {
5960 LHSPointee = LHSPointee.getUnqualifiedType();
5961 RHSPointee = RHSPointee.getUnqualifiedType();
5962 }
5963 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5964 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005965 if (ResultType.isNull()) return QualType();
5966 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5967 return LHS;
5968 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5969 return RHS;
5970 return getBlockPointerType(ResultType);
5971 }
Eli Friedmanb001de72011-10-06 23:00:33 +00005972 case Type::Atomic:
5973 {
5974 // Merge two pointer types, while trying to preserve typedef info
5975 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5976 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5977 if (Unqualified) {
5978 LHSValue = LHSValue.getUnqualifiedType();
5979 RHSValue = RHSValue.getUnqualifiedType();
5980 }
5981 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
5982 Unqualified);
5983 if (ResultType.isNull()) return QualType();
5984 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
5985 return LHS;
5986 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
5987 return RHS;
5988 return getAtomicType(ResultType);
5989 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005990 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005991 {
5992 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5993 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5994 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5995 return QualType();
5996
5997 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5998 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005999 if (Unqualified) {
6000 LHSElem = LHSElem.getUnqualifiedType();
6001 RHSElem = RHSElem.getUnqualifiedType();
6002 }
6003
6004 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00006005 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00006006 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6007 return LHS;
6008 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6009 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00006010 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6011 ArrayType::ArraySizeModifier(), 0);
6012 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6013 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006014 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6015 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00006016 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6017 return LHS;
6018 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6019 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00006020 if (LVAT) {
6021 // FIXME: This isn't correct! But tricky to implement because
6022 // the array's size has to be the size of LHS, but the type
6023 // has to be different.
6024 return LHS;
6025 }
6026 if (RVAT) {
6027 // FIXME: This isn't correct! But tricky to implement because
6028 // the array's size has to be the size of RHS, but the type
6029 // has to be different.
6030 return RHS;
6031 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00006032 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6033 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00006034 return getIncompleteArrayType(ResultType,
6035 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00006036 }
Chris Lattner1adb8832008-01-14 05:45:46 +00006037 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00006038 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00006039 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00006040 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00006041 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00006042 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006043 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00006044 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00006045 case Type::Complex:
6046 // Distinct complex types are incompatible.
6047 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00006048 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006049 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00006050 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6051 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00006052 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00006053 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00006054 case Type::ObjCObject: {
6055 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00006056 // FIXME: This should be type compatibility, e.g. whether
6057 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00006058 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6059 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6060 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00006061 return LHS;
6062
Eli Friedman3d815e72008-08-22 00:56:42 +00006063 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00006064 }
Steve Naroff14108da2009-07-10 23:34:53 +00006065 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006066 if (OfBlockPointer) {
6067 if (canAssignObjCInterfacesInBlockPointer(
6068 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00006069 RHS->getAs<ObjCObjectPointerType>(),
6070 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006071 return LHS;
6072 return QualType();
6073 }
John McCall183700f2009-09-21 23:43:11 +00006074 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6075 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00006076 return LHS;
6077
Steve Naroffbc76dd02008-12-10 22:14:21 +00006078 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00006079 }
Steve Naroffec0550f2007-10-15 20:41:53 +00006080 }
Douglas Gregor72564e72009-02-26 23:50:07 +00006081
6082 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00006083}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00006084
Fariborz Jahanian78213e42011-09-28 21:52:05 +00006085bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6086 const FunctionProtoType *FromFunctionType,
6087 const FunctionProtoType *ToFunctionType) {
6088 if (FromFunctionType->hasAnyConsumedArgs() !=
6089 ToFunctionType->hasAnyConsumedArgs())
6090 return false;
6091 FunctionProtoType::ExtProtoInfo FromEPI =
6092 FromFunctionType->getExtProtoInfo();
6093 FunctionProtoType::ExtProtoInfo ToEPI =
6094 ToFunctionType->getExtProtoInfo();
6095 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6096 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6097 ArgIdx != NumArgs; ++ArgIdx) {
6098 if (FromEPI.ConsumedArguments[ArgIdx] !=
6099 ToEPI.ConsumedArguments[ArgIdx])
6100 return false;
6101 }
6102 return true;
6103}
6104
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006105/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6106/// 'RHS' attributes and returns the merged version; including for function
6107/// return types.
6108QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6109 QualType LHSCan = getCanonicalType(LHS),
6110 RHSCan = getCanonicalType(RHS);
6111 // If two types are identical, they are compatible.
6112 if (LHSCan == RHSCan)
6113 return LHS;
6114 if (RHSCan->isFunctionType()) {
6115 if (!LHSCan->isFunctionType())
6116 return QualType();
6117 QualType OldReturnType =
6118 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6119 QualType NewReturnType =
6120 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6121 QualType ResReturnType =
6122 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6123 if (ResReturnType.isNull())
6124 return QualType();
6125 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6126 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6127 // In either case, use OldReturnType to build the new function type.
6128 const FunctionType *F = LHS->getAs<FunctionType>();
6129 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00006130 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6131 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006132 QualType ResultType
6133 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00006134 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00006135 return ResultType;
6136 }
6137 }
6138 return QualType();
6139 }
6140
6141 // If the qualifiers are different, the types can still be merged.
6142 Qualifiers LQuals = LHSCan.getLocalQualifiers();
6143 Qualifiers RQuals = RHSCan.getLocalQualifiers();
6144 if (LQuals != RQuals) {
6145 // If any of these qualifiers are different, we have a type mismatch.
6146 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6147 LQuals.getAddressSpace() != RQuals.getAddressSpace())
6148 return QualType();
6149
6150 // Exactly one GC qualifier difference is allowed: __strong is
6151 // okay if the other type has no GC qualifier but is an Objective
6152 // C object pointer (i.e. implicitly strong by default). We fix
6153 // this by pretending that the unqualified type was actually
6154 // qualified __strong.
6155 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6156 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6157 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6158
6159 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6160 return QualType();
6161
6162 if (GC_L == Qualifiers::Strong)
6163 return LHS;
6164 if (GC_R == Qualifiers::Strong)
6165 return RHS;
6166 return QualType();
6167 }
6168
6169 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6170 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6171 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6172 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6173 if (ResQT == LHSBaseQT)
6174 return LHS;
6175 if (ResQT == RHSBaseQT)
6176 return RHS;
6177 }
6178 return QualType();
6179}
6180
Chris Lattner5426bf62008-04-07 07:01:58 +00006181//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00006182// Integer Predicates
6183//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00006184
Jay Foad4ba2a172011-01-12 09:06:06 +00006185unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00006186 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00006187 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00006188 if (T->isBooleanType())
6189 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00006190 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00006191 return (unsigned)getTypeSize(T);
6192}
6193
6194QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00006195 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00006196
6197 // Turn <4 x signed int> -> <4 x unsigned int>
6198 if (const VectorType *VTy = T->getAs<VectorType>())
6199 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00006200 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00006201
6202 // For enums, we return the unsigned version of the base type.
6203 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00006204 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00006205
6206 const BuiltinType *BTy = T->getAs<BuiltinType>();
6207 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006208 switch (BTy->getKind()) {
6209 case BuiltinType::Char_S:
6210 case BuiltinType::SChar:
6211 return UnsignedCharTy;
6212 case BuiltinType::Short:
6213 return UnsignedShortTy;
6214 case BuiltinType::Int:
6215 return UnsignedIntTy;
6216 case BuiltinType::Long:
6217 return UnsignedLongTy;
6218 case BuiltinType::LongLong:
6219 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00006220 case BuiltinType::Int128:
6221 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00006222 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006223 llvm_unreachable("Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00006224 }
6225}
6226
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00006227ASTMutationListener::~ASTMutationListener() { }
6228
Chris Lattner86df27b2009-06-14 00:45:47 +00006229
6230//===----------------------------------------------------------------------===//
6231// Builtin Type Computation
6232//===----------------------------------------------------------------------===//
6233
6234/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00006235/// pointer over the consumed characters. This returns the resultant type. If
6236/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6237/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
6238/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00006239///
6240/// RequiresICE is filled in on return to indicate whether the value is required
6241/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00006242static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00006243 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00006244 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00006245 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00006246 // Modifiers.
6247 int HowLong = 0;
6248 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00006249 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006250
Chris Lattner33daae62010-10-01 22:42:38 +00006251 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00006252 bool Done = false;
6253 while (!Done) {
6254 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00006255 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006256 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00006257 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00006258 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006259 case 'S':
6260 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6261 assert(!Signed && "Can't use 'S' modifier multiple times!");
6262 Signed = true;
6263 break;
6264 case 'U':
6265 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6266 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6267 Unsigned = true;
6268 break;
6269 case 'L':
6270 assert(HowLong <= 2 && "Can't have LLLL modifier");
6271 ++HowLong;
6272 break;
6273 }
6274 }
6275
6276 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00006277
Chris Lattner86df27b2009-06-14 00:45:47 +00006278 // Read the base type.
6279 switch (*Str++) {
David Blaikieb219cfc2011-09-23 05:06:16 +00006280 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattner86df27b2009-06-14 00:45:47 +00006281 case 'v':
6282 assert(HowLong == 0 && !Signed && !Unsigned &&
6283 "Bad modifiers used with 'v'!");
6284 Type = Context.VoidTy;
6285 break;
6286 case 'f':
6287 assert(HowLong == 0 && !Signed && !Unsigned &&
6288 "Bad modifiers used with 'f'!");
6289 Type = Context.FloatTy;
6290 break;
6291 case 'd':
6292 assert(HowLong < 2 && !Signed && !Unsigned &&
6293 "Bad modifiers used with 'd'!");
6294 if (HowLong)
6295 Type = Context.LongDoubleTy;
6296 else
6297 Type = Context.DoubleTy;
6298 break;
6299 case 's':
6300 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6301 if (Unsigned)
6302 Type = Context.UnsignedShortTy;
6303 else
6304 Type = Context.ShortTy;
6305 break;
6306 case 'i':
6307 if (HowLong == 3)
6308 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6309 else if (HowLong == 2)
6310 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6311 else if (HowLong == 1)
6312 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6313 else
6314 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6315 break;
6316 case 'c':
6317 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6318 if (Signed)
6319 Type = Context.SignedCharTy;
6320 else if (Unsigned)
6321 Type = Context.UnsignedCharTy;
6322 else
6323 Type = Context.CharTy;
6324 break;
6325 case 'b': // boolean
6326 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6327 Type = Context.BoolTy;
6328 break;
6329 case 'z': // size_t.
6330 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6331 Type = Context.getSizeType();
6332 break;
6333 case 'F':
6334 Type = Context.getCFConstantStringType();
6335 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006336 case 'G':
6337 Type = Context.getObjCIdType();
6338 break;
6339 case 'H':
6340 Type = Context.getObjCSelType();
6341 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006342 case 'a':
6343 Type = Context.getBuiltinVaListType();
6344 assert(!Type.isNull() && "builtin va list type not initialized!");
6345 break;
6346 case 'A':
6347 // This is a "reference" to a va_list; however, what exactly
6348 // this means depends on how va_list is defined. There are two
6349 // different kinds of va_list: ones passed by value, and ones
6350 // passed by reference. An example of a by-value va_list is
6351 // x86, where va_list is a char*. An example of by-ref va_list
6352 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6353 // we want this argument to be a char*&; for x86-64, we want
6354 // it to be a __va_list_tag*.
6355 Type = Context.getBuiltinVaListType();
6356 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006357 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006358 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006359 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006360 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006361 break;
6362 case 'V': {
6363 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006364 unsigned NumElements = strtoul(Str, &End, 10);
6365 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006366 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006367
Chris Lattner14e0e742010-10-01 22:53:11 +00006368 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6369 RequiresICE, false);
6370 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006371
6372 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006373 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006374 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006375 break;
6376 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006377 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006378 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6379 false);
6380 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006381 Type = Context.getComplexType(ElementType);
6382 break;
Fariborz Jahaniancc075e42011-08-23 23:33:09 +00006383 }
6384 case 'Y' : {
6385 Type = Context.getPointerDiffType();
6386 break;
6387 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006388 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006389 Type = Context.getFILEType();
6390 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006391 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006392 return QualType();
6393 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006394 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006395 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006396 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006397 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006398 else
6399 Type = Context.getjmp_bufType();
6400
Mike Stumpfd612db2009-07-28 23:47:15 +00006401 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006402 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006403 return QualType();
6404 }
6405 break;
Rafael Espindolae2d4f4e2011-11-13 21:51:09 +00006406 case 'K':
6407 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6408 Type = Context.getucontext_tType();
6409
6410 if (Type.isNull()) {
6411 Error = ASTContext::GE_Missing_ucontext;
6412 return QualType();
6413 }
6414 break;
Mike Stump782fa302009-07-28 02:25:19 +00006415 }
Mike Stump1eb44332009-09-09 15:08:12 +00006416
Chris Lattner33daae62010-10-01 22:42:38 +00006417 // If there are modifiers and if we're allowed to parse them, go for it.
6418 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006419 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006420 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006421 default: Done = true; --Str; break;
6422 case '*':
6423 case '&': {
6424 // Both pointers and references can have their pointee types
6425 // qualified with an address space.
6426 char *End;
6427 unsigned AddrSpace = strtoul(Str, &End, 10);
6428 if (End != Str && AddrSpace != 0) {
6429 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6430 Str = End;
6431 }
6432 if (c == '*')
6433 Type = Context.getPointerType(Type);
6434 else
6435 Type = Context.getLValueReferenceType(Type);
6436 break;
6437 }
6438 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6439 case 'C':
6440 Type = Type.withConst();
6441 break;
6442 case 'D':
6443 Type = Context.getVolatileType(Type);
6444 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006445 }
6446 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006447
Chris Lattner14e0e742010-10-01 22:53:11 +00006448 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006449 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006450
Chris Lattner86df27b2009-06-14 00:45:47 +00006451 return Type;
6452}
6453
6454/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006455QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006456 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006457 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006458 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006459
Chris Lattner5f9e2722011-07-23 10:55:15 +00006460 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006461
Chris Lattner14e0e742010-10-01 22:53:11 +00006462 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006463 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006464 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6465 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006466 if (Error != GE_None)
6467 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006468
6469 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6470
Chris Lattner86df27b2009-06-14 00:45:47 +00006471 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006472 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006473 if (Error != GE_None)
6474 return QualType();
6475
Chris Lattner14e0e742010-10-01 22:53:11 +00006476 // If this argument is required to be an IntegerConstantExpression and the
6477 // caller cares, fill in the bitmask we return.
6478 if (RequiresICE && IntegerConstantArgs)
6479 *IntegerConstantArgs |= 1 << ArgTypes.size();
6480
Chris Lattner86df27b2009-06-14 00:45:47 +00006481 // Do array -> pointer decay. The builtin should use the decayed type.
6482 if (Ty->isArrayType())
6483 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006484
Chris Lattner86df27b2009-06-14 00:45:47 +00006485 ArgTypes.push_back(Ty);
6486 }
6487
6488 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6489 "'.' should only occur at end of builtin type list!");
6490
John McCall00ccbef2010-12-21 00:44:39 +00006491 FunctionType::ExtInfo EI;
6492 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6493
6494 bool Variadic = (TypeStr[0] == '.');
6495
6496 // We really shouldn't be making a no-proto type here, especially in C++.
6497 if (ArgTypes.empty() && Variadic)
6498 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006499
John McCalle23cf432010-12-14 08:05:40 +00006500 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006501 EPI.ExtInfo = EI;
6502 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006503
6504 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006505}
Eli Friedmana95d7572009-08-19 07:44:53 +00006506
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006507GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6508 GVALinkage External = GVA_StrongExternal;
6509
6510 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006511 switch (L) {
6512 case NoLinkage:
6513 case InternalLinkage:
6514 case UniqueExternalLinkage:
6515 return GVA_Internal;
6516
6517 case ExternalLinkage:
6518 switch (FD->getTemplateSpecializationKind()) {
6519 case TSK_Undeclared:
6520 case TSK_ExplicitSpecialization:
6521 External = GVA_StrongExternal;
6522 break;
6523
6524 case TSK_ExplicitInstantiationDefinition:
6525 return GVA_ExplicitTemplateInstantiation;
6526
6527 case TSK_ExplicitInstantiationDeclaration:
6528 case TSK_ImplicitInstantiation:
6529 External = GVA_TemplateInstantiation;
6530 break;
6531 }
6532 }
6533
6534 if (!FD->isInlined())
6535 return External;
6536
6537 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6538 // GNU or C99 inline semantics. Determine whether this symbol should be
6539 // externally visible.
6540 if (FD->isInlineDefinitionExternallyVisible())
6541 return External;
6542
6543 // C99 inline semantics, where the symbol is not externally visible.
6544 return GVA_C99Inline;
6545 }
6546
6547 // C++0x [temp.explicit]p9:
6548 // [ Note: The intent is that an inline function that is the subject of
6549 // an explicit instantiation declaration will still be implicitly
6550 // instantiated when used so that the body can be considered for
6551 // inlining, but that no out-of-line copy of the inline function would be
6552 // generated in the translation unit. -- end note ]
6553 if (FD->getTemplateSpecializationKind()
6554 == TSK_ExplicitInstantiationDeclaration)
6555 return GVA_C99Inline;
6556
6557 return GVA_CXXInline;
6558}
6559
6560GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6561 // If this is a static data member, compute the kind of template
6562 // specialization. Otherwise, this variable is not part of a
6563 // template.
6564 TemplateSpecializationKind TSK = TSK_Undeclared;
6565 if (VD->isStaticDataMember())
6566 TSK = VD->getTemplateSpecializationKind();
6567
6568 Linkage L = VD->getLinkage();
6569 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6570 VD->getType()->getLinkage() == UniqueExternalLinkage)
6571 L = UniqueExternalLinkage;
6572
6573 switch (L) {
6574 case NoLinkage:
6575 case InternalLinkage:
6576 case UniqueExternalLinkage:
6577 return GVA_Internal;
6578
6579 case ExternalLinkage:
6580 switch (TSK) {
6581 case TSK_Undeclared:
6582 case TSK_ExplicitSpecialization:
6583 return GVA_StrongExternal;
6584
6585 case TSK_ExplicitInstantiationDeclaration:
6586 llvm_unreachable("Variable should not be instantiated");
6587 // Fall through to treat this like any other instantiation.
6588
6589 case TSK_ExplicitInstantiationDefinition:
6590 return GVA_ExplicitTemplateInstantiation;
6591
6592 case TSK_ImplicitInstantiation:
6593 return GVA_TemplateInstantiation;
6594 }
6595 }
6596
6597 return GVA_StrongExternal;
6598}
6599
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006600bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006601 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6602 if (!VD->isFileVarDecl())
6603 return false;
Argyrios Kyrtzidis144b38a2011-09-13 21:35:00 +00006604 } else if (!isa<FunctionDecl>(D))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006605 return false;
6606
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006607 // Weak references don't produce any output by themselves.
6608 if (D->hasAttr<WeakRefAttr>())
6609 return false;
6610
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006611 // Aliases and used decls are required.
6612 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6613 return true;
6614
6615 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6616 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006617 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006618 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006619
6620 // Constructors and destructors are required.
6621 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6622 return true;
6623
6624 // The key function for a class is required.
6625 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6626 const CXXRecordDecl *RD = MD->getParent();
6627 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6628 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6629 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6630 return true;
6631 }
6632 }
6633
6634 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6635
6636 // static, static inline, always_inline, and extern inline functions can
6637 // always be deferred. Normal inline functions can be deferred in C99/C++.
6638 // Implicit template instantiations can also be deferred in C++.
6639 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6640 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6641 return false;
6642 return true;
6643 }
Douglas Gregor94da1582011-09-10 00:22:34 +00006644
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006645 const VarDecl *VD = cast<VarDecl>(D);
6646 assert(VD->isFileVarDecl() && "Expected file scoped var");
6647
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006648 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6649 return false;
6650
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006651 // Structs that have non-trivial constructors or destructors are required.
6652
6653 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006654 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006655 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6656 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006657 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6658 RD->hasTrivialCopyConstructor() &&
6659 RD->hasTrivialMoveConstructor() &&
6660 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006661 return true;
6662 }
6663 }
6664
6665 GVALinkage L = GetGVALinkageForVariable(VD);
6666 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6667 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6668 return false;
6669 }
6670
6671 return true;
6672}
Charles Davis071cc7d2010-08-16 03:33:14 +00006673
Charles Davisee743f92010-11-09 18:04:24 +00006674CallingConv ASTContext::getDefaultMethodCallConv() {
6675 // Pass through to the C++ ABI object
6676 return ABI->getDefaultMethodCallConv();
6677}
6678
Jay Foad4ba2a172011-01-12 09:06:06 +00006679bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006680 // Pass through to the C++ ABI object
6681 return ABI->isNearlyEmpty(RD);
6682}
6683
Peter Collingbourne14110472011-01-13 18:57:25 +00006684MangleContext *ASTContext::createMangleContext() {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00006685 switch (Target->getCXXABI()) {
Peter Collingbourne14110472011-01-13 18:57:25 +00006686 case CXXABI_ARM:
6687 case CXXABI_Itanium:
6688 return createItaniumMangleContext(*this, getDiagnostics());
6689 case CXXABI_Microsoft:
6690 return createMicrosoftMangleContext(*this, getDiagnostics());
6691 }
David Blaikieb219cfc2011-09-23 05:06:16 +00006692 llvm_unreachable("Unsupported ABI");
Peter Collingbourne14110472011-01-13 18:57:25 +00006693}
6694
Charles Davis071cc7d2010-08-16 03:33:14 +00006695CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006696
6697size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006698 return ASTRecordLayouts.getMemorySize()
6699 + llvm::capacity_in_bytes(ObjCLayouts)
6700 + llvm::capacity_in_bytes(KeyFunctions)
6701 + llvm::capacity_in_bytes(ObjCImpls)
6702 + llvm::capacity_in_bytes(BlockVarCopyInits)
6703 + llvm::capacity_in_bytes(DeclAttrs)
6704 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6705 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6706 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6707 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6708 + llvm::capacity_in_bytes(OverriddenMethods)
6709 + llvm::capacity_in_bytes(Types)
Francois Pichetaf0f4d02011-08-14 03:52:19 +00006710 + llvm::capacity_in_bytes(VariableArrayTypes)
Francois Pichet0d95f0d2011-08-14 14:28:49 +00006711 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006712}
Ted Kremenekd211cb72011-10-06 05:00:56 +00006713
6714void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6715 ParamIndices[D] = index;
6716}
6717
6718unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6719 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6720 assert(I != ParamIndices.end() &&
6721 "ParmIndices lacks entry set by ParmVarDecl");
6722 return I->second;
6723}