blob: cf4535bd90ca46b7085d95bb0a6b1b5411b74f79 [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 {
53 FloatRank, DoubleRank, LongDoubleRank
54};
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
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000199static const LangAS::Map &getAddressSpaceMap(const TargetInfo &T,
200 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 };
209 return FakeAddrSpaceMap;
210 } else {
211 return T.getAddressSpaceMap();
212 }
213}
214
Chris Lattner61710852008-10-05 17:34:18 +0000215ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
Daniel Dunbar444be732009-11-13 05:51:54 +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 Gregor63fe86b2010-07-25 17:53:33 +0000219 unsigned size_reserve) :
Sebastian Redl8026f6d2011-03-13 17:09:40 +0000220 FunctionProtoTypes(this_()),
John McCallef990012010-06-11 11:07:21 +0000221 TemplateSpecializationTypes(this_()),
222 DependentTemplateSpecializationTypes(this_()),
John McCall14606042011-06-30 08:33:18 +0000223 SubstTemplateTemplateParmPacks(this_()),
Argyrios Kyrtzidis00611382010-07-04 21:44:19 +0000224 GlobalNestedNameSpecifier(0), IsInt128Installed(false),
Douglas Gregor4dfd02a2011-08-12 05:46:01 +0000225 ObjCIdDecl(0), CFConstantStringTypeDecl(0),
Douglas Gregor0815b572011-08-09 17:23:49 +0000226 FILEDecl(0),
John McCallf85e1932011-06-15 23:02:42 +0000227 jmp_bufDecl(0), sigjmp_bufDecl(0), BlockDescriptorType(0),
228 BlockDescriptorExtendedType(0), cudaConfigureCallDecl(0),
John McCallbf1a0282010-06-04 23:28:52 +0000229 NullTypeSourceInfo(QualType()),
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000230 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)),
231 AddrSpaceMap(getAddressSpaceMap(t, LOpts)), Target(t),
Douglas Gregor2e222532009-07-02 17:08:52 +0000232 Idents(idents), Selectors(sels),
Ted Kremenekac9590e2010-05-10 20:40:08 +0000233 BuiltinInfo(builtins),
234 DeclarationNames(*this),
Argyrios Kyrtzidis9a44b5f2010-10-28 09:29:35 +0000235 ExternalSource(0), Listener(0), PrintingPolicy(LOpts),
Ted Kremenekf057bf72010-06-18 00:31:04 +0000236 LastSDM(0, 0),
John McCall8178df32011-02-22 22:38:33 +0000237 UniqueBlockByRefTypeID(0) {
Mike Stump1eb44332009-09-09 15:08:12 +0000238 if (size_reserve > 0) Types.reserve(size_reserve);
Daniel Dunbare91593e2008-08-11 04:54:23 +0000239 TUDecl = TranslationUnitDecl::Create(*this);
Steve Naroff14108da2009-07-10 23:34:53 +0000240 InitBuiltinTypes();
Daniel Dunbare91593e2008-08-11 04:54:23 +0000241}
242
Reid Spencer5f016e22007-07-11 17:01:13 +0000243ASTContext::~ASTContext() {
Ted Kremenek3478eb62010-02-11 07:12:28 +0000244 // Release the DenseMaps associated with DeclContext objects.
245 // FIXME: Is this the ideal solution?
246 ReleaseDeclContextMaps();
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000247
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000248 // Call all of the deallocation functions.
249 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
250 Deallocations[I].first(Deallocations[I].second);
Douglas Gregor00545312010-05-23 18:26:36 +0000251
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000252 // Release all of the memory associated with overridden C++ methods.
253 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
254 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
255 OM != OMEnd; ++OM)
256 OM->second.Destroy();
Ted Kremenek3478eb62010-02-11 07:12:28 +0000257
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000258 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000259 // because they can contain DenseMaps.
260 for (llvm::DenseMap<const ObjCContainerDecl*,
261 const ASTRecordLayout*>::iterator
262 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
263 // Increment in loop to prevent using deallocated memory.
264 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
265 R->Destroy(*this);
266
Ted Kremenekdcfcfbe2010-06-08 23:00:58 +0000267 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
268 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
269 // Increment in loop to prevent using deallocated memory.
270 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
271 R->Destroy(*this);
272 }
Douglas Gregor63200642010-08-30 16:49:28 +0000273
274 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
275 AEnd = DeclAttrs.end();
276 A != AEnd; ++A)
277 A->second->~AttrVec();
278}
Douglas Gregorab452ba2009-03-26 23:50:42 +0000279
Douglas Gregor00545312010-05-23 18:26:36 +0000280void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
281 Deallocations.push_back(std::make_pair(Callback, Data));
282}
283
Mike Stump1eb44332009-09-09 15:08:12 +0000284void
Douglas Gregor2cf26342009-04-09 22:27:44 +0000285ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
286 ExternalSource.reset(Source.take());
287}
288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289void ASTContext::PrintStats() const {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000290 llvm::errs() << "\n*** AST Context Stats:\n";
291 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000292
Douglas Gregordbe833d2009-05-26 14:40:08 +0000293 unsigned counts[] = {
Mike Stump1eb44332009-09-09 15:08:12 +0000294#define TYPE(Name, Parent) 0,
Douglas Gregordbe833d2009-05-26 14:40:08 +0000295#define ABSTRACT_TYPE(Name, Parent)
296#include "clang/AST/TypeNodes.def"
297 0 // Extra
298 };
Douglas Gregorc2ee10d2009-04-07 17:20:56 +0000299
Reid Spencer5f016e22007-07-11 17:01:13 +0000300 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
301 Type *T = Types[i];
Douglas Gregordbe833d2009-05-26 14:40:08 +0000302 counts[(unsigned)T->getTypeClass()]++;
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 }
304
Douglas Gregordbe833d2009-05-26 14:40:08 +0000305 unsigned Idx = 0;
306 unsigned TotalBytes = 0;
307#define TYPE(Name, Parent) \
308 if (counts[Idx]) \
Chandler Carruthcd92a652011-07-04 05:32:14 +0000309 llvm::errs() << " " << counts[Idx] << " " << #Name \
310 << " types\n"; \
Douglas Gregordbe833d2009-05-26 14:40:08 +0000311 TotalBytes += counts[Idx] * sizeof(Name##Type); \
312 ++Idx;
313#define ABSTRACT_TYPE(Name, Parent)
314#include "clang/AST/TypeNodes.def"
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Chandler Carruthcd92a652011-07-04 05:32:14 +0000316 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
317
Douglas Gregor4923aa22010-07-02 20:37:36 +0000318 // Implicit special member functions.
Chandler Carruthcd92a652011-07-04 05:32:14 +0000319 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
320 << NumImplicitDefaultConstructors
321 << " implicit default constructors created\n";
322 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
323 << NumImplicitCopyConstructors
324 << " implicit copy constructors created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000325 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000326 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
327 << NumImplicitMoveConstructors
328 << " implicit move constructors created\n";
329 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
330 << NumImplicitCopyAssignmentOperators
331 << " implicit copy assignment operators created\n";
Sean Huntffe37fd2011-05-25 20:50:04 +0000332 if (getLangOptions().CPlusPlus)
Chandler Carruthcd92a652011-07-04 05:32:14 +0000333 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
334 << NumImplicitMoveAssignmentOperators
335 << " implicit move assignment operators created\n";
336 llvm::errs() << NumImplicitDestructorsDeclared << "/"
337 << NumImplicitDestructors
338 << " implicit destructors created\n";
339
Douglas Gregor2cf26342009-04-09 22:27:44 +0000340 if (ExternalSource.get()) {
Chandler Carruthcd92a652011-07-04 05:32:14 +0000341 llvm::errs() << "\n";
Douglas Gregor2cf26342009-04-09 22:27:44 +0000342 ExternalSource->PrintStats();
343 }
Chandler Carruthcd92a652011-07-04 05:32:14 +0000344
Douglas Gregor63fe86b2010-07-25 17:53:33 +0000345 BumpAlloc.PrintStats();
Reid Spencer5f016e22007-07-11 17:01:13 +0000346}
347
348
John McCalle27ec8a2009-10-23 23:03:21 +0000349void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall6b304a02009-09-24 23:30:46 +0000350 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCalle27ec8a2009-10-23 23:03:21 +0000351 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall6b304a02009-09-24 23:30:46 +0000352 Types.push_back(Ty);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353}
354
Reid Spencer5f016e22007-07-11 17:01:13 +0000355void ASTContext::InitBuiltinTypes() {
356 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 // C99 6.2.5p19.
359 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // C99 6.2.5p2.
362 InitBuiltinType(BoolTy, BuiltinType::Bool);
363 // C99 6.2.5p3.
Eli Friedman15b91762009-06-05 07:05:05 +0000364 if (LangOpts.CharIsSigned)
Reid Spencer5f016e22007-07-11 17:01:13 +0000365 InitBuiltinType(CharTy, BuiltinType::Char_S);
366 else
367 InitBuiltinType(CharTy, BuiltinType::Char_U);
368 // C99 6.2.5p4.
369 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
370 InitBuiltinType(ShortTy, BuiltinType::Short);
371 InitBuiltinType(IntTy, BuiltinType::Int);
372 InitBuiltinType(LongTy, BuiltinType::Long);
373 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // C99 6.2.5p6.
376 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
377 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
378 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
379 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
380 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 // C99 6.2.5p10.
383 InitBuiltinType(FloatTy, BuiltinType::Float);
384 InitBuiltinType(DoubleTy, BuiltinType::Double);
385 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000386
Chris Lattner2df9ced2009-04-30 02:43:43 +0000387 // GNU extension, 128-bit integers.
388 InitBuiltinType(Int128Ty, BuiltinType::Int128);
389 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
390
Chris Lattner3f59c972010-12-25 23:25:43 +0000391 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
Eli Friedmand3d77cd2011-04-30 19:24:24 +0000392 if (TargetInfo::isTypeSigned(Target.getWCharType()))
Chris Lattner3f59c972010-12-25 23:25:43 +0000393 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
394 else // -fshort-wchar makes wchar_t be unsigned.
395 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
396 } else // C99
Chris Lattner3a250322009-02-26 23:43:47 +0000397 WCharTy = getFromTargetType(Target.getWCharType());
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000398
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000399 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
400 InitBuiltinType(Char16Ty, BuiltinType::Char16);
401 else // C99
402 Char16Ty = getFromTargetType(Target.getChar16Type());
403
404 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
405 InitBuiltinType(Char32Ty, BuiltinType::Char32);
406 else // C99
407 Char32Ty = getFromTargetType(Target.getChar32Type());
408
Douglas Gregor898574e2008-12-05 23:32:09 +0000409 // Placeholder type for type-dependent expressions whose type is
410 // completely unknown. No code should ever check a type against
411 // DependentTy and users should never see it; however, it is here to
412 // help diagnose failures to properly check for type-dependent
413 // expressions.
414 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000415
John McCall2a984ca2010-10-12 00:20:44 +0000416 // Placeholder type for functions.
417 InitBuiltinType(OverloadTy, BuiltinType::Overload);
418
John McCall864c0412011-04-26 20:42:42 +0000419 // Placeholder type for bound members.
420 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
421
John McCall1de4d4e2011-04-07 08:22:57 +0000422 // "any" type; useful for debugger-like clients.
423 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
424
Reid Spencer5f016e22007-07-11 17:01:13 +0000425 // C99 6.2.5p11.
426 FloatComplexTy = getComplexType(FloatTy);
427 DoubleComplexTy = getComplexType(DoubleTy);
428 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000429
Steve Naroff7e219e42007-10-15 14:41:52 +0000430 BuiltinVaListType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Steve Naroffde2e22d2009-07-15 18:40:39 +0000432 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
Steve Naroffde2e22d2009-07-15 18:40:39 +0000433 ObjCClassTypedefType = QualType();
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000434 ObjCSelTypedefType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000436 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroffde2e22d2009-07-15 18:40:39 +0000437 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
438 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000439 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Steve Naroff14108da2009-07-10 23:34:53 +0000440
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000441 ObjCConstantStringType = QualType();
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000443 // void * type
444 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000445
446 // nullptr type (C++0x 2.14.7)
447 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000448}
449
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000450Diagnostic &ASTContext::getDiagnostics() const {
451 return SourceMgr.getDiagnostics();
452}
453
Douglas Gregor63200642010-08-30 16:49:28 +0000454AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
455 AttrVec *&Result = DeclAttrs[D];
456 if (!Result) {
457 void *Mem = Allocate(sizeof(AttrVec));
458 Result = new (Mem) AttrVec;
459 }
460
461 return *Result;
462}
463
464/// \brief Erase the attributes corresponding to the given declaration.
465void ASTContext::eraseDeclAttrs(const Decl *D) {
466 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
467 if (Pos != DeclAttrs.end()) {
468 Pos->second->~AttrVec();
469 DeclAttrs.erase(Pos);
470 }
471}
472
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000473MemberSpecializationInfo *
Douglas Gregor663b5a02009-10-14 20:14:33 +0000474ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000475 assert(Var->isStaticDataMember() && "Not a static data member");
Douglas Gregor663b5a02009-10-14 20:14:33 +0000476 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
Douglas Gregor7caa6822009-07-24 20:34:43 +0000477 = InstantiatedFromStaticDataMember.find(Var);
478 if (Pos == InstantiatedFromStaticDataMember.end())
479 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Douglas Gregor7caa6822009-07-24 20:34:43 +0000481 return Pos->second;
482}
483
Mike Stump1eb44332009-09-09 15:08:12 +0000484void
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000485ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000486 TemplateSpecializationKind TSK,
487 SourceLocation PointOfInstantiation) {
Douglas Gregor7caa6822009-07-24 20:34:43 +0000488 assert(Inst->isStaticDataMember() && "Not a static data member");
489 assert(Tmpl->isStaticDataMember() && "Not a static data member");
490 assert(!InstantiatedFromStaticDataMember[Inst] &&
491 "Already noted what static data member was instantiated from");
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000492 InstantiatedFromStaticDataMember[Inst]
Argyrios Kyrtzidis9421adc2010-07-04 21:44:00 +0000493 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000494}
495
John McCall7ba107a2009-11-18 02:36:19 +0000496NamedDecl *
John McCalled976492009-12-04 22:46:56 +0000497ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
John McCall7ba107a2009-11-18 02:36:19 +0000498 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
John McCalled976492009-12-04 22:46:56 +0000499 = InstantiatedFromUsingDecl.find(UUD);
500 if (Pos == InstantiatedFromUsingDecl.end())
Anders Carlsson0d8df782009-08-29 19:37:28 +0000501 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Anders Carlsson0d8df782009-08-29 19:37:28 +0000503 return Pos->second;
504}
505
506void
John McCalled976492009-12-04 22:46:56 +0000507ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
508 assert((isa<UsingDecl>(Pattern) ||
509 isa<UnresolvedUsingValueDecl>(Pattern) ||
510 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
511 "pattern decl is not a using decl");
512 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
513 InstantiatedFromUsingDecl[Inst] = Pattern;
514}
515
516UsingShadowDecl *
517ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
518 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
519 = InstantiatedFromUsingShadowDecl.find(Inst);
520 if (Pos == InstantiatedFromUsingShadowDecl.end())
521 return 0;
522
523 return Pos->second;
524}
525
526void
527ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
528 UsingShadowDecl *Pattern) {
529 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
530 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +0000531}
532
Anders Carlssond8b285f2009-09-01 04:26:58 +0000533FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
534 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
535 = InstantiatedFromUnnamedFieldDecl.find(Field);
536 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
537 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Anders Carlssond8b285f2009-09-01 04:26:58 +0000539 return Pos->second;
540}
541
542void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
543 FieldDecl *Tmpl) {
544 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
545 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
546 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
547 "Already noted what unnamed field was instantiated from");
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Anders Carlssond8b285f2009-09-01 04:26:58 +0000549 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
550}
551
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000552bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
553 const FieldDecl *LastFD) const {
554 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000555 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0);
Fariborz Jahanian14d56ef2011-04-27 17:14:21 +0000556}
557
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000558bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
559 const FieldDecl *LastFD) const {
560 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000561 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() == 0 &&
562 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() != 0);
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000563}
564
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000565bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
566 const FieldDecl *LastFD) const {
567 return (FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000568 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue() &&
569 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +0000570}
571
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000572bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000573 const FieldDecl *LastFD) const {
574 return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000575 LastFD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000576}
577
Chad Rosierdd7fddb2011-08-04 23:34:15 +0000578bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000579 const FieldDecl *LastFD) const {
580 return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
Chad Rosier682b7f82011-08-04 21:50:29 +0000581 FD->getBitWidth()->EvaluateAsInt(*this).getZExtValue());
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +0000582}
583
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000584ASTContext::overridden_cxx_method_iterator
585ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
586 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
587 = OverriddenMethods.find(Method);
588 if (Pos == OverriddenMethods.end())
589 return 0;
590
591 return Pos->second.begin();
592}
593
594ASTContext::overridden_cxx_method_iterator
595ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
596 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
597 = OverriddenMethods.find(Method);
598 if (Pos == OverriddenMethods.end())
599 return 0;
600
601 return Pos->second.end();
602}
603
Argyrios Kyrtzidisc91e9f42010-07-04 21:44:35 +0000604unsigned
605ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
606 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
607 = OverriddenMethods.find(Method);
608 if (Pos == OverriddenMethods.end())
609 return 0;
610
611 return Pos->second.size();
612}
613
Douglas Gregor7d10b7e2010-03-02 23:58:15 +0000614void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
615 const CXXMethodDecl *Overridden) {
616 OverriddenMethods[Method].push_back(Overridden);
617}
618
Chris Lattner464175b2007-07-18 17:52:12 +0000619//===----------------------------------------------------------------------===//
620// Type Sizing and Analysis
621//===----------------------------------------------------------------------===//
Chris Lattnera7674d82007-07-13 22:13:22 +0000622
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000623/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
624/// scalar floating point type.
625const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall183700f2009-09-21 23:43:11 +0000626 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000627 assert(BT && "Not a floating point type!");
628 switch (BT->getKind()) {
629 default: assert(0 && "Not a floating point type!");
630 case BuiltinType::Float: return Target.getFloatFormat();
631 case BuiltinType::Double: return Target.getDoubleFormat();
632 case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
633 }
634}
635
Ken Dyck8b752f12010-01-27 17:10:57 +0000636/// getDeclAlign - Return a conservative estimate of the alignment of the
Chris Lattneraf707ab2009-01-24 21:53:27 +0000637/// specified decl. Note that bitfields do not have a valid alignment, so
638/// this method will assert on them.
Sebastian Redl5d484e82009-11-23 17:18:46 +0000639/// If @p RefAsPointee, references are treated like their underlying type
640/// (for alignof), else they're treated like pointers (for CodeGen).
Jay Foad4ba2a172011-01-12 09:06:06 +0000641CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
Eli Friedmandcdafb62009-02-22 02:56:25 +0000642 unsigned Align = Target.getCharWidth();
643
John McCall4081a5c2010-10-08 18:24:19 +0000644 bool UseAlignAttrOnly = false;
645 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
646 Align = AlignFromAttr;
Eli Friedmandcdafb62009-02-22 02:56:25 +0000647
John McCall4081a5c2010-10-08 18:24:19 +0000648 // __attribute__((aligned)) can increase or decrease alignment
649 // *except* on a struct or struct member, where it only increases
650 // alignment unless 'packed' is also specified.
651 //
652 // It is an error for [[align]] to decrease alignment, so we can
653 // ignore that possibility; Sema should diagnose it.
654 if (isa<FieldDecl>(D)) {
655 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
656 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
657 } else {
658 UseAlignAttrOnly = true;
659 }
660 }
Fariborz Jahanian78a7d7d2011-05-05 21:19:14 +0000661 else if (isa<FieldDecl>(D))
662 UseAlignAttrOnly =
663 D->hasAttr<PackedAttr>() ||
664 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall4081a5c2010-10-08 18:24:19 +0000665
John McCallba4f5d52011-01-20 07:57:12 +0000666 // If we're using the align attribute only, just ignore everything
667 // else about the declaration and its type.
John McCall4081a5c2010-10-08 18:24:19 +0000668 if (UseAlignAttrOnly) {
John McCallba4f5d52011-01-20 07:57:12 +0000669 // do nothing
670
John McCall4081a5c2010-10-08 18:24:19 +0000671 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattneraf707ab2009-01-24 21:53:27 +0000672 QualType T = VD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000673 if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
Sebastian Redl5d484e82009-11-23 17:18:46 +0000674 if (RefAsPointee)
675 T = RT->getPointeeType();
676 else
677 T = getPointerType(RT->getPointeeType());
678 }
679 if (!T->isIncompleteType() && !T->isFunctionType()) {
John McCall3b657512011-01-19 10:06:00 +0000680 // Adjust alignments of declarations with array type by the
681 // large-array alignment on the target.
Rafael Espindola6deecb02010-06-04 23:15:27 +0000682 unsigned MinWidth = Target.getLargeArrayMinWidth();
John McCall3b657512011-01-19 10:06:00 +0000683 const ArrayType *arrayType;
684 if (MinWidth && (arrayType = getAsArrayType(T))) {
685 if (isa<VariableArrayType>(arrayType))
686 Align = std::max(Align, Target.getLargeArrayAlign());
687 else if (isa<ConstantArrayType>(arrayType) &&
688 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
689 Align = std::max(Align, Target.getLargeArrayAlign());
Eli Friedmandcdafb62009-02-22 02:56:25 +0000690
John McCall3b657512011-01-19 10:06:00 +0000691 // Walk through any array types while we're at it.
692 T = getBaseElementType(arrayType);
693 }
Chad Rosier9f1210c2011-07-26 07:03:04 +0000694 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Eli Friedmandcdafb62009-02-22 02:56:25 +0000695 }
John McCallba4f5d52011-01-20 07:57:12 +0000696
697 // Fields can be subject to extra alignment constraints, like if
698 // the field is packed, the struct is packed, or the struct has a
699 // a max-field-alignment constraint (#pragma pack). So calculate
700 // the actual alignment of the field within the struct, and then
701 // (as we're expected to) constrain that by the alignment of the type.
702 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
703 // So calculate the alignment of the field.
704 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
705
706 // Start with the record's overall alignment.
Ken Dyckdac54c12011-02-15 02:32:40 +0000707 unsigned fieldAlign = toBits(layout.getAlignment());
John McCallba4f5d52011-01-20 07:57:12 +0000708
709 // Use the GCD of that and the offset within the record.
710 uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
711 if (offset > 0) {
712 // Alignment is always a power of 2, so the GCD will be a power of 2,
713 // which means we get to do this crazy thing instead of Euclid's.
714 uint64_t lowBitOfOffset = offset & (~offset + 1);
715 if (lowBitOfOffset < fieldAlign)
716 fieldAlign = static_cast<unsigned>(lowBitOfOffset);
717 }
718
719 Align = std::min(Align, fieldAlign);
Charles Davis05f62472010-02-23 04:52:00 +0000720 }
Chris Lattneraf707ab2009-01-24 21:53:27 +0000721 }
Eli Friedmandcdafb62009-02-22 02:56:25 +0000722
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000723 return toCharUnitsFromBits(Align);
Chris Lattneraf707ab2009-01-24 21:53:27 +0000724}
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000725
John McCallea1471e2010-05-20 01:18:31 +0000726std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000727ASTContext::getTypeInfoInChars(const Type *T) const {
John McCallea1471e2010-05-20 01:18:31 +0000728 std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
Ken Dyckeb6f5dc2011-01-15 18:38:59 +0000729 return std::make_pair(toCharUnitsFromBits(Info.first),
730 toCharUnitsFromBits(Info.second));
John McCallea1471e2010-05-20 01:18:31 +0000731}
732
733std::pair<CharUnits, CharUnits>
Ken Dyckbee5a792011-02-20 01:55:18 +0000734ASTContext::getTypeInfoInChars(QualType T) const {
John McCallea1471e2010-05-20 01:18:31 +0000735 return getTypeInfoInChars(T.getTypePtr());
736}
737
Chris Lattnera7674d82007-07-13 22:13:22 +0000738/// getTypeSize - Return the size of the specified type, in bits. This method
739/// does not work on incomplete types.
John McCall0953e762009-09-24 19:53:00 +0000740///
741/// FIXME: Pointers into different addr spaces could have different sizes and
742/// alignment requirements: getPointerInfo should take an AddrSpace, this
743/// should take a QualType, &c.
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000744std::pair<uint64_t, unsigned>
Jay Foad4ba2a172011-01-12 09:06:06 +0000745ASTContext::getTypeInfo(const Type *T) const {
Mike Stump5e301002009-02-27 18:32:39 +0000746 uint64_t Width=0;
747 unsigned Align=8;
Chris Lattnera7674d82007-07-13 22:13:22 +0000748 switch (T->getTypeClass()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000749#define TYPE(Class, Base)
750#define ABSTRACT_TYPE(Class, Base)
Douglas Gregor18857642009-04-30 17:32:17 +0000751#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregor72564e72009-02-26 23:50:07 +0000752#define DEPENDENT_TYPE(Class, Base) case Type::Class:
753#include "clang/AST/TypeNodes.def"
John McCalld3d49bb2011-06-28 16:49:23 +0000754 llvm_unreachable("Should not see dependent types");
Douglas Gregor72564e72009-02-26 23:50:07 +0000755 break;
756
Chris Lattner692233e2007-07-13 22:27:08 +0000757 case Type::FunctionNoProto:
758 case Type::FunctionProto:
Douglas Gregor18857642009-04-30 17:32:17 +0000759 // GCC extension: alignof(function) = 32 bits
760 Width = 0;
761 Align = 32;
762 break;
763
Douglas Gregor72564e72009-02-26 23:50:07 +0000764 case Type::IncompleteArray:
Steve Narofffb22d962007-08-30 01:06:46 +0000765 case Type::VariableArray:
Douglas Gregor18857642009-04-30 17:32:17 +0000766 Width = 0;
767 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
768 break;
769
Steve Narofffb22d962007-08-30 01:06:46 +0000770 case Type::ConstantArray: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000771 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Chris Lattner98be4942008-03-05 18:54:05 +0000773 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000774 Width = EltInfo.first*CAT->getSize().getZExtValue();
Chris Lattner030d8842007-07-19 22:06:24 +0000775 Align = EltInfo.second;
Argyrios Kyrtzidiscd88b412011-04-26 21:05:39 +0000776 Width = llvm::RoundUpToAlignment(Width, Align);
Chris Lattner030d8842007-07-19 22:06:24 +0000777 break;
Christopher Lamb5c09a022007-12-29 05:10:55 +0000778 }
Nate Begeman213541a2008-04-18 23:10:10 +0000779 case Type::ExtVector:
Chris Lattner030d8842007-07-19 22:06:24 +0000780 case Type::Vector: {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000781 const VectorType *VT = cast<VectorType>(T);
782 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
783 Width = EltInfo.first*VT->getNumElements();
Eli Friedman4bd998b2008-05-30 09:31:38 +0000784 Align = Width;
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000785 // If the alignment is not a power of 2, round up to the next power of 2.
786 // This happens for non-power-of-2 length vectors.
Dan Gohman8eefcd32010-04-21 23:32:43 +0000787 if (Align & (Align-1)) {
Chris Lattner9fcfe922009-10-22 05:17:15 +0000788 Align = llvm::NextPowerOf2(Align);
789 Width = llvm::RoundUpToAlignment(Width, Align);
790 }
Chris Lattner030d8842007-07-19 22:06:24 +0000791 break;
792 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000793
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000794 case Type::Builtin:
Chris Lattnera7674d82007-07-13 22:13:22 +0000795 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner692233e2007-07-13 22:27:08 +0000796 default: assert(0 && "Unknown builtin type!");
Chris Lattnerd2d2a112007-07-14 01:29:45 +0000797 case BuiltinType::Void:
Douglas Gregor18857642009-04-30 17:32:17 +0000798 // GCC extension: alignof(void) = 8 bits.
799 Width = 0;
800 Align = 8;
801 break;
802
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000803 case BuiltinType::Bool:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000804 Width = Target.getBoolWidth();
805 Align = Target.getBoolAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000806 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000807 case BuiltinType::Char_S:
808 case BuiltinType::Char_U:
809 case BuiltinType::UChar:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000810 case BuiltinType::SChar:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000811 Width = Target.getCharWidth();
812 Align = Target.getCharAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000813 break;
Chris Lattner3f59c972010-12-25 23:25:43 +0000814 case BuiltinType::WChar_S:
815 case BuiltinType::WChar_U:
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +0000816 Width = Target.getWCharWidth();
817 Align = Target.getWCharAlign();
818 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +0000819 case BuiltinType::Char16:
820 Width = Target.getChar16Width();
821 Align = Target.getChar16Align();
822 break;
823 case BuiltinType::Char32:
824 Width = Target.getChar32Width();
825 Align = Target.getChar32Align();
826 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000827 case BuiltinType::UShort:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000828 case BuiltinType::Short:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000829 Width = Target.getShortWidth();
830 Align = Target.getShortAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000831 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000832 case BuiltinType::UInt:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000833 case BuiltinType::Int:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000834 Width = Target.getIntWidth();
835 Align = Target.getIntAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000836 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000837 case BuiltinType::ULong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000838 case BuiltinType::Long:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000839 Width = Target.getLongWidth();
840 Align = Target.getLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000841 break;
Chris Lattner692233e2007-07-13 22:27:08 +0000842 case BuiltinType::ULongLong:
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000843 case BuiltinType::LongLong:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000844 Width = Target.getLongLongWidth();
845 Align = Target.getLongLongAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000846 break;
Chris Lattnerec16cb92009-04-30 02:55:13 +0000847 case BuiltinType::Int128:
848 case BuiltinType::UInt128:
849 Width = 128;
850 Align = 128; // int128_t is 128-bit aligned on all targets.
851 break;
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000852 case BuiltinType::Float:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000853 Width = Target.getFloatWidth();
854 Align = Target.getFloatAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000855 break;
856 case BuiltinType::Double:
Chris Lattner5426bf62008-04-07 07:01:58 +0000857 Width = Target.getDoubleWidth();
858 Align = Target.getDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000859 break;
860 case BuiltinType::LongDouble:
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000861 Width = Target.getLongDoubleWidth();
862 Align = Target.getLongDoubleAlign();
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000863 break;
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000864 case BuiltinType::NullPtr:
865 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
866 Align = Target.getPointerAlign(0); // == sizeof(void*)
Sebastian Redl1590d9c2009-05-27 19:34:06 +0000867 break;
Fariborz Jahaniane04f5fc2010-08-02 18:03:20 +0000868 case BuiltinType::ObjCId:
869 case BuiltinType::ObjCClass:
870 case BuiltinType::ObjCSel:
871 Width = Target.getPointerWidth(0);
872 Align = Target.getPointerAlign(0);
873 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000874 }
Chris Lattnerbfef6d72007-07-15 23:46:53 +0000875 break;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000876 case Type::ObjCObjectPointer:
Chris Lattner5426bf62008-04-07 07:01:58 +0000877 Width = Target.getPointerWidth(0);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000878 Align = Target.getPointerAlign(0);
Chris Lattner6f62c2a2007-12-19 19:23:28 +0000879 break;
Steve Naroff485eeff2008-09-24 15:05:44 +0000880 case Type::BlockPointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000881 unsigned AS = getTargetAddressSpace(
882 cast<BlockPointerType>(T)->getPointeeType());
Steve Naroff485eeff2008-09-24 15:05:44 +0000883 Width = Target.getPointerWidth(AS);
884 Align = Target.getPointerAlign(AS);
885 break;
886 }
Sebastian Redl5d484e82009-11-23 17:18:46 +0000887 case Type::LValueReference:
888 case Type::RValueReference: {
889 // alignof and sizeof should never enter this code path here, so we go
890 // the pointer route.
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000891 unsigned AS = getTargetAddressSpace(
892 cast<ReferenceType>(T)->getPointeeType());
Sebastian Redl5d484e82009-11-23 17:18:46 +0000893 Width = Target.getPointerWidth(AS);
894 Align = Target.getPointerAlign(AS);
895 break;
896 }
Chris Lattnerf72a4432008-03-08 08:34:58 +0000897 case Type::Pointer: {
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000898 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Chris Lattner5426bf62008-04-07 07:01:58 +0000899 Width = Target.getPointerWidth(AS);
Chris Lattnerf72a4432008-03-08 08:34:58 +0000900 Align = Target.getPointerAlign(AS);
901 break;
902 }
Sebastian Redlf30208a2009-01-24 21:16:55 +0000903 case Type::MemberPointer: {
Charles Davis071cc7d2010-08-16 03:33:14 +0000904 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000905 std::pair<uint64_t, unsigned> PtrDiffInfo =
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000906 getTypeInfo(getPointerDiffType());
Charles Davis071cc7d2010-08-16 03:33:14 +0000907 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
Anders Carlsson1cca74e2009-05-17 02:06:04 +0000908 Align = PtrDiffInfo.second;
909 break;
Sebastian Redlf30208a2009-01-24 21:16:55 +0000910 }
Chris Lattner5d2a6302007-07-18 18:26:58 +0000911 case Type::Complex: {
912 // Complex types have the same alignment as their elements, but twice the
913 // size.
Mike Stump1eb44332009-09-09 15:08:12 +0000914 std::pair<uint64_t, unsigned> EltInfo =
Chris Lattner98be4942008-03-05 18:54:05 +0000915 getTypeInfo(cast<ComplexType>(T)->getElementType());
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000916 Width = EltInfo.first*2;
Chris Lattner5d2a6302007-07-18 18:26:58 +0000917 Align = EltInfo.second;
918 break;
919 }
John McCallc12c5bb2010-05-15 11:32:37 +0000920 case Type::ObjCObject:
921 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Devang Patel44a3dde2008-06-04 21:54:36 +0000922 case Type::ObjCInterface: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000923 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Patel44a3dde2008-06-04 21:54:36 +0000924 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000925 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000926 Align = toBits(Layout.getAlignment());
Devang Patel44a3dde2008-06-04 21:54:36 +0000927 break;
928 }
Douglas Gregor72564e72009-02-26 23:50:07 +0000929 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +0000930 case Type::Enum: {
Daniel Dunbar1d751182008-11-08 05:48:37 +0000931 const TagType *TT = cast<TagType>(T);
932
933 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor22ce41d2011-04-20 17:29:44 +0000934 Width = 8;
935 Align = 8;
Chris Lattner8389eab2008-08-09 21:35:13 +0000936 break;
937 }
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Daniel Dunbar1d751182008-11-08 05:48:37 +0000939 if (const EnumType *ET = dyn_cast<EnumType>(TT))
Chris Lattner71763312008-04-06 22:05:18 +0000940 return getTypeInfo(ET->getDecl()->getIntegerType());
941
Daniel Dunbar1d751182008-11-08 05:48:37 +0000942 const RecordType *RT = cast<RecordType>(TT);
Chris Lattner71763312008-04-06 22:05:18 +0000943 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
Ken Dyckdd76a9a2011-02-11 01:54:29 +0000944 Width = toBits(Layout.getSize());
Ken Dyckdac54c12011-02-15 02:32:40 +0000945 Align = toBits(Layout.getAlignment());
Chris Lattnerdc0d73e2007-07-23 22:46:22 +0000946 break;
Chris Lattnera7674d82007-07-13 22:13:22 +0000947 }
Douglas Gregor7532dc62009-03-30 22:58:21 +0000948
Chris Lattner9fcfe922009-10-22 05:17:15 +0000949 case Type::SubstTemplateTypeParm:
John McCall49a832b2009-10-18 09:09:24 +0000950 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
951 getReplacementType().getTypePtr());
John McCall49a832b2009-10-18 09:09:24 +0000952
Richard Smith34b41d92011-02-20 03:19:35 +0000953 case Type::Auto: {
954 const AutoType *A = cast<AutoType>(T);
955 assert(A->isDeduced() && "Cannot request the size of a dependent type");
Matt Beaumont-Gaydc856af2011-02-22 20:00:16 +0000956 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith34b41d92011-02-20 03:19:35 +0000957 }
958
Abramo Bagnara075f8f12010-12-10 16:29:40 +0000959 case Type::Paren:
960 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
961
Douglas Gregor18857642009-04-30 17:32:17 +0000962 case Type::Typedef: {
Richard Smith162e1c12011-04-15 14:24:37 +0000963 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
Douglas Gregordf1367a2010-08-27 00:11:28 +0000964 std::pair<uint64_t, unsigned> Info
965 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattnerc1de52d2011-02-19 22:55:41 +0000966 // If the typedef has an aligned attribute on it, it overrides any computed
967 // alignment we have. This violates the GCC documentation (which says that
968 // attribute(aligned) can only round up) but matches its implementation.
969 if (unsigned AttrAlign = Typedef->getMaxAlignment())
970 Align = AttrAlign;
971 else
972 Align = Info.second;
Douglas Gregordf1367a2010-08-27 00:11:28 +0000973 Width = Info.first;
Douglas Gregor7532dc62009-03-30 22:58:21 +0000974 break;
Chris Lattner71763312008-04-06 22:05:18 +0000975 }
Douglas Gregor18857642009-04-30 17:32:17 +0000976
977 case Type::TypeOfExpr:
978 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
979 .getTypePtr());
980
981 case Type::TypeOf:
982 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
983
Anders Carlsson395b4752009-06-24 19:06:50 +0000984 case Type::Decltype:
985 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
986 .getTypePtr());
987
Sean Huntca63c202011-05-24 22:41:36 +0000988 case Type::UnaryTransform:
989 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
990
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000991 case Type::Elaborated:
992 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump1eb44332009-09-09 15:08:12 +0000993
John McCall9d156a72011-01-06 01:58:22 +0000994 case Type::Attributed:
995 return getTypeInfo(
996 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
997
Richard Smith3e4c6c42011-05-05 21:57:07 +0000998 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +0000999 assert(getCanonicalType(T) != T &&
Douglas Gregor18857642009-04-30 17:32:17 +00001000 "Cannot request the size of a dependent type");
Richard Smith3e4c6c42011-05-05 21:57:07 +00001001 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1002 // A type alias template specialization may refer to a typedef with the
1003 // aligned attribute on it.
1004 if (TST->isTypeAlias())
1005 return getTypeInfo(TST->getAliasedType().getTypePtr());
1006 else
1007 return getTypeInfo(getCanonicalType(T));
1008 }
1009
Douglas Gregor18857642009-04-30 17:32:17 +00001010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Chris Lattner464175b2007-07-18 17:52:12 +00001012 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001013 return std::make_pair(Width, Align);
Chris Lattnera7674d82007-07-13 22:13:22 +00001014}
1015
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001016/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1017CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1018 return CharUnits::fromQuantity(BitSize / getCharWidth());
1019}
1020
Ken Dyckdd76a9a2011-02-11 01:54:29 +00001021/// toBits - Convert a size in characters to a size in characters.
1022int64_t ASTContext::toBits(CharUnits CharSize) const {
1023 return CharSize.getQuantity() * getCharWidth();
1024}
1025
Ken Dyckbdc601b2009-12-22 14:23:30 +00001026/// getTypeSizeInChars - Return the size of the specified type, in characters.
1027/// This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001028CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001029 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001030}
Jay Foad4ba2a172011-01-12 09:06:06 +00001031CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001032 return toCharUnitsFromBits(getTypeSize(T));
Ken Dyckbdc601b2009-12-22 14:23:30 +00001033}
1034
Ken Dyck16e20cc2010-01-26 17:25:18 +00001035/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck86fa4312010-01-26 17:22:55 +00001036/// characters. This method does not work on incomplete types.
Jay Foad4ba2a172011-01-12 09:06:06 +00001037CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001038 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001039}
Jay Foad4ba2a172011-01-12 09:06:06 +00001040CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckeb6f5dc2011-01-15 18:38:59 +00001041 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck86fa4312010-01-26 17:22:55 +00001042}
1043
Chris Lattner34ebde42009-01-27 18:08:34 +00001044/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1045/// type for the current target in bits. This can be different than the ABI
1046/// alignment in cases where it is beneficial for performance to overalign
1047/// a data type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001048unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
Chris Lattner34ebde42009-01-27 18:08:34 +00001049 unsigned ABIAlign = getTypeAlign(T);
Eli Friedman1eed6022009-05-25 21:27:19 +00001050
1051 // Double and long long should be naturally aligned if possible.
John McCall183700f2009-09-21 23:43:11 +00001052 if (const ComplexType* CT = T->getAs<ComplexType>())
Eli Friedman1eed6022009-05-25 21:27:19 +00001053 T = CT->getElementType().getTypePtr();
1054 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1055 T->isSpecificBuiltinType(BuiltinType::LongLong))
1056 return std::max(ABIAlign, (unsigned)getTypeSize(T));
1057
Chris Lattner34ebde42009-01-27 18:08:34 +00001058 return ABIAlign;
1059}
1060
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001061/// DeepCollectObjCIvars -
1062/// This routine first collects all declared, but not synthesized, ivars in
1063/// super class and then collects all ivars, including those synthesized for
1064/// current class. This routine is used for implementation of current class
1065/// when all ivars, declared and synthesized are known.
Fariborz Jahanian98200742009-05-12 18:14:29 +00001066///
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001067void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1068 bool leafClass,
Jordy Rosedb8264e2011-07-22 02:08:32 +00001069 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00001070 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1071 DeepCollectObjCIvars(SuperClass, false, Ivars);
1072 if (!leafClass) {
1073 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1074 E = OI->ivar_end(); I != E; ++I)
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001075 Ivars.push_back(*I);
1076 }
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001077 else {
1078 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosedb8264e2011-07-22 02:08:32 +00001079 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001080 Iv= Iv->getNextIvar())
1081 Ivars.push_back(Iv);
1082 }
Fariborz Jahanian98200742009-05-12 18:14:29 +00001083}
1084
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001085/// CollectInheritedProtocols - Collect all protocols in current class and
1086/// those inherited by it.
1087void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001088 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001089 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001090 // We can use protocol_iterator here instead of
1091 // all_referenced_protocol_iterator since we are walking all categories.
1092 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1093 PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001094 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001095 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001096 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001097 PE = Proto->protocol_end(); P != PE; ++P) {
1098 Protocols.insert(*P);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001099 CollectInheritedProtocols(*P, Protocols);
1100 }
Fariborz Jahanianb2f81212010-02-25 18:24:33 +00001101 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001102
1103 // Categories of this Interface.
1104 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1105 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1106 CollectInheritedProtocols(CDeclChain, Protocols);
1107 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1108 while (SD) {
1109 CollectInheritedProtocols(SD, Protocols);
1110 SD = SD->getSuperClass();
1111 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001112 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Ted Kremenek53b94412010-09-01 01:21:15 +00001113 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001114 PE = OC->protocol_end(); P != PE; ++P) {
1115 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001116 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001117 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1118 PE = Proto->protocol_end(); P != PE; ++P)
1119 CollectInheritedProtocols(*P, Protocols);
1120 }
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001121 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001122 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1123 PE = OP->protocol_end(); P != PE; ++P) {
1124 ObjCProtocolDecl *Proto = (*P);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00001125 Protocols.insert(Proto);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001126 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1127 PE = Proto->protocol_end(); P != PE; ++P)
1128 CollectInheritedProtocols(*P, Protocols);
1129 }
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00001130 }
1131}
1132
Jay Foad4ba2a172011-01-12 09:06:06 +00001133unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001134 unsigned count = 0;
1135 // Count ivars declared in class extension.
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +00001136 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1137 CDecl = CDecl->getNextClassExtension())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001138 count += CDecl->ivar_size();
1139
Fariborz Jahanian3bfacdf2010-03-22 18:25:57 +00001140 // Count ivar defined in this class's implementation. This
1141 // includes synthesized ivars.
1142 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramerb170ca52010-04-27 17:47:25 +00001143 count += ImplDecl->ivar_size();
1144
Fariborz Jahanian8e6ac1d2009-06-04 01:19:09 +00001145 return count;
1146}
1147
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001148/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1149ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1150 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1151 I = ObjCImpls.find(D);
1152 if (I != ObjCImpls.end())
1153 return cast<ObjCImplementationDecl>(I->second);
1154 return 0;
1155}
1156/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1157ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1158 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1159 I = ObjCImpls.find(D);
1160 if (I != ObjCImpls.end())
1161 return cast<ObjCCategoryImplDecl>(I->second);
1162 return 0;
1163}
1164
1165/// \brief Set the implementation of ObjCInterfaceDecl.
1166void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1167 ObjCImplementationDecl *ImplD) {
1168 assert(IFaceD && ImplD && "Passed null params");
1169 ObjCImpls[IFaceD] = ImplD;
1170}
1171/// \brief Set the implementation of ObjCCategoryDecl.
1172void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1173 ObjCCategoryImplDecl *ImplD) {
1174 assert(CatD && ImplD && "Passed null params");
1175 ObjCImpls[CatD] = ImplD;
1176}
1177
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001178/// \brief Get the copy initialization expression of VarDecl,or NULL if
1179/// none exists.
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001180Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001181 assert(VD && "Passed null params");
1182 assert(VD->hasAttr<BlocksAttr>() &&
1183 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian830937b2010-12-02 17:02:11 +00001184 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001185 I = BlockVarCopyInits.find(VD);
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001186 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1187}
1188
1189/// \brief Set the copy inialization expression of a block var decl.
1190void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1191 assert(VD && Init && "Passed null params");
Fariborz Jahaniand016ec22010-12-06 17:28:17 +00001192 assert(VD->hasAttr<BlocksAttr>() &&
1193 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian1ceee5c2010-12-01 22:29:46 +00001194 BlockVarCopyInits[VD] = Init;
1195}
1196
John McCalla93c9342009-12-07 02:54:59 +00001197/// \brief Allocate an uninitialized TypeSourceInfo.
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001198///
John McCalla93c9342009-12-07 02:54:59 +00001199/// The caller should initialize the memory held by TypeSourceInfo using
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001200/// the TypeLoc wrappers.
1201///
1202/// \param T the type that will be the basis for type source info. This type
1203/// should refer to how the declarator was written in source code, not to
1204/// what type semantic analysis resolved the declarator to.
John McCalla93c9342009-12-07 02:54:59 +00001205TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001206 unsigned DataSize) const {
John McCall109de5e2009-10-21 00:23:54 +00001207 if (!DataSize)
1208 DataSize = TypeLoc::getFullDataSizeForType(T);
1209 else
1210 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCalla93c9342009-12-07 02:54:59 +00001211 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall109de5e2009-10-21 00:23:54 +00001212
John McCalla93c9342009-12-07 02:54:59 +00001213 TypeSourceInfo *TInfo =
1214 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1215 new (TInfo) TypeSourceInfo(T);
1216 return TInfo;
Argyrios Kyrtzidisb17166c2009-08-19 01:27:32 +00001217}
1218
John McCalla93c9342009-12-07 02:54:59 +00001219TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001220 SourceLocation L) const {
John McCalla93c9342009-12-07 02:54:59 +00001221 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregorc21c7e92011-01-25 19:13:18 +00001222 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCalla4eb74d2009-10-23 21:14:09 +00001223 return DI;
1224}
1225
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001226const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001227ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001228 return getObjCLayout(D, 0);
1229}
1230
1231const ASTRecordLayout &
Jay Foad4ba2a172011-01-12 09:06:06 +00001232ASTContext::getASTObjCImplementationLayout(
1233 const ObjCImplementationDecl *D) const {
Daniel Dunbarb2dbbb92009-05-03 10:38:35 +00001234 return getObjCLayout(D->getClassInterface(), D);
1235}
1236
Chris Lattnera7674d82007-07-13 22:13:22 +00001237//===----------------------------------------------------------------------===//
1238// Type creation/memoization methods
1239//===----------------------------------------------------------------------===//
1240
Jay Foad4ba2a172011-01-12 09:06:06 +00001241QualType
John McCall3b657512011-01-19 10:06:00 +00001242ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1243 unsigned fastQuals = quals.getFastQualifiers();
1244 quals.removeFastQualifiers();
John McCall0953e762009-09-24 19:53:00 +00001245
1246 // Check if we've already instantiated this type.
1247 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001248 ExtQuals::Profile(ID, baseType, quals);
1249 void *insertPos = 0;
1250 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1251 assert(eq->getQualifiers() == quals);
1252 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001253 }
1254
John McCall3b657512011-01-19 10:06:00 +00001255 // If the base type is not canonical, make the appropriate canonical type.
1256 QualType canon;
1257 if (!baseType->isCanonicalUnqualified()) {
1258 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1259 canonSplit.second.addConsistentQualifiers(quals);
1260 canon = getExtQualType(canonSplit.first, canonSplit.second);
1261
1262 // Re-find the insert position.
1263 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1264 }
1265
1266 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1267 ExtQualNodes.InsertNode(eq, insertPos);
1268 return QualType(eq, fastQuals);
John McCall0953e762009-09-24 19:53:00 +00001269}
1270
Jay Foad4ba2a172011-01-12 09:06:06 +00001271QualType
1272ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001273 QualType CanT = getCanonicalType(T);
1274 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattnerf46699c2008-02-20 20:55:12 +00001275 return T;
Chris Lattnerb7d25532009-02-18 22:53:11 +00001276
John McCall0953e762009-09-24 19:53:00 +00001277 // If we are composing extended qualifiers together, merge together
1278 // into one ExtQuals node.
1279 QualifierCollector Quals;
1280 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001281
John McCall0953e762009-09-24 19:53:00 +00001282 // If this type already has an address space specified, it cannot get
1283 // another one.
1284 assert(!Quals.hasAddressSpace() &&
1285 "Type cannot be in multiple addr spaces!");
1286 Quals.addAddressSpace(AddressSpace);
Mike Stump1eb44332009-09-09 15:08:12 +00001287
John McCall0953e762009-09-24 19:53:00 +00001288 return getExtQualType(TypeNode, Quals);
Christopher Lambebb97e92008-02-04 02:31:56 +00001289}
1290
Chris Lattnerb7d25532009-02-18 22:53:11 +00001291QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad4ba2a172011-01-12 09:06:06 +00001292 Qualifiers::GC GCAttr) const {
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001293 QualType CanT = getCanonicalType(T);
Chris Lattnerb7d25532009-02-18 22:53:11 +00001294 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001295 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00001296
John McCall7f040a92010-12-24 02:08:15 +00001297 if (const PointerType *ptr = T->getAs<PointerType>()) {
1298 QualType Pointee = ptr->getPointeeType();
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001299 if (Pointee->isAnyPointerType()) {
Fariborz Jahanian4027cd12009-06-03 17:15:17 +00001300 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1301 return getPointerType(ResultType);
1302 }
1303 }
Mike Stump1eb44332009-09-09 15:08:12 +00001304
John McCall0953e762009-09-24 19:53:00 +00001305 // If we are composing extended qualifiers together, merge together
1306 // into one ExtQuals node.
1307 QualifierCollector Quals;
1308 const Type *TypeNode = Quals.strip(T);
Mike Stump1eb44332009-09-09 15:08:12 +00001309
John McCall0953e762009-09-24 19:53:00 +00001310 // If this type already has an ObjCGC specified, it cannot get
1311 // another one.
1312 assert(!Quals.hasObjCGCAttr() &&
1313 "Type cannot have multiple ObjCGCs!");
1314 Quals.addObjCGCAttr(GCAttr);
Mike Stump1eb44332009-09-09 15:08:12 +00001315
John McCall0953e762009-09-24 19:53:00 +00001316 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniand33d9c02009-02-18 05:09:49 +00001317}
Chris Lattnera7674d82007-07-13 22:13:22 +00001318
John McCalle6a365d2010-12-19 02:44:49 +00001319const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1320 FunctionType::ExtInfo Info) {
1321 if (T->getExtInfo() == Info)
1322 return T;
1323
1324 QualType Result;
1325 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1326 Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1327 } else {
1328 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1329 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1330 EPI.ExtInfo = Info;
1331 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1332 FPT->getNumArgs(), EPI);
1333 }
1334
1335 return cast<FunctionType>(Result.getTypePtr());
1336}
1337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338/// getComplexType - Return the uniqued reference to the type for a complex
1339/// number with the specified element type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001340QualType ASTContext::getComplexType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 // Unique pointers, to guarantee there is only one pointer of a particular
1342 // structure.
1343 llvm::FoldingSetNodeID ID;
1344 ComplexType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Reid Spencer5f016e22007-07-11 17:01:13 +00001346 void *InsertPos = 0;
1347 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1348 return QualType(CT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Reid Spencer5f016e22007-07-11 17:01:13 +00001350 // If the pointee type isn't canonical, this won't be a canonical type either,
1351 // so fill in the canonical type field.
1352 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001353 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001354 Canonical = getComplexType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Reid Spencer5f016e22007-07-11 17:01:13 +00001356 // Get the new insert position for the node we care about.
1357 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001358 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001359 }
John McCall6b304a02009-09-24 23:30:46 +00001360 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001361 Types.push_back(New);
1362 ComplexTypes.InsertNode(New, InsertPos);
1363 return QualType(New, 0);
1364}
1365
Reid Spencer5f016e22007-07-11 17:01:13 +00001366/// getPointerType - Return the uniqued reference to the type for a pointer to
1367/// the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001368QualType ASTContext::getPointerType(QualType T) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001369 // Unique pointers, to guarantee there is only one pointer of a particular
1370 // structure.
1371 llvm::FoldingSetNodeID ID;
1372 PointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 void *InsertPos = 0;
1375 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1376 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 // If the pointee type isn't canonical, this won't be a canonical type either,
1379 // so fill in the canonical type field.
1380 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001381 if (!T.isCanonical()) {
Chris Lattnerf52ab252008-04-06 22:59:24 +00001382 Canonical = getPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Reid Spencer5f016e22007-07-11 17:01:13 +00001384 // Get the new insert position for the node we care about.
1385 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001386 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001387 }
John McCall6b304a02009-09-24 23:30:46 +00001388 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Reid Spencer5f016e22007-07-11 17:01:13 +00001389 Types.push_back(New);
1390 PointerTypes.InsertNode(New, InsertPos);
1391 return QualType(New, 0);
1392}
1393
Mike Stump1eb44332009-09-09 15:08:12 +00001394/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroff5618bd42008-08-27 16:04:49 +00001395/// a pointer to the specified block.
Jay Foad4ba2a172011-01-12 09:06:06 +00001396QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff296e8d52008-08-28 19:20:44 +00001397 assert(T->isFunctionType() && "block of function types only");
1398 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroff5618bd42008-08-27 16:04:49 +00001399 // structure.
1400 llvm::FoldingSetNodeID ID;
1401 BlockPointerType::Profile(ID, T);
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Steve Naroff5618bd42008-08-27 16:04:49 +00001403 void *InsertPos = 0;
1404 if (BlockPointerType *PT =
1405 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1406 return QualType(PT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001407
1408 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroff5618bd42008-08-27 16:04:49 +00001409 // type either so fill in the canonical type field.
1410 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001411 if (!T.isCanonical()) {
Steve Naroff5618bd42008-08-27 16:04:49 +00001412 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Steve Naroff5618bd42008-08-27 16:04:49 +00001414 // Get the new insert position for the node we care about.
1415 BlockPointerType *NewIP =
1416 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001417 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff5618bd42008-08-27 16:04:49 +00001418 }
John McCall6b304a02009-09-24 23:30:46 +00001419 BlockPointerType *New
1420 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroff5618bd42008-08-27 16:04:49 +00001421 Types.push_back(New);
1422 BlockPointerTypes.InsertNode(New, InsertPos);
1423 return QualType(New, 0);
1424}
1425
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001426/// getLValueReferenceType - Return the uniqued reference to the type for an
1427/// lvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001428QualType
1429ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor9625e442011-05-21 22:16:50 +00001430 assert(getCanonicalType(T) != OverloadTy &&
1431 "Unresolved overloaded function type");
1432
Reid Spencer5f016e22007-07-11 17:01:13 +00001433 // Unique pointers, to guarantee there is only one pointer of a particular
1434 // structure.
1435 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001436 ReferenceType::Profile(ID, T, SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001437
1438 void *InsertPos = 0;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001439 if (LValueReferenceType *RT =
1440 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001441 return QualType(RT, 0);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001442
John McCall54e14c42009-10-22 22:37:11 +00001443 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1444
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // If the referencee type isn't canonical, this won't be a canonical type
1446 // either, so fill in the canonical type field.
1447 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001448 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1449 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1450 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001451
Reid Spencer5f016e22007-07-11 17:01:13 +00001452 // Get the new insert position for the node we care about.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001453 LValueReferenceType *NewIP =
1454 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001455 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001456 }
1457
John McCall6b304a02009-09-24 23:30:46 +00001458 LValueReferenceType *New
John McCall54e14c42009-10-22 22:37:11 +00001459 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1460 SpelledAsLValue);
Reid Spencer5f016e22007-07-11 17:01:13 +00001461 Types.push_back(New);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001462 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCall54e14c42009-10-22 22:37:11 +00001463
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001464 return QualType(New, 0);
1465}
1466
1467/// getRValueReferenceType - Return the uniqued reference to the type for an
1468/// rvalue reference to the specified type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001469QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001470 // Unique pointers, to guarantee there is only one pointer of a particular
1471 // structure.
1472 llvm::FoldingSetNodeID ID;
John McCall54e14c42009-10-22 22:37:11 +00001473 ReferenceType::Profile(ID, T, false);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001474
1475 void *InsertPos = 0;
1476 if (RValueReferenceType *RT =
1477 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1478 return QualType(RT, 0);
1479
John McCall54e14c42009-10-22 22:37:11 +00001480 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1481
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001482 // If the referencee type isn't canonical, this won't be a canonical type
1483 // either, so fill in the canonical type field.
1484 QualType Canonical;
John McCall54e14c42009-10-22 22:37:11 +00001485 if (InnerRef || !T.isCanonical()) {
1486 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1487 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001488
1489 // Get the new insert position for the node we care about.
1490 RValueReferenceType *NewIP =
1491 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001492 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001493 }
1494
John McCall6b304a02009-09-24 23:30:46 +00001495 RValueReferenceType *New
1496 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001497 Types.push_back(New);
1498 RValueReferenceTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001499 return QualType(New, 0);
1500}
1501
Sebastian Redlf30208a2009-01-24 21:16:55 +00001502/// getMemberPointerType - Return the uniqued reference to the type for a
1503/// member pointer to the specified type, in the specified class.
Jay Foad4ba2a172011-01-12 09:06:06 +00001504QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001505 // Unique pointers, to guarantee there is only one pointer of a particular
1506 // structure.
1507 llvm::FoldingSetNodeID ID;
1508 MemberPointerType::Profile(ID, T, Cls);
1509
1510 void *InsertPos = 0;
1511 if (MemberPointerType *PT =
1512 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1513 return QualType(PT, 0);
1514
1515 // If the pointee or class type isn't canonical, this won't be a canonical
1516 // type either, so fill in the canonical type field.
1517 QualType Canonical;
Douglas Gregor87c12c42009-11-04 16:49:01 +00001518 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redlf30208a2009-01-24 21:16:55 +00001519 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1520
1521 // Get the new insert position for the node we care about.
1522 MemberPointerType *NewIP =
1523 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001524 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redlf30208a2009-01-24 21:16:55 +00001525 }
John McCall6b304a02009-09-24 23:30:46 +00001526 MemberPointerType *New
1527 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redlf30208a2009-01-24 21:16:55 +00001528 Types.push_back(New);
1529 MemberPointerTypes.InsertNode(New, InsertPos);
1530 return QualType(New, 0);
1531}
1532
Mike Stump1eb44332009-09-09 15:08:12 +00001533/// getConstantArrayType - Return the unique reference to the type for an
Steve Narofffb22d962007-08-30 01:06:46 +00001534/// array of the specified element type.
Mike Stump1eb44332009-09-09 15:08:12 +00001535QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattner38aeec72009-05-13 04:12:56 +00001536 const llvm::APInt &ArySizeIn,
Steve Naroffc9406122007-08-30 18:10:14 +00001537 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001538 unsigned IndexTypeQuals) const {
Sebastian Redl923d56d2009-11-05 15:52:31 +00001539 assert((EltTy->isDependentType() ||
1540 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedman587cbdf2009-05-29 20:17:55 +00001541 "Constant array of VLAs is illegal!");
1542
Chris Lattner38aeec72009-05-13 04:12:56 +00001543 // Convert the array size into a canonical width matching the pointer size for
1544 // the target.
1545 llvm::APInt ArySize(ArySizeIn);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001546 ArySize =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001547 ArySize.zextOrTrunc(Target.getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Reid Spencer5f016e22007-07-11 17:01:13 +00001549 llvm::FoldingSetNodeID ID;
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001550 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Reid Spencer5f016e22007-07-11 17:01:13 +00001552 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001553 if (ConstantArrayType *ATP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001554 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 return QualType(ATP, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
John McCall3b657512011-01-19 10:06:00 +00001557 // If the element type isn't canonical or has qualifiers, this won't
1558 // be a canonical type either, so fill in the canonical type field.
1559 QualType Canon;
1560 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1561 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1562 Canon = getConstantArrayType(QualType(canonSplit.first, 0), ArySize,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001563 ASM, IndexTypeQuals);
John McCall3b657512011-01-19 10:06:00 +00001564 Canon = getQualifiedType(Canon, canonSplit.second);
1565
Reid Spencer5f016e22007-07-11 17:01:13 +00001566 // Get the new insert position for the node we care about.
Mike Stump1eb44332009-09-09 15:08:12 +00001567 ConstantArrayType *NewIP =
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001568 ConstantArrayTypes.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 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
John McCall6b304a02009-09-24 23:30:46 +00001572 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001573 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenek7192f8e2007-10-31 17:10:13 +00001574 ConstantArrayTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 Types.push_back(New);
1576 return QualType(New, 0);
1577}
1578
John McCallce889032011-01-18 08:40:38 +00001579/// getVariableArrayDecayedType - Turns the given type, which may be
1580/// variably-modified, into the corresponding type with all the known
1581/// sizes replaced with [*].
1582QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1583 // Vastly most common case.
1584 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001585
John McCallce889032011-01-18 08:40:38 +00001586 QualType result;
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001587
John McCallce889032011-01-18 08:40:38 +00001588 SplitQualType split = type.getSplitDesugaredType();
1589 const Type *ty = split.first;
1590 switch (ty->getTypeClass()) {
1591#define TYPE(Class, Base)
1592#define ABSTRACT_TYPE(Class, Base)
1593#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1594#include "clang/AST/TypeNodes.def"
1595 llvm_unreachable("didn't desugar past all non-canonical types?");
1596
1597 // These types should never be variably-modified.
1598 case Type::Builtin:
1599 case Type::Complex:
1600 case Type::Vector:
1601 case Type::ExtVector:
1602 case Type::DependentSizedExtVector:
1603 case Type::ObjCObject:
1604 case Type::ObjCInterface:
1605 case Type::ObjCObjectPointer:
1606 case Type::Record:
1607 case Type::Enum:
1608 case Type::UnresolvedUsing:
1609 case Type::TypeOfExpr:
1610 case Type::TypeOf:
1611 case Type::Decltype:
Sean Huntca63c202011-05-24 22:41:36 +00001612 case Type::UnaryTransform:
John McCallce889032011-01-18 08:40:38 +00001613 case Type::DependentName:
1614 case Type::InjectedClassName:
1615 case Type::TemplateSpecialization:
1616 case Type::DependentTemplateSpecialization:
1617 case Type::TemplateTypeParm:
1618 case Type::SubstTemplateTypeParmPack:
Richard Smith34b41d92011-02-20 03:19:35 +00001619 case Type::Auto:
John McCallce889032011-01-18 08:40:38 +00001620 case Type::PackExpansion:
1621 llvm_unreachable("type should never be variably-modified");
1622
1623 // These types can be variably-modified but should never need to
1624 // further decay.
1625 case Type::FunctionNoProto:
1626 case Type::FunctionProto:
1627 case Type::BlockPointer:
1628 case Type::MemberPointer:
1629 return type;
1630
1631 // These types can be variably-modified. All these modifications
1632 // preserve structure except as noted by comments.
1633 // TODO: if we ever care about optimizing VLAs, there are no-op
1634 // optimizations available here.
1635 case Type::Pointer:
1636 result = getPointerType(getVariableArrayDecayedType(
1637 cast<PointerType>(ty)->getPointeeType()));
1638 break;
1639
1640 case Type::LValueReference: {
1641 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1642 result = getLValueReferenceType(
1643 getVariableArrayDecayedType(lv->getPointeeType()),
1644 lv->isSpelledAsLValue());
1645 break;
1646 }
1647
1648 case Type::RValueReference: {
1649 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1650 result = getRValueReferenceType(
1651 getVariableArrayDecayedType(lv->getPointeeType()));
1652 break;
1653 }
1654
1655 case Type::ConstantArray: {
1656 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1657 result = getConstantArrayType(
1658 getVariableArrayDecayedType(cat->getElementType()),
1659 cat->getSize(),
1660 cat->getSizeModifier(),
1661 cat->getIndexTypeCVRQualifiers());
1662 break;
1663 }
1664
1665 case Type::DependentSizedArray: {
1666 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1667 result = getDependentSizedArrayType(
1668 getVariableArrayDecayedType(dat->getElementType()),
1669 dat->getSizeExpr(),
1670 dat->getSizeModifier(),
1671 dat->getIndexTypeCVRQualifiers(),
1672 dat->getBracketsRange());
1673 break;
1674 }
1675
1676 // Turn incomplete types into [*] types.
1677 case Type::IncompleteArray: {
1678 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1679 result = getVariableArrayType(
1680 getVariableArrayDecayedType(iat->getElementType()),
1681 /*size*/ 0,
1682 ArrayType::Normal,
1683 iat->getIndexTypeCVRQualifiers(),
1684 SourceRange());
1685 break;
1686 }
1687
1688 // Turn VLA types into [*] types.
1689 case Type::VariableArray: {
1690 const VariableArrayType *vat = cast<VariableArrayType>(ty);
1691 result = getVariableArrayType(
1692 getVariableArrayDecayedType(vat->getElementType()),
1693 /*size*/ 0,
1694 ArrayType::Star,
1695 vat->getIndexTypeCVRQualifiers(),
1696 vat->getBracketsRange());
1697 break;
1698 }
1699 }
1700
1701 // Apply the top-level qualifiers from the original.
1702 return getQualifiedType(result, split.second);
1703}
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001704
Steve Naroffbdbf7b02007-08-30 18:14:25 +00001705/// getVariableArrayType - Returns a non-unique reference to the type for a
1706/// variable array of the specified element type.
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00001707QualType ASTContext::getVariableArrayType(QualType EltTy,
1708 Expr *NumElts,
Steve Naroffc9406122007-08-30 18:10:14 +00001709 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001710 unsigned IndexTypeQuals,
Jay Foad4ba2a172011-01-12 09:06:06 +00001711 SourceRange Brackets) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001712 // Since we don't unique expressions, it isn't possible to unique VLA's
1713 // that have an expression provided for their size.
John McCall3b657512011-01-19 10:06:00 +00001714 QualType Canon;
Douglas Gregor715e9c82010-05-23 16:10:32 +00001715
John McCall3b657512011-01-19 10:06:00 +00001716 // Be sure to pull qualifiers off the element type.
1717 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1718 SplitQualType canonSplit = getCanonicalType(EltTy).split();
1719 Canon = getVariableArrayType(QualType(canonSplit.first, 0), NumElts, ASM,
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001720 IndexTypeQuals, Brackets);
John McCall3b657512011-01-19 10:06:00 +00001721 Canon = getQualifiedType(Canon, canonSplit.second);
Douglas Gregor715e9c82010-05-23 16:10:32 +00001722 }
1723
John McCall6b304a02009-09-24 23:30:46 +00001724 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara63e7d252011-01-27 19:55:10 +00001725 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001726
1727 VariableArrayTypes.push_back(New);
1728 Types.push_back(New);
1729 return QualType(New, 0);
1730}
1731
Douglas Gregor898574e2008-12-05 23:32:09 +00001732/// getDependentSizedArrayType - Returns a non-unique reference to
1733/// the type for a dependently-sized array of the specified element
Douglas Gregor04d4bee2009-07-31 00:23:35 +00001734/// type.
John McCall3b657512011-01-19 10:06:00 +00001735QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1736 Expr *numElements,
Douglas Gregor898574e2008-12-05 23:32:09 +00001737 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001738 unsigned elementTypeQuals,
1739 SourceRange brackets) const {
1740 assert((!numElements || numElements->isTypeDependent() ||
1741 numElements->isValueDependent()) &&
Douglas Gregor898574e2008-12-05 23:32:09 +00001742 "Size must be type- or value-dependent!");
1743
John McCall3b657512011-01-19 10:06:00 +00001744 // Dependently-sized array types that do not have a specified number
1745 // of elements will have their sizes deduced from a dependent
1746 // initializer. We do no canonicalization here at all, which is okay
1747 // because they can't be used in most locations.
1748 if (!numElements) {
1749 DependentSizedArrayType *newType
1750 = new (*this, TypeAlignment)
1751 DependentSizedArrayType(*this, elementType, QualType(),
1752 numElements, ASM, elementTypeQuals,
1753 brackets);
1754 Types.push_back(newType);
1755 return QualType(newType, 0);
1756 }
1757
1758 // Otherwise, we actually build a new type every time, but we
1759 // also build a canonical type.
1760
1761 SplitQualType canonElementType = getCanonicalType(elementType).split();
1762
1763 void *insertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00001764 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001765 DependentSizedArrayType::Profile(ID, *this,
1766 QualType(canonElementType.first, 0),
1767 ASM, elementTypeQuals, numElements);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001768
John McCall3b657512011-01-19 10:06:00 +00001769 // Look for an existing type with these properties.
1770 DependentSizedArrayType *canonTy =
1771 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001772
John McCall3b657512011-01-19 10:06:00 +00001773 // If we don't have one, build one.
1774 if (!canonTy) {
1775 canonTy = new (*this, TypeAlignment)
1776 DependentSizedArrayType(*this, QualType(canonElementType.first, 0),
1777 QualType(), numElements, ASM, elementTypeQuals,
1778 brackets);
1779 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1780 Types.push_back(canonTy);
Douglas Gregorcb78d882009-11-19 18:03:26 +00001781 }
1782
John McCall3b657512011-01-19 10:06:00 +00001783 // Apply qualifiers from the element type to the array.
1784 QualType canon = getQualifiedType(QualType(canonTy,0),
1785 canonElementType.second);
Mike Stump1eb44332009-09-09 15:08:12 +00001786
John McCall3b657512011-01-19 10:06:00 +00001787 // If we didn't need extra canonicalization for the element type,
1788 // then just use that as our result.
1789 if (QualType(canonElementType.first, 0) == elementType)
1790 return canon;
1791
1792 // Otherwise, we need to build a type which follows the spelling
1793 // of the element type.
1794 DependentSizedArrayType *sugaredType
1795 = new (*this, TypeAlignment)
1796 DependentSizedArrayType(*this, elementType, canon, numElements,
1797 ASM, elementTypeQuals, brackets);
1798 Types.push_back(sugaredType);
1799 return QualType(sugaredType, 0);
Douglas Gregor898574e2008-12-05 23:32:09 +00001800}
1801
John McCall3b657512011-01-19 10:06:00 +00001802QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanc5773c42008-02-15 18:16:39 +00001803 ArrayType::ArraySizeModifier ASM,
John McCall3b657512011-01-19 10:06:00 +00001804 unsigned elementTypeQuals) const {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001805 llvm::FoldingSetNodeID ID;
John McCall3b657512011-01-19 10:06:00 +00001806 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001807
John McCall3b657512011-01-19 10:06:00 +00001808 void *insertPos = 0;
1809 if (IncompleteArrayType *iat =
1810 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1811 return QualType(iat, 0);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001812
1813 // If the element type isn't canonical, this won't be a canonical type
John McCall3b657512011-01-19 10:06:00 +00001814 // either, so fill in the canonical type field. We also have to pull
1815 // qualifiers off the element type.
1816 QualType canon;
Eli Friedmanc5773c42008-02-15 18:16:39 +00001817
John McCall3b657512011-01-19 10:06:00 +00001818 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1819 SplitQualType canonSplit = getCanonicalType(elementType).split();
1820 canon = getIncompleteArrayType(QualType(canonSplit.first, 0),
1821 ASM, elementTypeQuals);
1822 canon = getQualifiedType(canon, canonSplit.second);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001823
1824 // Get the new insert position for the node we care about.
John McCall3b657512011-01-19 10:06:00 +00001825 IncompleteArrayType *existing =
1826 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1827 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek2bd24ba2007-10-29 23:37:31 +00001828 }
Eli Friedmanc5773c42008-02-15 18:16:39 +00001829
John McCall3b657512011-01-19 10:06:00 +00001830 IncompleteArrayType *newType = new (*this, TypeAlignment)
1831 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanc5773c42008-02-15 18:16:39 +00001832
John McCall3b657512011-01-19 10:06:00 +00001833 IncompleteArrayTypes.InsertNode(newType, insertPos);
1834 Types.push_back(newType);
1835 return QualType(newType, 0);
Steve Narofffb22d962007-08-30 01:06:46 +00001836}
1837
Steve Naroff73322922007-07-18 18:00:27 +00001838/// getVectorType - Return the unique reference to a vector type of
1839/// the specified element type and size. VectorType must be a built-in type.
John Thompson82287d12010-02-05 00:12:22 +00001840QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad4ba2a172011-01-12 09:06:06 +00001841 VectorType::VectorKind VecKind) const {
John McCall3b657512011-01-19 10:06:00 +00001842 assert(vecType->isBuiltinType());
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 // Check if we've already instantiated a vector of this type.
1845 llvm::FoldingSetNodeID ID;
Bob Wilsone86d78c2010-11-10 21:56:12 +00001846 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner788b0fd2010-06-23 06:00:24 +00001847
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 void *InsertPos = 0;
1849 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1850 return QualType(VTP, 0);
1851
1852 // If the element type isn't canonical, this won't be a canonical type either,
1853 // so fill in the canonical type field.
1854 QualType Canonical;
Douglas Gregor255210e2010-08-06 10:14:59 +00001855 if (!vecType.isCanonical()) {
Bob Wilson231da7e2010-11-16 00:32:20 +00001856 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 // Get the new insert position for the node we care about.
1859 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001860 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001861 }
John McCall6b304a02009-09-24 23:30:46 +00001862 VectorType *New = new (*this, TypeAlignment)
Bob Wilsone86d78c2010-11-10 21:56:12 +00001863 VectorType(vecType, NumElts, Canonical, VecKind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001864 VectorTypes.InsertNode(New, InsertPos);
1865 Types.push_back(New);
1866 return QualType(New, 0);
1867}
1868
Nate Begeman213541a2008-04-18 23:10:10 +00001869/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff73322922007-07-18 18:00:27 +00001870/// the specified element type and size. VectorType must be a built-in type.
Jay Foad4ba2a172011-01-12 09:06:06 +00001871QualType
1872ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001873 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Steve Naroff73322922007-07-18 18:00:27 +00001875 // Check if we've already instantiated a vector of this type.
1876 llvm::FoldingSetNodeID ID;
Chris Lattner788b0fd2010-06-23 06:00:24 +00001877 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001878 VectorType::GenericVector);
Steve Naroff73322922007-07-18 18:00:27 +00001879 void *InsertPos = 0;
1880 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1881 return QualType(VTP, 0);
1882
1883 // If the element type isn't canonical, this won't be a canonical type either,
1884 // so fill in the canonical type field.
1885 QualType Canonical;
John McCall467b27b2009-10-22 20:10:53 +00001886 if (!vecType.isCanonical()) {
Nate Begeman213541a2008-04-18 23:10:10 +00001887 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Steve Naroff73322922007-07-18 18:00:27 +00001889 // Get the new insert position for the node we care about.
1890 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001891 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff73322922007-07-18 18:00:27 +00001892 }
John McCall6b304a02009-09-24 23:30:46 +00001893 ExtVectorType *New = new (*this, TypeAlignment)
1894 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff73322922007-07-18 18:00:27 +00001895 VectorTypes.InsertNode(New, InsertPos);
1896 Types.push_back(New);
1897 return QualType(New, 0);
1898}
1899
Jay Foad4ba2a172011-01-12 09:06:06 +00001900QualType
1901ASTContext::getDependentSizedExtVectorType(QualType vecType,
1902 Expr *SizeExpr,
1903 SourceLocation AttrLoc) const {
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001904 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001905 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001906 SizeExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001908 void *InsertPos = 0;
1909 DependentSizedExtVectorType *Canon
1910 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1911 DependentSizedExtVectorType *New;
1912 if (Canon) {
1913 // We already have a canonical version of this array type; use it as
1914 // the canonical type for a newly-built type.
John McCall6b304a02009-09-24 23:30:46 +00001915 New = new (*this, TypeAlignment)
1916 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1917 SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001918 } else {
1919 QualType CanonVecTy = getCanonicalType(vecType);
1920 if (CanonVecTy == vecType) {
John McCall6b304a02009-09-24 23:30:46 +00001921 New = new (*this, TypeAlignment)
1922 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1923 AttrLoc);
Douglas Gregor789b1f62010-02-04 18:10:26 +00001924
1925 DependentSizedExtVectorType *CanonCheck
1926 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1927 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1928 (void)CanonCheck;
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001929 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1930 } else {
1931 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1932 SourceLocation());
John McCall6b304a02009-09-24 23:30:46 +00001933 New = new (*this, TypeAlignment)
1934 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor2ec09f12009-07-31 03:54:25 +00001935 }
1936 }
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00001938 Types.push_back(New);
1939 return QualType(New, 0);
1940}
1941
Douglas Gregor72564e72009-02-26 23:50:07 +00001942/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Reid Spencer5f016e22007-07-11 17:01:13 +00001943///
Jay Foad4ba2a172011-01-12 09:06:06 +00001944QualType
1945ASTContext::getFunctionNoProtoType(QualType ResultTy,
1946 const FunctionType::ExtInfo &Info) const {
Roman Divackycfe9af22011-03-01 17:40:53 +00001947 const CallingConv DefaultCC = Info.getCC();
1948 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
1949 CC_X86StdCall : DefaultCC;
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 // Unique functions, to guarantee there is only one function of a particular
1951 // structure.
1952 llvm::FoldingSetNodeID ID;
Rafael Espindola264ba482010-03-30 20:24:48 +00001953 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Reid Spencer5f016e22007-07-11 17:01:13 +00001955 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001956 if (FunctionNoProtoType *FT =
Douglas Gregor72564e72009-02-26 23:50:07 +00001957 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001958 return QualType(FT, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Reid Spencer5f016e22007-07-11 17:01:13 +00001960 QualType Canonical;
Douglas Gregorab8bbf42010-01-18 17:14:39 +00001961 if (!ResultTy.isCanonical() ||
John McCall04a67a62010-02-05 21:31:56 +00001962 getCanonicalCallConv(CallConv) != CallConv) {
Rafael Espindola264ba482010-03-30 20:24:48 +00001963 Canonical =
1964 getFunctionNoProtoType(getCanonicalType(ResultTy),
1965 Info.withCallingConv(getCanonicalCallConv(CallConv)));
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00001968 FunctionNoProtoType *NewIP =
1969 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001970 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 }
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Roman Divackycfe9af22011-03-01 17:40:53 +00001973 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
John McCall6b304a02009-09-24 23:30:46 +00001974 FunctionNoProtoType *New = new (*this, TypeAlignment)
Roman Divackycfe9af22011-03-01 17:40:53 +00001975 FunctionNoProtoType(ResultTy, Canonical, newInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 Types.push_back(New);
Douglas Gregor72564e72009-02-26 23:50:07 +00001977 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 return QualType(New, 0);
1979}
1980
1981/// getFunctionType - Return a normal function type with a typed argument
1982/// list. isVariadic indicates whether the argument list includes '...'.
Jay Foad4ba2a172011-01-12 09:06:06 +00001983QualType
1984ASTContext::getFunctionType(QualType ResultTy,
1985 const QualType *ArgArray, unsigned NumArgs,
1986 const FunctionProtoType::ExtProtoInfo &EPI) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 // Unique functions, to guarantee there is only one function of a particular
1988 // structure.
1989 llvm::FoldingSetNodeID ID;
Sebastian Redl8026f6d2011-03-13 17:09:40 +00001990 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
Reid Spencer5f016e22007-07-11 17:01:13 +00001991
1992 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001993 if (FunctionProtoType *FTP =
Douglas Gregor72564e72009-02-26 23:50:07 +00001994 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 return QualType(FTP, 0);
Sebastian Redl465226e2009-05-27 22:11:52 +00001996
1997 // Determine whether the type being created is already canonical or not.
Sebastian Redl8b5b4092011-03-06 10:52:04 +00001998 bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002000 if (!ArgArray[i].isCanonicalAsParam())
Reid Spencer5f016e22007-07-11 17:01:13 +00002001 isCanonical = false;
2002
Roman Divackycfe9af22011-03-01 17:40:53 +00002003 const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2004 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2005 CC_X86StdCall : DefaultCC;
John McCalle23cf432010-12-14 08:05:40 +00002006
Reid Spencer5f016e22007-07-11 17:01:13 +00002007 // If this type isn't canonical, get the canonical version of it.
Sebastian Redl465226e2009-05-27 22:11:52 +00002008 // The exception spec is not part of the canonical type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 QualType Canonical;
John McCall04a67a62010-02-05 21:31:56 +00002010 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002011 SmallVector<QualType, 16> CanonicalArgs;
Reid Spencer5f016e22007-07-11 17:01:13 +00002012 CanonicalArgs.reserve(NumArgs);
2013 for (unsigned i = 0; i != NumArgs; ++i)
John McCall54e14c42009-10-22 22:37:11 +00002014 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl465226e2009-05-27 22:11:52 +00002015
John McCalle23cf432010-12-14 08:05:40 +00002016 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Sebastian Redl8b5b4092011-03-06 10:52:04 +00002017 CanonicalEPI.ExceptionSpecType = EST_None;
2018 CanonicalEPI.NumExceptions = 0;
John McCalle23cf432010-12-14 08:05:40 +00002019 CanonicalEPI.ExtInfo
2020 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2021
Chris Lattnerf52ab252008-04-06 22:59:24 +00002022 Canonical = getFunctionType(getCanonicalType(ResultTy),
Jay Foadbeaaccd2009-05-21 09:52:38 +00002023 CanonicalArgs.data(), NumArgs,
John McCalle23cf432010-12-14 08:05:40 +00002024 CanonicalEPI);
Sebastian Redl465226e2009-05-27 22:11:52 +00002025
Reid Spencer5f016e22007-07-11 17:01:13 +00002026 // Get the new insert position for the node we care about.
Douglas Gregor72564e72009-02-26 23:50:07 +00002027 FunctionProtoType *NewIP =
2028 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002029 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 }
Sebastian Redl465226e2009-05-27 22:11:52 +00002031
John McCallf85e1932011-06-15 23:02:42 +00002032 // FunctionProtoType objects are allocated with extra bytes after
2033 // them for three variable size arrays at the end:
2034 // - parameter types
2035 // - exception types
2036 // - consumed-arguments flags
2037 // Instead of the exception types, there could be a noexcept
2038 // expression.
John McCalle23cf432010-12-14 08:05:40 +00002039 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redl60618fa2011-03-12 11:50:43 +00002040 NumArgs * sizeof(QualType);
2041 if (EPI.ExceptionSpecType == EST_Dynamic)
2042 Size += EPI.NumExceptions * sizeof(QualType);
2043 else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002044 Size += sizeof(Expr*);
Sebastian Redl60618fa2011-03-12 11:50:43 +00002045 }
John McCallf85e1932011-06-15 23:02:42 +00002046 if (EPI.ConsumedArguments)
2047 Size += NumArgs * sizeof(bool);
2048
John McCalle23cf432010-12-14 08:05:40 +00002049 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divackycfe9af22011-03-01 17:40:53 +00002050 FunctionProtoType::ExtProtoInfo newEPI = EPI;
2051 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
Sebastian Redl8026f6d2011-03-13 17:09:40 +00002052 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
Reid Spencer5f016e22007-07-11 17:01:13 +00002053 Types.push_back(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +00002054 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 return QualType(FTP, 0);
2056}
2057
John McCall3cb0ebd2010-03-10 03:28:59 +00002058#ifndef NDEBUG
2059static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2060 if (!isa<CXXRecordDecl>(D)) return false;
2061 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2062 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2063 return true;
2064 if (RD->getDescribedClassTemplate() &&
2065 !isa<ClassTemplateSpecializationDecl>(RD))
2066 return true;
2067 return false;
2068}
2069#endif
2070
2071/// getInjectedClassNameType - Return the unique reference to the
2072/// injected class name type for the specified templated declaration.
2073QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00002074 QualType TST) const {
John McCall3cb0ebd2010-03-10 03:28:59 +00002075 assert(NeedsInjectedClassNameType(Decl));
2076 if (Decl->TypeForDecl) {
2077 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Argyrios Kyrtzidis37ffed32010-07-02 11:55:32 +00002078 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002079 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2080 Decl->TypeForDecl = PrevDecl->TypeForDecl;
2081 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2082 } else {
John McCallf4c73712011-01-19 06:33:43 +00002083 Type *newType =
John McCall31f17ec2010-04-27 00:57:59 +00002084 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCallf4c73712011-01-19 06:33:43 +00002085 Decl->TypeForDecl = newType;
2086 Types.push_back(newType);
John McCall3cb0ebd2010-03-10 03:28:59 +00002087 }
2088 return QualType(Decl->TypeForDecl, 0);
2089}
2090
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002091/// getTypeDeclType - Return the unique reference to the type for the
2092/// specified type declaration.
Jay Foad4ba2a172011-01-12 09:06:06 +00002093QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis1e6759e2008-10-16 16:50:47 +00002094 assert(Decl && "Passed null for Decl param");
John McCallbecb8d52010-03-10 06:48:02 +00002095 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Richard Smith162e1c12011-04-15 14:24:37 +00002097 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002098 return getTypedefType(Typedef);
John McCallbecb8d52010-03-10 06:48:02 +00002099
John McCallbecb8d52010-03-10 06:48:02 +00002100 assert(!isa<TemplateTypeParmDecl>(Decl) &&
2101 "Template type parameter types are always available.");
2102
John McCall19c85762010-02-16 03:57:14 +00002103 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002104 assert(!Record->getPreviousDeclaration() &&
2105 "struct/union has previous declaration");
2106 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002107 return getRecordType(Record);
John McCall19c85762010-02-16 03:57:14 +00002108 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
John McCallbecb8d52010-03-10 06:48:02 +00002109 assert(!Enum->getPreviousDeclaration() &&
2110 "enum has previous declaration");
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002111 return getEnumType(Enum);
John McCall19c85762010-02-16 03:57:14 +00002112 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCalled976492009-12-04 22:46:56 +00002113 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCallf4c73712011-01-19 06:33:43 +00002114 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2115 Decl->TypeForDecl = newType;
2116 Types.push_back(newType);
Mike Stump9fdbab32009-07-31 02:02:20 +00002117 } else
John McCallbecb8d52010-03-10 06:48:02 +00002118 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002119
Argyrios Kyrtzidis49aa7ff2008-08-07 20:55:28 +00002120 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor2ce52f32008-04-13 21:07:44 +00002121}
2122
Reid Spencer5f016e22007-07-11 17:01:13 +00002123/// getTypedefType - Return the unique reference to the type for the
Richard Smith162e1c12011-04-15 14:24:37 +00002124/// specified typedef name decl.
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002125QualType
Richard Smith162e1c12011-04-15 14:24:37 +00002126ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2127 QualType Canonical) const {
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002130 if (Canonical.isNull())
2131 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCallf4c73712011-01-19 06:33:43 +00002132 TypedefType *newType = new(*this, TypeAlignment)
John McCall6b304a02009-09-24 23:30:46 +00002133 TypedefType(Type::Typedef, Decl, Canonical);
John McCallf4c73712011-01-19 06:33:43 +00002134 Decl->TypeForDecl = newType;
2135 Types.push_back(newType);
2136 return QualType(newType, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002137}
2138
Jay Foad4ba2a172011-01-12 09:06:06 +00002139QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002140 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2141
2142 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration())
2143 if (PrevDecl->TypeForDecl)
2144 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2145
John McCallf4c73712011-01-19 06:33:43 +00002146 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2147 Decl->TypeForDecl = newType;
2148 Types.push_back(newType);
2149 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002150}
2151
Jay Foad4ba2a172011-01-12 09:06:06 +00002152QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002153 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2154
2155 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration())
2156 if (PrevDecl->TypeForDecl)
2157 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2158
John McCallf4c73712011-01-19 06:33:43 +00002159 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2160 Decl->TypeForDecl = newType;
2161 Types.push_back(newType);
2162 return QualType(newType, 0);
Argyrios Kyrtzidis400f5122010-07-04 21:44:47 +00002163}
2164
John McCall9d156a72011-01-06 01:58:22 +00002165QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2166 QualType modifiedType,
2167 QualType equivalentType) {
2168 llvm::FoldingSetNodeID id;
2169 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2170
2171 void *insertPos = 0;
2172 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2173 if (type) return QualType(type, 0);
2174
2175 QualType canon = getCanonicalType(equivalentType);
2176 type = new (*this, TypeAlignment)
2177 AttributedType(canon, attrKind, modifiedType, equivalentType);
2178
2179 Types.push_back(type);
2180 AttributedTypes.InsertNode(type, insertPos);
2181
2182 return QualType(type, 0);
2183}
2184
2185
John McCall49a832b2009-10-18 09:09:24 +00002186/// \brief Retrieve a substitution-result type.
2187QualType
2188ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad4ba2a172011-01-12 09:06:06 +00002189 QualType Replacement) const {
John McCall467b27b2009-10-22 20:10:53 +00002190 assert(Replacement.isCanonical()
John McCall49a832b2009-10-18 09:09:24 +00002191 && "replacement types must always be canonical");
2192
2193 llvm::FoldingSetNodeID ID;
2194 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2195 void *InsertPos = 0;
2196 SubstTemplateTypeParmType *SubstParm
2197 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2198
2199 if (!SubstParm) {
2200 SubstParm = new (*this, TypeAlignment)
2201 SubstTemplateTypeParmType(Parm, Replacement);
2202 Types.push_back(SubstParm);
2203 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2204 }
2205
2206 return QualType(SubstParm, 0);
2207}
2208
Douglas Gregorc3069d62011-01-14 02:55:32 +00002209/// \brief Retrieve a
2210QualType ASTContext::getSubstTemplateTypeParmPackType(
2211 const TemplateTypeParmType *Parm,
2212 const TemplateArgument &ArgPack) {
2213#ifndef NDEBUG
2214 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2215 PEnd = ArgPack.pack_end();
2216 P != PEnd; ++P) {
2217 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2218 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2219 }
2220#endif
2221
2222 llvm::FoldingSetNodeID ID;
2223 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2224 void *InsertPos = 0;
2225 if (SubstTemplateTypeParmPackType *SubstParm
2226 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2227 return QualType(SubstParm, 0);
2228
2229 QualType Canon;
2230 if (!Parm->isCanonicalUnqualified()) {
2231 Canon = getCanonicalType(QualType(Parm, 0));
2232 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2233 ArgPack);
2234 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2235 }
2236
2237 SubstTemplateTypeParmPackType *SubstParm
2238 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2239 ArgPack);
2240 Types.push_back(SubstParm);
2241 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2242 return QualType(SubstParm, 0);
2243}
2244
Douglas Gregorfab9d672009-02-05 23:33:38 +00002245/// \brief Retrieve the template type parameter type for a template
Mike Stump1eb44332009-09-09 15:08:12 +00002246/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002247/// name.
Mike Stump1eb44332009-09-09 15:08:12 +00002248QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002249 bool ParameterPack,
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002250 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregorfab9d672009-02-05 23:33:38 +00002251 llvm::FoldingSetNodeID ID;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002252 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002253 void *InsertPos = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002254 TemplateTypeParmType *TypeParm
Douglas Gregorfab9d672009-02-05 23:33:38 +00002255 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2256
2257 if (TypeParm)
2258 return QualType(TypeParm, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002259
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002260 if (TTPDecl) {
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002261 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00002262 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002263
2264 TemplateTypeParmType *TypeCheck
2265 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2266 assert(!TypeCheck && "Template type parameter canonical type broken");
2267 (void)TypeCheck;
Anders Carlsson76e4ce42009-06-16 00:30:48 +00002268 } else
John McCall6b304a02009-09-24 23:30:46 +00002269 TypeParm = new (*this, TypeAlignment)
2270 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregorfab9d672009-02-05 23:33:38 +00002271
2272 Types.push_back(TypeParm);
2273 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2274
2275 return QualType(TypeParm, 0);
2276}
2277
John McCall3cb0ebd2010-03-10 03:28:59 +00002278TypeSourceInfo *
2279ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2280 SourceLocation NameLoc,
2281 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002282 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002283 assert(!Name.getAsDependentTemplateName() &&
2284 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002285 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCall3cb0ebd2010-03-10 03:28:59 +00002286
2287 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2288 TemplateSpecializationTypeLoc TL
2289 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2290 TL.setTemplateNameLoc(NameLoc);
2291 TL.setLAngleLoc(Args.getLAngleLoc());
2292 TL.setRAngleLoc(Args.getRAngleLoc());
2293 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2294 TL.setArgLocInfo(i, Args[i].getLocInfo());
2295 return DI;
2296}
2297
Mike Stump1eb44332009-09-09 15:08:12 +00002298QualType
Douglas Gregor7532dc62009-03-30 22:58:21 +00002299ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCalld5532b62009-11-23 01:53:49 +00002300 const TemplateArgumentListInfo &Args,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002301 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002302 assert(!Template.getAsDependentTemplateName() &&
2303 "No dependent template names here!");
2304
John McCalld5532b62009-11-23 01:53:49 +00002305 unsigned NumArgs = Args.size();
2306
Chris Lattner5f9e2722011-07-23 10:55:15 +00002307 SmallVector<TemplateArgument, 4> ArgVec;
John McCall833ca992009-10-29 08:12:44 +00002308 ArgVec.reserve(NumArgs);
2309 for (unsigned i = 0; i != NumArgs; ++i)
2310 ArgVec.push_back(Args[i].getArgument());
2311
John McCall31f17ec2010-04-27 00:57:59 +00002312 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002313 Underlying);
John McCall833ca992009-10-29 08:12:44 +00002314}
2315
2316QualType
2317ASTContext::getTemplateSpecializationType(TemplateName Template,
Douglas Gregor7532dc62009-03-30 22:58:21 +00002318 const TemplateArgument *Args,
2319 unsigned NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002320 QualType Underlying) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002321 assert(!Template.getAsDependentTemplateName() &&
2322 "No dependent template names here!");
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002323 // Look through qualified template names.
2324 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2325 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002326
Richard Smith3e4c6c42011-05-05 21:57:07 +00002327 bool isTypeAlias =
2328 Template.getAsTemplateDecl() &&
2329 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2330
2331 QualType CanonType;
2332 if (!Underlying.isNull())
2333 CanonType = getCanonicalType(Underlying);
2334 else {
2335 assert(!isTypeAlias &&
2336 "Underlying type for template alias must be computed by caller");
2337 CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2338 NumArgs);
2339 }
Douglas Gregorfc705b82009-02-26 22:19:44 +00002340
Douglas Gregor1275ae02009-07-28 23:00:59 +00002341 // Allocate the (non-canonical) template specialization type, but don't
2342 // try to unique it: these types typically have location information that
2343 // we don't unique and don't want to lose.
Richard Smith3e4c6c42011-05-05 21:57:07 +00002344 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2345 sizeof(TemplateArgument) * NumArgs +
2346 (isTypeAlias ? sizeof(QualType) : 0),
John McCall6b304a02009-09-24 23:30:46 +00002347 TypeAlignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002348 TemplateSpecializationType *Spec
John McCallef990012010-06-11 11:07:21 +00002349 = new (Mem) TemplateSpecializationType(Template,
John McCall31f17ec2010-04-27 00:57:59 +00002350 Args, NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002351 CanonType,
2352 isTypeAlias ? Underlying : QualType());
Mike Stump1eb44332009-09-09 15:08:12 +00002353
Douglas Gregor55f6b142009-02-09 18:46:07 +00002354 Types.push_back(Spec);
Mike Stump1eb44332009-09-09 15:08:12 +00002355 return QualType(Spec, 0);
Douglas Gregor55f6b142009-02-09 18:46:07 +00002356}
2357
Mike Stump1eb44332009-09-09 15:08:12 +00002358QualType
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002359ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2360 const TemplateArgument *Args,
Jay Foad4ba2a172011-01-12 09:06:06 +00002361 unsigned NumArgs) const {
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002362 assert(!Template.getAsDependentTemplateName() &&
2363 "No dependent template names here!");
Richard Smith3e4c6c42011-05-05 21:57:07 +00002364 assert((!Template.getAsTemplateDecl() ||
2365 !isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) &&
2366 "Underlying type for template alias must be computed by caller");
2367
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00002368 // Look through qualified template names.
2369 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2370 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregor7c3179c2011-02-28 18:50:33 +00002371
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002372 // Build the canonical template specialization type.
2373 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002374 SmallVector<TemplateArgument, 4> CanonArgs;
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002375 CanonArgs.reserve(NumArgs);
2376 for (unsigned I = 0; I != NumArgs; ++I)
2377 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2378
2379 // Determine whether this canonical template specialization type already
2380 // exists.
2381 llvm::FoldingSetNodeID ID;
2382 TemplateSpecializationType::Profile(ID, CanonTemplate,
2383 CanonArgs.data(), NumArgs, *this);
2384
2385 void *InsertPos = 0;
2386 TemplateSpecializationType *Spec
2387 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2388
2389 if (!Spec) {
2390 // Allocate a new canonical template specialization type.
2391 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2392 sizeof(TemplateArgument) * NumArgs),
2393 TypeAlignment);
2394 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2395 CanonArgs.data(), NumArgs,
Richard Smith3e4c6c42011-05-05 21:57:07 +00002396 QualType(), QualType());
Argyrios Kyrtzidis9763e222010-07-02 11:55:11 +00002397 Types.push_back(Spec);
2398 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2399 }
2400
2401 assert(Spec->isDependentType() &&
2402 "Non-dependent template-id type must have a canonical type");
2403 return QualType(Spec, 0);
2404}
2405
2406QualType
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002407ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2408 NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002409 QualType NamedType) const {
Douglas Gregore4e5b052009-03-19 00:18:19 +00002410 llvm::FoldingSetNodeID ID;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002411 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002412
2413 void *InsertPos = 0;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002414 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002415 if (T)
2416 return QualType(T, 0);
2417
Douglas Gregor789b1f62010-02-04 18:10:26 +00002418 QualType Canon = NamedType;
2419 if (!Canon.isCanonical()) {
2420 Canon = getCanonicalType(NamedType);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002421 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2422 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregor789b1f62010-02-04 18:10:26 +00002423 (void)CheckT;
2424 }
2425
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002426 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002427 Types.push_back(T);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002428 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregore4e5b052009-03-19 00:18:19 +00002429 return QualType(T, 0);
2430}
2431
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002432QualType
Jay Foad4ba2a172011-01-12 09:06:06 +00002433ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara075f8f12010-12-10 16:29:40 +00002434 llvm::FoldingSetNodeID ID;
2435 ParenType::Profile(ID, InnerType);
2436
2437 void *InsertPos = 0;
2438 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2439 if (T)
2440 return QualType(T, 0);
2441
2442 QualType Canon = InnerType;
2443 if (!Canon.isCanonical()) {
2444 Canon = getCanonicalType(InnerType);
2445 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2446 assert(!CheckT && "Paren canonical type broken");
2447 (void)CheckT;
2448 }
2449
2450 T = new (*this) ParenType(InnerType, Canon);
2451 Types.push_back(T);
2452 ParenTypes.InsertNode(T, InsertPos);
2453 return QualType(T, 0);
2454}
2455
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002456QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2457 NestedNameSpecifier *NNS,
2458 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002459 QualType Canon) const {
Douglas Gregord57959a2009-03-27 23:10:48 +00002460 assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2461
2462 if (Canon.isNull()) {
2463 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002464 ElaboratedTypeKeyword CanonKeyword = Keyword;
2465 if (Keyword == ETK_None)
2466 CanonKeyword = ETK_Typename;
2467
2468 if (CanonNNS != NNS || CanonKeyword != Keyword)
2469 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002470 }
2471
2472 llvm::FoldingSetNodeID ID;
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002473 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregord57959a2009-03-27 23:10:48 +00002474
2475 void *InsertPos = 0;
Douglas Gregor4714c122010-03-31 17:34:00 +00002476 DependentNameType *T
2477 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregord57959a2009-03-27 23:10:48 +00002478 if (T)
2479 return QualType(T, 0);
2480
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002481 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregord57959a2009-03-27 23:10:48 +00002482 Types.push_back(T);
Douglas Gregor4714c122010-03-31 17:34:00 +00002483 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002484 return QualType(T, 0);
Douglas Gregord57959a2009-03-27 23:10:48 +00002485}
2486
Mike Stump1eb44332009-09-09 15:08:12 +00002487QualType
John McCall33500952010-06-11 00:33:02 +00002488ASTContext::getDependentTemplateSpecializationType(
2489 ElaboratedTypeKeyword Keyword,
Douglas Gregor4a2023f2010-03-31 20:19:30 +00002490 NestedNameSpecifier *NNS,
John McCall33500952010-06-11 00:33:02 +00002491 const IdentifierInfo *Name,
Jay Foad4ba2a172011-01-12 09:06:06 +00002492 const TemplateArgumentListInfo &Args) const {
John McCall33500952010-06-11 00:33:02 +00002493 // TODO: avoid this copy
Chris Lattner5f9e2722011-07-23 10:55:15 +00002494 SmallVector<TemplateArgument, 16> ArgCopy;
John McCall33500952010-06-11 00:33:02 +00002495 for (unsigned I = 0, E = Args.size(); I != E; ++I)
2496 ArgCopy.push_back(Args[I].getArgument());
2497 return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2498 ArgCopy.size(),
2499 ArgCopy.data());
2500}
2501
2502QualType
2503ASTContext::getDependentTemplateSpecializationType(
2504 ElaboratedTypeKeyword Keyword,
2505 NestedNameSpecifier *NNS,
2506 const IdentifierInfo *Name,
2507 unsigned NumArgs,
Jay Foad4ba2a172011-01-12 09:06:06 +00002508 const TemplateArgument *Args) const {
Douglas Gregoraa2187d2011-02-28 00:04:36 +00002509 assert((!NNS || NNS->isDependent()) &&
2510 "nested-name-specifier must be dependent");
Douglas Gregor17343172009-04-01 00:28:59 +00002511
Douglas Gregor789b1f62010-02-04 18:10:26 +00002512 llvm::FoldingSetNodeID ID;
John McCall33500952010-06-11 00:33:02 +00002513 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2514 Name, NumArgs, Args);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002515
2516 void *InsertPos = 0;
John McCall33500952010-06-11 00:33:02 +00002517 DependentTemplateSpecializationType *T
2518 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002519 if (T)
2520 return QualType(T, 0);
2521
John McCall33500952010-06-11 00:33:02 +00002522 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregor789b1f62010-02-04 18:10:26 +00002523
John McCall33500952010-06-11 00:33:02 +00002524 ElaboratedTypeKeyword CanonKeyword = Keyword;
2525 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2526
2527 bool AnyNonCanonArgs = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002528 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCall33500952010-06-11 00:33:02 +00002529 for (unsigned I = 0; I != NumArgs; ++I) {
2530 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2531 if (!CanonArgs[I].structurallyEquals(Args[I]))
2532 AnyNonCanonArgs = true;
Douglas Gregor17343172009-04-01 00:28:59 +00002533 }
2534
John McCall33500952010-06-11 00:33:02 +00002535 QualType Canon;
2536 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2537 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2538 Name, NumArgs,
2539 CanonArgs.data());
2540
2541 // Find the insert position again.
2542 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2543 }
2544
2545 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2546 sizeof(TemplateArgument) * NumArgs),
2547 TypeAlignment);
John McCallef990012010-06-11 11:07:21 +00002548 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
John McCall33500952010-06-11 00:33:02 +00002549 Name, NumArgs, Args, Canon);
Douglas Gregor17343172009-04-01 00:28:59 +00002550 Types.push_back(T);
John McCall33500952010-06-11 00:33:02 +00002551 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00002552 return QualType(T, 0);
Douglas Gregor17343172009-04-01 00:28:59 +00002553}
2554
Douglas Gregorcded4f62011-01-14 17:04:44 +00002555QualType ASTContext::getPackExpansionType(QualType Pattern,
2556 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregor7536dd52010-12-20 02:24:11 +00002557 llvm::FoldingSetNodeID ID;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002558 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002559
2560 assert(Pattern->containsUnexpandedParameterPack() &&
2561 "Pack expansions must expand one or more parameter packs");
2562 void *InsertPos = 0;
2563 PackExpansionType *T
2564 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2565 if (T)
2566 return QualType(T, 0);
2567
2568 QualType Canon;
2569 if (!Pattern.isCanonical()) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00002570 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002571
2572 // Find the insert position again.
2573 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2574 }
2575
Douglas Gregorcded4f62011-01-14 17:04:44 +00002576 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregor7536dd52010-12-20 02:24:11 +00002577 Types.push_back(T);
2578 PackExpansionTypes.InsertNode(T, InsertPos);
2579 return QualType(T, 0);
2580}
2581
Chris Lattner88cb27a2008-04-07 04:56:42 +00002582/// CmpProtocolNames - Comparison predicate for sorting protocols
2583/// alphabetically.
2584static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2585 const ObjCProtocolDecl *RHS) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002586 return LHS->getDeclName() < RHS->getDeclName();
Chris Lattner88cb27a2008-04-07 04:56:42 +00002587}
2588
John McCallc12c5bb2010-05-15 11:32:37 +00002589static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
John McCall54e14c42009-10-22 22:37:11 +00002590 unsigned NumProtocols) {
2591 if (NumProtocols == 0) return true;
2592
2593 for (unsigned i = 1; i != NumProtocols; ++i)
2594 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2595 return false;
2596 return true;
2597}
2598
2599static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
Chris Lattner88cb27a2008-04-07 04:56:42 +00002600 unsigned &NumProtocols) {
2601 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Chris Lattner88cb27a2008-04-07 04:56:42 +00002603 // Sort protocols, keyed by name.
2604 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2605
2606 // Remove duplicates.
2607 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2608 NumProtocols = ProtocolsEnd-Protocols;
2609}
2610
John McCallc12c5bb2010-05-15 11:32:37 +00002611QualType ASTContext::getObjCObjectType(QualType BaseType,
2612 ObjCProtocolDecl * const *Protocols,
Jay Foad4ba2a172011-01-12 09:06:06 +00002613 unsigned NumProtocols) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002614 // If the base type is an interface and there aren't any protocols
2615 // to add, then the interface type will do just fine.
2616 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2617 return BaseType;
2618
2619 // Look in the folding set for an existing type.
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002620 llvm::FoldingSetNodeID ID;
John McCallc12c5bb2010-05-15 11:32:37 +00002621 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002622 void *InsertPos = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00002623 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2624 return QualType(QT, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002625
John McCallc12c5bb2010-05-15 11:32:37 +00002626 // Build the canonical type, which has the canonical base type and
2627 // a sorted-and-uniqued list of protocols.
John McCall54e14c42009-10-22 22:37:11 +00002628 QualType Canonical;
John McCallc12c5bb2010-05-15 11:32:37 +00002629 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2630 if (!ProtocolsSorted || !BaseType.isCanonical()) {
2631 if (!ProtocolsSorted) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002632 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
Benjamin Kramer02379412010-04-27 17:12:11 +00002633 Protocols + NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002634 unsigned UniqueCount = NumProtocols;
2635
John McCall54e14c42009-10-22 22:37:11 +00002636 SortAndUniqueProtocols(&Sorted[0], UniqueCount);
John McCallc12c5bb2010-05-15 11:32:37 +00002637 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2638 &Sorted[0], UniqueCount);
John McCall54e14c42009-10-22 22:37:11 +00002639 } else {
John McCallc12c5bb2010-05-15 11:32:37 +00002640 Canonical = getObjCObjectType(getCanonicalType(BaseType),
2641 Protocols, NumProtocols);
John McCall54e14c42009-10-22 22:37:11 +00002642 }
2643
2644 // Regenerate InsertPos.
John McCallc12c5bb2010-05-15 11:32:37 +00002645 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2646 }
2647
2648 unsigned Size = sizeof(ObjCObjectTypeImpl);
2649 Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2650 void *Mem = Allocate(Size, TypeAlignment);
2651 ObjCObjectTypeImpl *T =
2652 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2653
2654 Types.push_back(T);
2655 ObjCObjectTypes.InsertNode(T, InsertPos);
2656 return QualType(T, 0);
2657}
2658
2659/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2660/// the given object type.
Jay Foad4ba2a172011-01-12 09:06:06 +00002661QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCallc12c5bb2010-05-15 11:32:37 +00002662 llvm::FoldingSetNodeID ID;
2663 ObjCObjectPointerType::Profile(ID, ObjectT);
2664
2665 void *InsertPos = 0;
2666 if (ObjCObjectPointerType *QT =
2667 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2668 return QualType(QT, 0);
2669
2670 // Find the canonical object type.
2671 QualType Canonical;
2672 if (!ObjectT.isCanonical()) {
2673 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2674
2675 // Regenerate InsertPos.
John McCall54e14c42009-10-22 22:37:11 +00002676 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2677 }
2678
Douglas Gregorfd6a0882010-02-08 22:59:26 +00002679 // No match.
John McCallc12c5bb2010-05-15 11:32:37 +00002680 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2681 ObjCObjectPointerType *QType =
2682 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002684 Types.push_back(QType);
2685 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCallc12c5bb2010-05-15 11:32:37 +00002686 return QualType(QType, 0);
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002687}
Chris Lattner88cb27a2008-04-07 04:56:42 +00002688
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002689/// getObjCInterfaceType - Return the unique reference to the type for the
2690/// specified ObjC interface decl. The list of protocols is optional.
Jay Foad4ba2a172011-01-12 09:06:06 +00002691QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) const {
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002692 if (Decl->TypeForDecl)
2693 return QualType(Decl->TypeForDecl, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002694
Douglas Gregordeacbdc2010-08-11 12:19:30 +00002695 // FIXME: redeclarations?
2696 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2697 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2698 Decl->TypeForDecl = T;
2699 Types.push_back(T);
2700 return QualType(T, 0);
Fariborz Jahanian4b6c9052007-10-11 00:55:41 +00002701}
2702
Douglas Gregor72564e72009-02-26 23:50:07 +00002703/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2704/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroff9752f252007-08-01 18:02:17 +00002705/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump1eb44332009-09-09 15:08:12 +00002706/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002707/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002708QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002709 TypeOfExprType *toe;
Douglas Gregorb1975722009-07-30 23:18:24 +00002710 if (tofExpr->isTypeDependent()) {
2711 llvm::FoldingSetNodeID ID;
2712 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Douglas Gregorb1975722009-07-30 23:18:24 +00002714 void *InsertPos = 0;
2715 DependentTypeOfExprType *Canon
2716 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2717 if (Canon) {
2718 // We already have a "canonical" version of an identical, dependent
2719 // typeof(expr) type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002720 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregorb1975722009-07-30 23:18:24 +00002721 QualType((TypeOfExprType*)Canon, 0));
2722 }
2723 else {
2724 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002725 Canon
2726 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregorb1975722009-07-30 23:18:24 +00002727 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2728 toe = Canon;
2729 }
2730 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002731 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall6b304a02009-09-24 23:30:46 +00002732 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregordd0257c2009-07-08 00:03:05 +00002733 }
Steve Naroff9752f252007-08-01 18:02:17 +00002734 Types.push_back(toe);
2735 return QualType(toe, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002736}
2737
Steve Naroff9752f252007-08-01 18:02:17 +00002738/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
2739/// TypeOfType AST's. The only motivation to unique these nodes would be
2740/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002741/// an issue. This doesn't effect the type checker, since it operates
Steve Naroff9752f252007-08-01 18:02:17 +00002742/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002743QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattnerf52ab252008-04-06 22:59:24 +00002744 QualType Canonical = getCanonicalType(tofType);
John McCall6b304a02009-09-24 23:30:46 +00002745 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroff9752f252007-08-01 18:02:17 +00002746 Types.push_back(tot);
2747 return QualType(tot, 0);
Steve Naroffd1861fd2007-07-31 12:34:36 +00002748}
2749
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002750/// getDecltypeForExpr - Given an expr, will return the decltype for that
2751/// expression, according to the rules in C++0x [dcl.type.simple]p4
Jay Foad4ba2a172011-01-12 09:06:06 +00002752static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
Anders Carlssona07c33e2009-06-25 15:00:34 +00002753 if (e->isTypeDependent())
2754 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002756 // If e is an id expression or a class member access, decltype(e) is defined
2757 // as the type of the entity named by e.
2758 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2759 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2760 return VD->getType();
2761 }
2762 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2763 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2764 return FD->getType();
2765 }
2766 // If e is a function call or an invocation of an overloaded operator,
2767 // (parentheses around e are ignored), decltype(e) is defined as the
2768 // return type of that function.
2769 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2770 return CE->getCallReturnType();
Mike Stump1eb44332009-09-09 15:08:12 +00002771
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002772 QualType T = e->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002773
2774 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002775 // defined as T&, otherwise decltype(e) is defined as T.
John McCall7eb0a9e2010-11-24 05:12:34 +00002776 if (e->isLValue())
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002777 T = Context.getLValueReferenceType(T);
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Anders Carlsson60a9a2a2009-06-24 21:24:56 +00002779 return T;
2780}
2781
Anders Carlsson395b4752009-06-24 19:06:50 +00002782/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique
2783/// DecltypeType AST's. The only motivation to unique these nodes would be
2784/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
Mike Stump1eb44332009-09-09 15:08:12 +00002785/// an issue. This doesn't effect the type checker, since it operates
Anders Carlsson395b4752009-06-24 19:06:50 +00002786/// on canonical type's (which are always unique).
Jay Foad4ba2a172011-01-12 09:06:06 +00002787QualType ASTContext::getDecltypeType(Expr *e) const {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002788 DecltypeType *dt;
Douglas Gregor561f8122011-07-01 01:22:09 +00002789
2790 // C++0x [temp.type]p2:
2791 // If an expression e involves a template parameter, decltype(e) denotes a
2792 // unique dependent type. Two such decltype-specifiers refer to the same
2793 // type only if their expressions are equivalent (14.5.6.1).
2794 if (e->isInstantiationDependent()) {
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002795 llvm::FoldingSetNodeID ID;
2796 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002798 void *InsertPos = 0;
2799 DependentDecltypeType *Canon
2800 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2801 if (Canon) {
2802 // We already have a "canonical" version of an equivalent, dependent
2803 // decltype type. Use that as our canonical type.
John McCall6b304a02009-09-24 23:30:46 +00002804 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002805 QualType((DecltypeType*)Canon, 0));
2806 }
2807 else {
2808 // Build a new, canonical typeof(expr) type.
John McCall6b304a02009-09-24 23:30:46 +00002809 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregor9d702ae2009-07-30 23:36:40 +00002810 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2811 dt = Canon;
2812 }
2813 } else {
Douglas Gregordd0257c2009-07-08 00:03:05 +00002814 QualType T = getDecltypeForExpr(e, *this);
John McCall6b304a02009-09-24 23:30:46 +00002815 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
Douglas Gregordd0257c2009-07-08 00:03:05 +00002816 }
Anders Carlsson395b4752009-06-24 19:06:50 +00002817 Types.push_back(dt);
2818 return QualType(dt, 0);
2819}
2820
Sean Huntca63c202011-05-24 22:41:36 +00002821/// getUnaryTransformationType - We don't unique these, since the memory
2822/// savings are minimal and these are rare.
2823QualType ASTContext::getUnaryTransformType(QualType BaseType,
2824 QualType UnderlyingType,
2825 UnaryTransformType::UTTKind Kind)
2826 const {
2827 UnaryTransformType *Ty =
Douglas Gregor69d97752011-05-25 17:51:54 +00002828 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2829 Kind,
2830 UnderlyingType->isDependentType() ?
2831 QualType() : UnderlyingType);
Sean Huntca63c202011-05-24 22:41:36 +00002832 Types.push_back(Ty);
2833 return QualType(Ty, 0);
2834}
2835
Richard Smith483b9f32011-02-21 20:05:19 +00002836/// getAutoType - We only unique auto types after they've been deduced.
Richard Smith34b41d92011-02-20 03:19:35 +00002837QualType ASTContext::getAutoType(QualType DeducedType) const {
Richard Smith483b9f32011-02-21 20:05:19 +00002838 void *InsertPos = 0;
2839 if (!DeducedType.isNull()) {
2840 // Look in the folding set for an existing type.
2841 llvm::FoldingSetNodeID ID;
2842 AutoType::Profile(ID, DeducedType);
2843 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2844 return QualType(AT, 0);
2845 }
2846
2847 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2848 Types.push_back(AT);
2849 if (InsertPos)
2850 AutoTypes.InsertNode(AT, InsertPos);
2851 return QualType(AT, 0);
Richard Smith34b41d92011-02-20 03:19:35 +00002852}
2853
Richard Smithad762fc2011-04-14 22:09:26 +00002854/// getAutoDeductType - Get type pattern for deducing against 'auto'.
2855QualType ASTContext::getAutoDeductType() const {
2856 if (AutoDeductTy.isNull())
2857 AutoDeductTy = getAutoType(QualType());
2858 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
2859 return AutoDeductTy;
2860}
2861
2862/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
2863QualType ASTContext::getAutoRRefDeductType() const {
2864 if (AutoRRefDeductTy.isNull())
2865 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
2866 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
2867 return AutoRRefDeductTy;
2868}
2869
Reid Spencer5f016e22007-07-11 17:01:13 +00002870/// getTagDeclType - Return the unique reference to the type for the
2871/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad4ba2a172011-01-12 09:06:06 +00002872QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenekd778f882007-11-26 21:16:01 +00002873 assert (Decl);
Mike Stumpe607ed02009-08-07 18:05:12 +00002874 // FIXME: What is the design on getTagDeclType when it requires casting
2875 // away const? mutable?
2876 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002877}
2878
Mike Stump1eb44332009-09-09 15:08:12 +00002879/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2880/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2881/// needs to agree with the definition in <stddef.h>.
Anders Carlssona3ccda52009-12-12 00:26:23 +00002882CanQualType ASTContext::getSizeType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002883 return getFromTargetType(Target.getSizeType());
Reid Spencer5f016e22007-07-11 17:01:13 +00002884}
2885
Argyrios Kyrtzidis64c438a2008-08-09 16:51:54 +00002886/// getSignedWCharType - Return the type of "signed wchar_t".
2887/// Used when in C++, as a GCC extension.
2888QualType ASTContext::getSignedWCharType() const {
2889 // FIXME: derive from "Target" ?
2890 return WCharTy;
2891}
2892
2893/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2894/// Used when in C++, as a GCC extension.
2895QualType ASTContext::getUnsignedWCharType() const {
2896 // FIXME: derive from "Target" ?
2897 return UnsignedIntTy;
2898}
2899
Chris Lattner8b9023b2007-07-13 03:05:23 +00002900/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2901/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2902QualType ASTContext::getPointerDiffType() const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00002903 return getFromTargetType(Target.getPtrDiffType(0));
Chris Lattner8b9023b2007-07-13 03:05:23 +00002904}
2905
Chris Lattnere6327742008-04-02 05:18:44 +00002906//===----------------------------------------------------------------------===//
2907// Type Operators
2908//===----------------------------------------------------------------------===//
2909
Jay Foad4ba2a172011-01-12 09:06:06 +00002910CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCall54e14c42009-10-22 22:37:11 +00002911 // Push qualifiers into arrays, and then discard any remaining
2912 // qualifiers.
2913 T = getCanonicalType(T);
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00002914 T = getVariableArrayDecayedType(T);
John McCall54e14c42009-10-22 22:37:11 +00002915 const Type *Ty = T.getTypePtr();
John McCall54e14c42009-10-22 22:37:11 +00002916 QualType Result;
2917 if (isa<ArrayType>(Ty)) {
2918 Result = getArrayDecayedType(QualType(Ty,0));
2919 } else if (isa<FunctionType>(Ty)) {
2920 Result = getPointerType(QualType(Ty, 0));
2921 } else {
2922 Result = QualType(Ty, 0);
2923 }
2924
2925 return CanQualType::CreateUnsafe(Result);
2926}
2927
John McCall62c28c82011-01-18 07:41:22 +00002928QualType ASTContext::getUnqualifiedArrayType(QualType type,
2929 Qualifiers &quals) {
2930 SplitQualType splitType = type.getSplitUnqualifiedType();
2931
2932 // FIXME: getSplitUnqualifiedType() actually walks all the way to
2933 // the unqualified desugared type and then drops it on the floor.
2934 // We then have to strip that sugar back off with
2935 // getUnqualifiedDesugaredType(), which is silly.
2936 const ArrayType *AT =
2937 dyn_cast<ArrayType>(splitType.first->getUnqualifiedDesugaredType());
2938
2939 // If we don't have an array, just use the results in splitType.
Douglas Gregor9dadd942010-05-17 18:45:21 +00002940 if (!AT) {
John McCall62c28c82011-01-18 07:41:22 +00002941 quals = splitType.second;
2942 return QualType(splitType.first, 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002943 }
2944
John McCall62c28c82011-01-18 07:41:22 +00002945 // Otherwise, recurse on the array's element type.
2946 QualType elementType = AT->getElementType();
2947 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
2948
2949 // If that didn't change the element type, AT has no qualifiers, so we
2950 // can just use the results in splitType.
2951 if (elementType == unqualElementType) {
2952 assert(quals.empty()); // from the recursive call
2953 quals = splitType.second;
2954 return QualType(splitType.first, 0);
2955 }
2956
2957 // Otherwise, add in the qualifiers from the outermost type, then
2958 // build the type back up.
2959 quals.addConsistentQualifiers(splitType.second);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002960
Douglas Gregor9dadd942010-05-17 18:45:21 +00002961 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002962 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002963 CAT->getSizeModifier(), 0);
2964 }
2965
Douglas Gregor9dadd942010-05-17 18:45:21 +00002966 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002967 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002968 }
2969
Douglas Gregor9dadd942010-05-17 18:45:21 +00002970 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall62c28c82011-01-18 07:41:22 +00002971 return getVariableArrayType(unqualElementType,
John McCall3fa5cae2010-10-26 07:05:15 +00002972 VAT->getSizeExpr(),
Douglas Gregor9dadd942010-05-17 18:45:21 +00002973 VAT->getSizeModifier(),
2974 VAT->getIndexTypeCVRQualifiers(),
2975 VAT->getBracketsRange());
2976 }
2977
2978 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall62c28c82011-01-18 07:41:22 +00002979 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth28e318c2009-12-29 07:16:59 +00002980 DSAT->getSizeModifier(), 0,
2981 SourceRange());
2982}
2983
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002984/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
2985/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2986/// they point to and return true. If T1 and T2 aren't pointer types
2987/// or pointer-to-member types, or if they are not similar at this
2988/// level, returns false and leaves T1 and T2 unchanged. Top-level
2989/// qualifiers on T1 and T2 are ignored. This function will typically
2990/// be called in a loop that successively "unwraps" pointer and
2991/// pointer-to-member types to compare them at each level.
2992bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2993 const PointerType *T1PtrType = T1->getAs<PointerType>(),
2994 *T2PtrType = T2->getAs<PointerType>();
2995 if (T1PtrType && T2PtrType) {
2996 T1 = T1PtrType->getPointeeType();
2997 T2 = T2PtrType->getPointeeType();
2998 return true;
2999 }
3000
3001 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3002 *T2MPType = T2->getAs<MemberPointerType>();
3003 if (T1MPType && T2MPType &&
3004 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3005 QualType(T2MPType->getClass(), 0))) {
3006 T1 = T1MPType->getPointeeType();
3007 T2 = T2MPType->getPointeeType();
3008 return true;
3009 }
3010
3011 if (getLangOptions().ObjC1) {
3012 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3013 *T2OPType = T2->getAs<ObjCObjectPointerType>();
3014 if (T1OPType && T2OPType) {
3015 T1 = T1OPType->getPointeeType();
3016 T2 = T2OPType->getPointeeType();
3017 return true;
3018 }
3019 }
3020
3021 // FIXME: Block pointers, too?
3022
3023 return false;
3024}
3025
Jay Foad4ba2a172011-01-12 09:06:06 +00003026DeclarationNameInfo
3027ASTContext::getNameForTemplate(TemplateName Name,
3028 SourceLocation NameLoc) const {
John McCall14606042011-06-30 08:33:18 +00003029 switch (Name.getKind()) {
3030 case TemplateName::QualifiedTemplate:
3031 case TemplateName::Template:
Abramo Bagnara25777432010-08-11 22:01:17 +00003032 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCall14606042011-06-30 08:33:18 +00003033 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3034 NameLoc);
Abramo Bagnara25777432010-08-11 22:01:17 +00003035
John McCall14606042011-06-30 08:33:18 +00003036 case TemplateName::OverloadedTemplate: {
3037 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3038 // DNInfo work in progress: CHECKME: what about DNLoc?
3039 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3040 }
3041
3042 case TemplateName::DependentTemplate: {
3043 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnara25777432010-08-11 22:01:17 +00003044 DeclarationName DName;
John McCall80ad16f2009-11-24 18:42:40 +00003045 if (DTN->isIdentifier()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00003046 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3047 return DeclarationNameInfo(DName, NameLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003048 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00003049 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3050 // DNInfo work in progress: FIXME: source locations?
3051 DeclarationNameLoc DNLoc;
3052 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3053 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3054 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall80ad16f2009-11-24 18:42:40 +00003055 }
3056 }
3057
John McCall14606042011-06-30 08:33:18 +00003058 case TemplateName::SubstTemplateTemplateParm: {
3059 SubstTemplateTemplateParmStorage *subst
3060 = Name.getAsSubstTemplateTemplateParm();
3061 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3062 NameLoc);
3063 }
3064
3065 case TemplateName::SubstTemplateTemplateParmPack: {
3066 SubstTemplateTemplateParmPackStorage *subst
3067 = Name.getAsSubstTemplateTemplateParmPack();
3068 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3069 NameLoc);
3070 }
3071 }
3072
3073 llvm_unreachable("bad template name kind!");
John McCall80ad16f2009-11-24 18:42:40 +00003074}
3075
Jay Foad4ba2a172011-01-12 09:06:06 +00003076TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCall14606042011-06-30 08:33:18 +00003077 switch (Name.getKind()) {
3078 case TemplateName::QualifiedTemplate:
3079 case TemplateName::Template: {
3080 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003081 if (TemplateTemplateParmDecl *TTP
John McCall14606042011-06-30 08:33:18 +00003082 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003083 Template = getCanonicalTemplateTemplateParmDecl(TTP);
3084
3085 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00003086 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor3e1274f2010-06-16 21:09:37 +00003087 }
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003088
John McCall14606042011-06-30 08:33:18 +00003089 case TemplateName::OverloadedTemplate:
3090 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump1eb44332009-09-09 15:08:12 +00003091
John McCall14606042011-06-30 08:33:18 +00003092 case TemplateName::DependentTemplate: {
3093 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3094 assert(DTN && "Non-dependent template names must refer to template decls.");
3095 return DTN->CanonicalTemplateName;
3096 }
3097
3098 case TemplateName::SubstTemplateTemplateParm: {
3099 SubstTemplateTemplateParmStorage *subst
3100 = Name.getAsSubstTemplateTemplateParm();
3101 return getCanonicalTemplateName(subst->getReplacement());
3102 }
3103
3104 case TemplateName::SubstTemplateTemplateParmPack: {
3105 SubstTemplateTemplateParmPackStorage *subst
3106 = Name.getAsSubstTemplateTemplateParmPack();
3107 TemplateTemplateParmDecl *canonParameter
3108 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3109 TemplateArgument canonArgPack
3110 = getCanonicalTemplateArgument(subst->getArgumentPack());
3111 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3112 }
3113 }
3114
3115 llvm_unreachable("bad template name!");
Douglas Gregor25a3ef72009-05-07 06:41:52 +00003116}
3117
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003118bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3119 X = getCanonicalTemplateName(X);
3120 Y = getCanonicalTemplateName(Y);
3121 return X.getAsVoidPointer() == Y.getAsVoidPointer();
3122}
3123
Mike Stump1eb44332009-09-09 15:08:12 +00003124TemplateArgument
Jay Foad4ba2a172011-01-12 09:06:06 +00003125ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregor1275ae02009-07-28 23:00:59 +00003126 switch (Arg.getKind()) {
3127 case TemplateArgument::Null:
3128 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Douglas Gregor1275ae02009-07-28 23:00:59 +00003130 case TemplateArgument::Expression:
Douglas Gregor1275ae02009-07-28 23:00:59 +00003131 return Arg;
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Douglas Gregor1275ae02009-07-28 23:00:59 +00003133 case TemplateArgument::Declaration:
John McCall833ca992009-10-29 08:12:44 +00003134 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Douglas Gregor788cd062009-11-11 01:00:40 +00003136 case TemplateArgument::Template:
3137 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregora7fc9012011-01-05 18:58:31 +00003138
3139 case TemplateArgument::TemplateExpansion:
3140 return TemplateArgument(getCanonicalTemplateName(
3141 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregor2be29f42011-01-14 23:41:42 +00003142 Arg.getNumTemplateExpansions());
Douglas Gregora7fc9012011-01-05 18:58:31 +00003143
Douglas Gregor1275ae02009-07-28 23:00:59 +00003144 case TemplateArgument::Integral:
John McCall833ca992009-10-29 08:12:44 +00003145 return TemplateArgument(*Arg.getAsIntegral(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003146 getCanonicalType(Arg.getIntegralType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003147
Douglas Gregor1275ae02009-07-28 23:00:59 +00003148 case TemplateArgument::Type:
John McCall833ca992009-10-29 08:12:44 +00003149 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003150
Douglas Gregor1275ae02009-07-28 23:00:59 +00003151 case TemplateArgument::Pack: {
Douglas Gregor87dd6972010-12-20 16:52:59 +00003152 if (Arg.pack_size() == 0)
3153 return Arg;
3154
Douglas Gregor910f8002010-11-07 23:05:16 +00003155 TemplateArgument *CanonArgs
3156 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregor1275ae02009-07-28 23:00:59 +00003157 unsigned Idx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003158 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregor1275ae02009-07-28 23:00:59 +00003159 AEnd = Arg.pack_end();
3160 A != AEnd; (void)++A, ++Idx)
3161 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump1eb44332009-09-09 15:08:12 +00003162
Douglas Gregor910f8002010-11-07 23:05:16 +00003163 return TemplateArgument(CanonArgs, Arg.pack_size());
Douglas Gregor1275ae02009-07-28 23:00:59 +00003164 }
3165 }
3166
3167 // Silence GCC warning
3168 assert(false && "Unhandled template argument kind");
3169 return TemplateArgument();
3170}
3171
Douglas Gregord57959a2009-03-27 23:10:48 +00003172NestedNameSpecifier *
Jay Foad4ba2a172011-01-12 09:06:06 +00003173ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump1eb44332009-09-09 15:08:12 +00003174 if (!NNS)
Douglas Gregord57959a2009-03-27 23:10:48 +00003175 return 0;
3176
3177 switch (NNS->getKind()) {
3178 case NestedNameSpecifier::Identifier:
3179 // Canonicalize the prefix but keep the identifier the same.
Mike Stump1eb44332009-09-09 15:08:12 +00003180 return NestedNameSpecifier::Create(*this,
Douglas Gregord57959a2009-03-27 23:10:48 +00003181 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3182 NNS->getAsIdentifier());
3183
3184 case NestedNameSpecifier::Namespace:
3185 // A namespace is canonical; build a nested-name-specifier with
3186 // this namespace and no prefix.
Douglas Gregor14aba762011-02-24 02:36:08 +00003187 return NestedNameSpecifier::Create(*this, 0,
3188 NNS->getAsNamespace()->getOriginalNamespace());
3189
3190 case NestedNameSpecifier::NamespaceAlias:
3191 // A namespace is canonical; build a nested-name-specifier with
3192 // this namespace and no prefix.
3193 return NestedNameSpecifier::Create(*this, 0,
3194 NNS->getAsNamespaceAlias()->getNamespace()
3195 ->getOriginalNamespace());
Douglas Gregord57959a2009-03-27 23:10:48 +00003196
3197 case NestedNameSpecifier::TypeSpec:
3198 case NestedNameSpecifier::TypeSpecWithTemplate: {
3199 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor264bf662010-11-04 00:09:33 +00003200
3201 // If we have some kind of dependent-named type (e.g., "typename T::type"),
3202 // break it apart into its prefix and identifier, then reconsititute those
3203 // as the canonical nested-name-specifier. This is required to canonicalize
3204 // a dependent nested-name-specifier involving typedefs of dependent-name
3205 // types, e.g.,
3206 // typedef typename T::type T1;
3207 // typedef typename T1::type T2;
3208 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3209 NestedNameSpecifier *Prefix
3210 = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3211 return NestedNameSpecifier::Create(*this, Prefix,
3212 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3213 }
3214
Douglas Gregor643f8432010-11-04 00:14:23 +00003215 // Do the same thing as above, but with dependent-named specializations.
Douglas Gregor264bf662010-11-04 00:09:33 +00003216 if (const DependentTemplateSpecializationType *DTST
3217 = T->getAs<DependentTemplateSpecializationType>()) {
3218 NestedNameSpecifier *Prefix
3219 = getCanonicalNestedNameSpecifier(DTST->getQualifier());
Douglas Gregoraa2187d2011-02-28 00:04:36 +00003220
3221 T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3222 Prefix, DTST->getIdentifier(),
3223 DTST->getNumArgs(),
3224 DTST->getArgs());
Douglas Gregor264bf662010-11-04 00:09:33 +00003225 T = getCanonicalType(T);
3226 }
3227
John McCall3b657512011-01-19 10:06:00 +00003228 return NestedNameSpecifier::Create(*this, 0, false,
3229 const_cast<Type*>(T.getTypePtr()));
Douglas Gregord57959a2009-03-27 23:10:48 +00003230 }
3231
3232 case NestedNameSpecifier::Global:
3233 // The global specifier is canonical and unique.
3234 return NNS;
3235 }
3236
3237 // Required to silence a GCC warning
3238 return 0;
3239}
3240
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003241
Jay Foad4ba2a172011-01-12 09:06:06 +00003242const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003243 // Handle the non-qualified case efficiently.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003244 if (!T.hasLocalQualifiers()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003245 // Handle the common positive case fast.
3246 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3247 return AT;
3248 }
Mike Stump1eb44332009-09-09 15:08:12 +00003249
John McCall0953e762009-09-24 19:53:00 +00003250 // Handle the common negative case fast.
John McCall3b657512011-01-19 10:06:00 +00003251 if (!isa<ArrayType>(T.getCanonicalType()))
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003252 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003253
John McCall0953e762009-09-24 19:53:00 +00003254 // Apply any qualifiers from the array type to the element type. This
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003255 // implements C99 6.7.3p8: "If the specification of an array type includes
3256 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump1eb44332009-09-09 15:08:12 +00003257
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003258 // If we get here, we either have type qualifiers on the type, or we have
3259 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor50d62d12009-08-05 05:36:45 +00003260 // we must propagate them down into the element type.
Mike Stump1eb44332009-09-09 15:08:12 +00003261
John McCall3b657512011-01-19 10:06:00 +00003262 SplitQualType split = T.getSplitDesugaredType();
3263 Qualifiers qs = split.second;
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003265 // If we have a simple case, just return now.
John McCall3b657512011-01-19 10:06:00 +00003266 const ArrayType *ATy = dyn_cast<ArrayType>(split.first);
3267 if (ATy == 0 || qs.empty())
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003268 return ATy;
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003270 // Otherwise, we have an array and we have qualifiers on it. Push the
3271 // qualifiers into the array element type and return a new array type.
John McCall3b657512011-01-19 10:06:00 +00003272 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003274 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3275 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3276 CAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003277 CAT->getIndexTypeCVRQualifiers()));
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003278 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3279 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3280 IAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003281 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor898574e2008-12-05 23:32:09 +00003282
Mike Stump1eb44332009-09-09 15:08:12 +00003283 if (const DependentSizedArrayType *DSAT
Douglas Gregor898574e2008-12-05 23:32:09 +00003284 = dyn_cast<DependentSizedArrayType>(ATy))
3285 return cast<ArrayType>(
Mike Stump1eb44332009-09-09 15:08:12 +00003286 getDependentSizedArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003287 DSAT->getSizeExpr(),
Douglas Gregor898574e2008-12-05 23:32:09 +00003288 DSAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003289 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003290 DSAT->getBracketsRange()));
Mike Stump1eb44332009-09-09 15:08:12 +00003291
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003292 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003293 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCall3fa5cae2010-10-26 07:05:15 +00003294 VAT->getSizeExpr(),
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003295 VAT->getSizeModifier(),
John McCall0953e762009-09-24 19:53:00 +00003296 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00003297 VAT->getBracketsRange()));
Chris Lattner77c96472008-04-06 22:41:35 +00003298}
3299
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003300QualType ASTContext::getAdjustedParameterType(QualType T) {
3301 // C99 6.7.5.3p7:
3302 // A declaration of a parameter as "array of type" shall be
3303 // adjusted to "qualified pointer to type", where the type
3304 // qualifiers (if any) are those specified within the [ and ] of
3305 // the array type derivation.
3306 if (T->isArrayType())
3307 return getArrayDecayedType(T);
3308
3309 // C99 6.7.5.3p8:
3310 // A declaration of a parameter as "function returning type"
3311 // shall be adjusted to "pointer to function returning type", as
3312 // in 6.3.2.1.
3313 if (T->isFunctionType())
3314 return getPointerType(T);
3315
3316 return T;
3317}
3318
3319QualType ASTContext::getSignatureParameterType(QualType T) {
3320 T = getVariableArrayDecayedType(T);
3321 T = getAdjustedParameterType(T);
3322 return T.getUnqualifiedType();
3323}
3324
Chris Lattnere6327742008-04-02 05:18:44 +00003325/// getArrayDecayedType - Return the properly qualified result of decaying the
3326/// specified array type to a pointer. This operation is non-trivial when
3327/// handling typedefs etc. The canonical type of "T" must be an array type,
3328/// this returns a pointer to a properly qualified element of the array.
3329///
3330/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad4ba2a172011-01-12 09:06:06 +00003331QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003332 // Get the element type with 'getAsArrayType' so that we don't lose any
3333 // typedefs in the element type of the array. This also handles propagation
3334 // of type qualifiers from the array type into the element type if present
3335 // (C99 6.7.3p8).
3336 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3337 assert(PrettyArrayType && "Not an array type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003339 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnere6327742008-04-02 05:18:44 +00003340
3341 // int x[restrict 4] -> int *restrict
John McCall0953e762009-09-24 19:53:00 +00003342 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
Chris Lattnere6327742008-04-02 05:18:44 +00003343}
3344
John McCall3b657512011-01-19 10:06:00 +00003345QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3346 return getBaseElementType(array->getElementType());
Douglas Gregor5e03f9e2009-07-23 23:49:00 +00003347}
3348
John McCall3b657512011-01-19 10:06:00 +00003349QualType ASTContext::getBaseElementType(QualType type) const {
3350 Qualifiers qs;
3351 while (true) {
3352 SplitQualType split = type.getSplitDesugaredType();
3353 const ArrayType *array = split.first->getAsArrayTypeUnsafe();
3354 if (!array) break;
Mike Stump1eb44332009-09-09 15:08:12 +00003355
John McCall3b657512011-01-19 10:06:00 +00003356 type = array->getElementType();
3357 qs.addConsistentQualifiers(split.second);
3358 }
Mike Stump1eb44332009-09-09 15:08:12 +00003359
John McCall3b657512011-01-19 10:06:00 +00003360 return getQualifiedType(type, qs);
Anders Carlsson6183a992008-12-21 03:44:36 +00003361}
3362
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003363/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump1eb44332009-09-09 15:08:12 +00003364uint64_t
Fariborz Jahanian0de78992009-08-21 16:31:06 +00003365ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
3366 uint64_t ElementCount = 1;
3367 do {
3368 ElementCount *= CA->getSize().getZExtValue();
3369 CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3370 } while (CA);
3371 return ElementCount;
3372}
3373
Reid Spencer5f016e22007-07-11 17:01:13 +00003374/// getFloatingRank - Return a relative rank for floating point types.
3375/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnera75cea32008-04-06 23:38:49 +00003376static FloatingRank getFloatingRank(QualType T) {
John McCall183700f2009-09-21 23:43:11 +00003377 if (const ComplexType *CT = T->getAs<ComplexType>())
Reid Spencer5f016e22007-07-11 17:01:13 +00003378 return getFloatingRank(CT->getElementType());
Chris Lattnera75cea32008-04-06 23:38:49 +00003379
John McCall183700f2009-09-21 23:43:11 +00003380 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3381 switch (T->getAs<BuiltinType>()->getKind()) {
Chris Lattnera75cea32008-04-06 23:38:49 +00003382 default: assert(0 && "getFloatingRank(): not a floating type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003383 case BuiltinType::Float: return FloatRank;
3384 case BuiltinType::Double: return DoubleRank;
3385 case BuiltinType::LongDouble: return LongDoubleRank;
3386 }
3387}
3388
Mike Stump1eb44332009-09-09 15:08:12 +00003389/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3390/// point or a complex type (based on typeDomain/typeSize).
Steve Naroff716c7302007-08-27 01:41:48 +00003391/// 'typeDomain' is a real floating point or complex type.
3392/// 'typeSize' is a real floating point or complex type.
Chris Lattner1361b112008-04-06 23:58:54 +00003393QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3394 QualType Domain) const {
3395 FloatingRank EltRank = getFloatingRank(Size);
3396 if (Domain->isComplexType()) {
3397 switch (EltRank) {
Steve Naroff716c7302007-08-27 01:41:48 +00003398 default: assert(0 && "getFloatingRank(): illegal value for rank");
Steve Narofff1448a02007-08-27 01:27:54 +00003399 case FloatRank: return FloatComplexTy;
3400 case DoubleRank: return DoubleComplexTy;
3401 case LongDoubleRank: return LongDoubleComplexTy;
3402 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003403 }
Chris Lattner1361b112008-04-06 23:58:54 +00003404
3405 assert(Domain->isRealFloatingType() && "Unknown domain!");
3406 switch (EltRank) {
3407 default: assert(0 && "getFloatingRank(): illegal value for rank");
3408 case FloatRank: return FloatTy;
3409 case DoubleRank: return DoubleTy;
3410 case LongDoubleRank: return LongDoubleTy;
Steve Narofff1448a02007-08-27 01:27:54 +00003411 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003412}
3413
Chris Lattner7cfeb082008-04-06 23:55:33 +00003414/// getFloatingTypeOrder - Compare the rank of the two specified floating
3415/// point types, ignoring the domain of the type (i.e. 'double' ==
3416/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003417/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003418int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnera75cea32008-04-06 23:38:49 +00003419 FloatingRank LHSR = getFloatingRank(LHS);
3420 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00003421
Chris Lattnera75cea32008-04-06 23:38:49 +00003422 if (LHSR == RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003423 return 0;
Chris Lattnera75cea32008-04-06 23:38:49 +00003424 if (LHSR > RHSR)
Steve Narofffb0d4962007-08-27 15:30:22 +00003425 return 1;
3426 return -1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003427}
3428
Chris Lattnerf52ab252008-04-06 22:59:24 +00003429/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3430/// routine will assert if passed a built-in type that isn't an integer or enum,
3431/// or if it is not canonicalized.
John McCallf4c73712011-01-19 06:33:43 +00003432unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCall467b27b2009-10-22 20:10:53 +00003433 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
John McCallf4c73712011-01-19 06:33:43 +00003434 if (const EnumType* ET = dyn_cast<EnumType>(T))
John McCall842aef82009-12-09 09:09:27 +00003435 T = ET->getDecl()->getPromotionType().getTypePtr();
Eli Friedmanf98aba32009-02-13 02:31:07 +00003436
Chris Lattner3f59c972010-12-25 23:25:43 +00003437 if (T->isSpecificBuiltinType(BuiltinType::WChar_S) ||
3438 T->isSpecificBuiltinType(BuiltinType::WChar_U))
Eli Friedmana3426752009-07-05 23:44:27 +00003439 T = getFromTargetType(Target.getWCharType()).getTypePtr();
3440
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00003441 if (T->isSpecificBuiltinType(BuiltinType::Char16))
3442 T = getFromTargetType(Target.getChar16Type()).getTypePtr();
3443
3444 if (T->isSpecificBuiltinType(BuiltinType::Char32))
3445 T = getFromTargetType(Target.getChar32Type()).getTypePtr();
3446
Chris Lattnerf52ab252008-04-06 22:59:24 +00003447 switch (cast<BuiltinType>(T)->getKind()) {
Chris Lattner7cfeb082008-04-06 23:55:33 +00003448 default: assert(0 && "getIntegerRank(): not a built-in integer");
3449 case BuiltinType::Bool:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003450 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003451 case BuiltinType::Char_S:
3452 case BuiltinType::Char_U:
3453 case BuiltinType::SChar:
3454 case BuiltinType::UChar:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003455 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003456 case BuiltinType::Short:
3457 case BuiltinType::UShort:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003458 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003459 case BuiltinType::Int:
3460 case BuiltinType::UInt:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003461 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003462 case BuiltinType::Long:
3463 case BuiltinType::ULong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003464 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattner7cfeb082008-04-06 23:55:33 +00003465 case BuiltinType::LongLong:
3466 case BuiltinType::ULongLong:
Eli Friedmanf98aba32009-02-13 02:31:07 +00003467 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattner2df9ced2009-04-30 02:43:43 +00003468 case BuiltinType::Int128:
3469 case BuiltinType::UInt128:
3470 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattnerf52ab252008-04-06 22:59:24 +00003471 }
3472}
3473
Eli Friedman04e83572009-08-20 04:21:42 +00003474/// \brief Whether this is a promotable bitfield reference according
3475/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3476///
3477/// \returns the type this bit-field will promote to, or NULL if no
3478/// promotion occurs.
Jay Foad4ba2a172011-01-12 09:06:06 +00003479QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregorceafbde2010-05-24 20:13:53 +00003480 if (E->isTypeDependent() || E->isValueDependent())
3481 return QualType();
3482
Eli Friedman04e83572009-08-20 04:21:42 +00003483 FieldDecl *Field = E->getBitField();
3484 if (!Field)
3485 return QualType();
3486
3487 QualType FT = Field->getType();
3488
3489 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
3490 uint64_t BitWidth = BitWidthAP.getZExtValue();
3491 uint64_t IntSize = getTypeSize(IntTy);
3492 // GCC extension compatibility: if the bit-field size is less than or equal
3493 // to the size of int, it gets promoted no matter what its type is.
3494 // For instance, unsigned long bf : 4 gets promoted to signed int.
3495 if (BitWidth < IntSize)
3496 return IntTy;
3497
3498 if (BitWidth == IntSize)
3499 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3500
3501 // Types bigger than int are not subject to promotions, and therefore act
3502 // like the base type.
3503 // FIXME: This doesn't quite match what gcc does, but what gcc does here
3504 // is ridiculous.
3505 return QualType();
3506}
3507
Eli Friedmana95d7572009-08-19 07:44:53 +00003508/// getPromotedIntegerType - Returns the type that Promotable will
3509/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3510/// integer type.
Jay Foad4ba2a172011-01-12 09:06:06 +00003511QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedmana95d7572009-08-19 07:44:53 +00003512 assert(!Promotable.isNull());
3513 assert(Promotable->isPromotableIntegerType());
John McCall842aef82009-12-09 09:09:27 +00003514 if (const EnumType *ET = Promotable->getAs<EnumType>())
3515 return ET->getDecl()->getPromotionType();
Eli Friedmana95d7572009-08-19 07:44:53 +00003516 if (Promotable->isSignedIntegerType())
3517 return IntTy;
3518 uint64_t PromotableSize = getTypeSize(Promotable);
3519 uint64_t IntSize = getTypeSize(IntTy);
3520 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3521 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3522}
3523
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003524/// \brief Recurses in pointer/array types until it finds an objc retainable
3525/// type and returns its ownership.
3526Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3527 while (!T.isNull()) {
3528 if (T.getObjCLifetime() != Qualifiers::OCL_None)
3529 return T.getObjCLifetime();
3530 if (T->isArrayType())
3531 T = getBaseElementType(T);
3532 else if (const PointerType *PT = T->getAs<PointerType>())
3533 T = PT->getPointeeType();
3534 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis28445f02011-07-01 23:01:46 +00003535 T = RT->getPointeeType();
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00003536 else
3537 break;
3538 }
3539
3540 return Qualifiers::OCL_None;
3541}
3542
Mike Stump1eb44332009-09-09 15:08:12 +00003543/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattner7cfeb082008-04-06 23:55:33 +00003544/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump1eb44332009-09-09 15:08:12 +00003545/// LHS < RHS, return -1.
Jay Foad4ba2a172011-01-12 09:06:06 +00003546int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCallf4c73712011-01-19 06:33:43 +00003547 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3548 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Chris Lattner7cfeb082008-04-06 23:55:33 +00003549 if (LHSC == RHSC) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003550
Chris Lattnerf52ab252008-04-06 22:59:24 +00003551 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3552 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Chris Lattner7cfeb082008-04-06 23:55:33 +00003554 unsigned LHSRank = getIntegerRank(LHSC);
3555 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Chris Lattner7cfeb082008-04-06 23:55:33 +00003557 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
3558 if (LHSRank == RHSRank) return 0;
3559 return LHSRank > RHSRank ? 1 : -1;
3560 }
Mike Stump1eb44332009-09-09 15:08:12 +00003561
Chris Lattner7cfeb082008-04-06 23:55:33 +00003562 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3563 if (LHSUnsigned) {
3564 // If the unsigned [LHS] type is larger, return it.
3565 if (LHSRank >= RHSRank)
3566 return 1;
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Chris Lattner7cfeb082008-04-06 23:55:33 +00003568 // If the signed type can represent all values of the unsigned type, it
3569 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003570 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003571 return -1;
3572 }
Chris Lattnerf52ab252008-04-06 22:59:24 +00003573
Chris Lattner7cfeb082008-04-06 23:55:33 +00003574 // If the unsigned [RHS] type is larger, return it.
3575 if (RHSRank >= LHSRank)
3576 return -1;
Mike Stump1eb44332009-09-09 15:08:12 +00003577
Chris Lattner7cfeb082008-04-06 23:55:33 +00003578 // If the signed type can represent all values of the unsigned type, it
3579 // wins. Because we are dealing with 2's complement and types that are
Mike Stump1eb44332009-09-09 15:08:12 +00003580 // powers of two larger than each other, this is always safe.
Chris Lattner7cfeb082008-04-06 23:55:33 +00003581 return 1;
Reid Spencer5f016e22007-07-11 17:01:13 +00003582}
Anders Carlsson71993dd2007-08-17 05:31:46 +00003583
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003584static RecordDecl *
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003585CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3586 DeclContext *DC, IdentifierInfo *Id) {
3587 SourceLocation Loc;
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003588 if (Ctx.getLangOptions().CPlusPlus)
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003589 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003590 else
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003591 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003592}
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003593
Mike Stump1eb44332009-09-09 15:08:12 +00003594// getCFConstantStringType - Return the type used for constant CFStrings.
Jay Foad4ba2a172011-01-12 09:06:06 +00003595QualType ASTContext::getCFConstantStringType() const {
Anders Carlsson71993dd2007-08-17 05:31:46 +00003596 if (!CFConstantStringTypeDecl) {
Mike Stump1eb44332009-09-09 15:08:12 +00003597 CFConstantStringTypeDecl =
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003598 CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003599 &Idents.get("NSConstantString"));
John McCall5cfa0112010-02-05 01:33:36 +00003600 CFConstantStringTypeDecl->startDefinition();
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003601
Anders Carlssonf06273f2007-11-19 00:25:30 +00003602 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Anders Carlsson71993dd2007-08-17 05:31:46 +00003604 // const int *isa;
John McCall0953e762009-09-24 19:53:00 +00003605 FieldTypes[0] = getPointerType(IntTy.withConst());
Anders Carlssonf06273f2007-11-19 00:25:30 +00003606 // int flags;
3607 FieldTypes[1] = IntTy;
Anders Carlsson71993dd2007-08-17 05:31:46 +00003608 // const char *str;
John McCall0953e762009-09-24 19:53:00 +00003609 FieldTypes[2] = getPointerType(CharTy.withConst());
Anders Carlsson71993dd2007-08-17 05:31:46 +00003610 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00003611 FieldTypes[3] = LongTy;
3612
Anders Carlsson71993dd2007-08-17 05:31:46 +00003613 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00003614 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00003615 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003616 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00003617 SourceLocation(), 0,
John McCalla93c9342009-12-07 02:54:59 +00003618 FieldTypes[i], /*TInfo=*/0,
Mike Stump1eb44332009-09-09 15:08:12 +00003619 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003620 /*Mutable=*/false,
3621 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003622 Field->setAccess(AS_public);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003623 CFConstantStringTypeDecl->addDecl(Field);
Douglas Gregor44b43212008-12-11 16:49:14 +00003624 }
3625
Douglas Gregor838db382010-02-11 01:19:42 +00003626 CFConstantStringTypeDecl->completeDefinition();
Anders Carlsson71993dd2007-08-17 05:31:46 +00003627 }
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Anders Carlsson71993dd2007-08-17 05:31:46 +00003629 return getTagDeclType(CFConstantStringTypeDecl);
Gabor Greif84675832007-09-11 15:32:40 +00003630}
Anders Carlssonb2cf3572007-10-11 01:00:40 +00003631
Douglas Gregor319ac892009-04-23 22:29:11 +00003632void ASTContext::setCFConstantStringType(QualType T) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003633 const RecordType *Rec = T->getAs<RecordType>();
Douglas Gregor319ac892009-04-23 22:29:11 +00003634 assert(Rec && "Invalid CFConstantStringType");
3635 CFConstantStringTypeDecl = Rec->getDecl();
3636}
3637
Jay Foad4ba2a172011-01-12 09:06:06 +00003638QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpadaaad32009-10-20 02:12:22 +00003639 if (BlockDescriptorType)
3640 return getTagDeclType(BlockDescriptorType);
3641
3642 RecordDecl *T;
3643 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003644 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003645 &Idents.get("__block_descriptor"));
John McCall5cfa0112010-02-05 01:33:36 +00003646 T->startDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003647
3648 QualType FieldTypes[] = {
3649 UnsignedLongTy,
3650 UnsignedLongTy,
3651 };
3652
3653 const char *FieldNames[] = {
3654 "reserved",
Mike Stump083c25e2009-10-22 00:49:09 +00003655 "Size"
Mike Stumpadaaad32009-10-20 02:12:22 +00003656 };
3657
3658 for (size_t i = 0; i < 2; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003659 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stumpadaaad32009-10-20 02:12:22 +00003660 SourceLocation(),
3661 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003662 FieldTypes[i], /*TInfo=*/0,
Mike Stumpadaaad32009-10-20 02:12:22 +00003663 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003664 /*Mutable=*/false,
3665 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003666 Field->setAccess(AS_public);
Mike Stumpadaaad32009-10-20 02:12:22 +00003667 T->addDecl(Field);
3668 }
3669
Douglas Gregor838db382010-02-11 01:19:42 +00003670 T->completeDefinition();
Mike Stumpadaaad32009-10-20 02:12:22 +00003671
3672 BlockDescriptorType = T;
3673
3674 return getTagDeclType(BlockDescriptorType);
3675}
3676
Jay Foad4ba2a172011-01-12 09:06:06 +00003677QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stump083c25e2009-10-22 00:49:09 +00003678 if (BlockDescriptorExtendedType)
3679 return getTagDeclType(BlockDescriptorExtendedType);
3680
3681 RecordDecl *T;
3682 // FIXME: Needs the FlagAppleBlock bit.
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003683 T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
Anders Carlsson79cbc7d2009-11-14 21:45:58 +00003684 &Idents.get("__block_descriptor_withcopydispose"));
John McCall5cfa0112010-02-05 01:33:36 +00003685 T->startDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003686
3687 QualType FieldTypes[] = {
3688 UnsignedLongTy,
3689 UnsignedLongTy,
3690 getPointerType(VoidPtrTy),
3691 getPointerType(VoidPtrTy)
3692 };
3693
3694 const char *FieldNames[] = {
3695 "reserved",
3696 "Size",
3697 "CopyFuncPtr",
3698 "DestroyFuncPtr"
3699 };
3700
3701 for (size_t i = 0; i < 4; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003702 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Mike Stump083c25e2009-10-22 00:49:09 +00003703 SourceLocation(),
3704 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003705 FieldTypes[i], /*TInfo=*/0,
Mike Stump083c25e2009-10-22 00:49:09 +00003706 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003707 /*Mutable=*/false,
3708 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003709 Field->setAccess(AS_public);
Mike Stump083c25e2009-10-22 00:49:09 +00003710 T->addDecl(Field);
3711 }
3712
Douglas Gregor838db382010-02-11 01:19:42 +00003713 T->completeDefinition();
Mike Stump083c25e2009-10-22 00:49:09 +00003714
3715 BlockDescriptorExtendedType = T;
3716
3717 return getTagDeclType(BlockDescriptorExtendedType);
3718}
3719
Jay Foad4ba2a172011-01-12 09:06:06 +00003720bool ASTContext::BlockRequiresCopying(QualType Ty) const {
John McCallf85e1932011-06-15 23:02:42 +00003721 if (Ty->isObjCRetainableType())
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003722 return true;
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003723 if (getLangOptions().CPlusPlus) {
3724 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3725 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Sean Huntffe37fd2011-05-25 20:50:04 +00003726 return RD->hasConstCopyConstructor();
Fariborz Jahaniane38be612010-11-17 00:21:28 +00003727
3728 }
3729 }
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003730 return false;
3731}
3732
Jay Foad4ba2a172011-01-12 09:06:06 +00003733QualType
Chris Lattner5f9e2722011-07-23 10:55:15 +00003734ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003735 // type = struct __Block_byref_1_X {
Mike Stumpea26cb52009-10-21 03:49:08 +00003736 // void *__isa;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003737 // struct __Block_byref_1_X *__forwarding;
Mike Stumpea26cb52009-10-21 03:49:08 +00003738 // unsigned int __flags;
3739 // unsigned int __size;
Eli Friedmana7e68452010-08-22 01:00:03 +00003740 // void *__copy_helper; // as needed
3741 // void *__destroy_help // as needed
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003742 // int X;
Mike Stumpea26cb52009-10-21 03:49:08 +00003743 // } *
3744
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003745 bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3746
3747 // FIXME: Move up
Benjamin Kramerf5942a42009-10-24 09:57:09 +00003748 llvm::SmallString<36> Name;
3749 llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3750 ++UniqueBlockByRefTypeID << '_' << DeclName;
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003751 RecordDecl *T;
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003752 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003753 T->startDefinition();
3754 QualType Int32Ty = IntTy;
3755 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3756 QualType FieldTypes[] = {
3757 getPointerType(VoidPtrTy),
3758 getPointerType(getTagDeclType(T)),
3759 Int32Ty,
3760 Int32Ty,
3761 getPointerType(VoidPtrTy),
3762 getPointerType(VoidPtrTy),
3763 Ty
3764 };
3765
Chris Lattner5f9e2722011-07-23 10:55:15 +00003766 StringRef FieldNames[] = {
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003767 "__isa",
3768 "__forwarding",
3769 "__flags",
3770 "__size",
3771 "__copy_helper",
3772 "__destroy_helper",
3773 DeclName,
3774 };
3775
3776 for (size_t i = 0; i < 7; ++i) {
3777 if (!HasCopyAndDispose && i >=4 && i <= 5)
3778 continue;
3779 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003780 SourceLocation(),
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003781 &Idents.get(FieldNames[i]),
John McCalla93c9342009-12-07 02:54:59 +00003782 FieldTypes[i], /*TInfo=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00003783 /*BitWidth=*/0, /*Mutable=*/false,
3784 /*HasInit=*/false);
John McCall2888b652010-04-30 21:35:41 +00003785 Field->setAccess(AS_public);
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003786 T->addDecl(Field);
3787 }
3788
Douglas Gregor838db382010-02-11 01:19:42 +00003789 T->completeDefinition();
Mike Stumpaf7b44d2009-10-21 18:16:27 +00003790
3791 return getPointerType(getTagDeclType(T));
Mike Stumpea26cb52009-10-21 03:49:08 +00003792}
3793
Anders Carlssone8c49532007-10-29 06:33:42 +00003794// This returns true if a type has been typedefed to BOOL:
3795// typedef <type> BOOL;
Chris Lattner2d998332007-10-30 20:27:44 +00003796static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlssone8c49532007-10-29 06:33:42 +00003797 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattnerbb49c3e2008-11-24 03:52:59 +00003798 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3799 return II->isStr("BOOL");
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Anders Carlsson85f9bce2007-10-29 05:01:08 +00003801 return false;
3802}
3803
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003804/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003805/// purpose.
Jay Foad4ba2a172011-01-12 09:06:06 +00003806CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregorf968d832011-05-27 01:19:52 +00003807 if (!type->isIncompleteArrayType() && type->isIncompleteType())
3808 return CharUnits::Zero();
3809
Ken Dyck199c3d62010-01-11 17:06:35 +00003810 CharUnits sz = getTypeSizeInChars(type);
Mike Stump1eb44332009-09-09 15:08:12 +00003811
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003812 // Make all integer and enum types at least as large as an int
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003813 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003814 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003815 // Treat arrays as pointers, since that's how they're passed in.
3816 else if (type->isArrayType())
Ken Dyck199c3d62010-01-11 17:06:35 +00003817 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003818 return sz;
Ken Dyck199c3d62010-01-11 17:06:35 +00003819}
3820
3821static inline
3822std::string charUnitsToString(const CharUnits &CU) {
3823 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003824}
3825
John McCall6b5a61b2011-02-07 10:33:21 +00003826/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall5e530af2009-11-17 19:33:30 +00003827/// declaration.
John McCall6b5a61b2011-02-07 10:33:21 +00003828std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
3829 std::string S;
3830
David Chisnall5e530af2009-11-17 19:33:30 +00003831 const BlockDecl *Decl = Expr->getBlockDecl();
3832 QualType BlockTy =
3833 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3834 // Encode result type.
John McCallc71a4912010-06-04 19:02:56 +00003835 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
David Chisnall5e530af2009-11-17 19:33:30 +00003836 // Compute size of all parameters.
3837 // Start with computing size of a pointer in number of bytes.
3838 // FIXME: There might(should) be a better way of doing this computation!
3839 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003840 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3841 CharUnits ParmOffset = PtrSize;
Fariborz Jahanian6f46c262010-04-08 18:06:22 +00003842 for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
David Chisnall5e530af2009-11-17 19:33:30 +00003843 E = Decl->param_end(); PI != E; ++PI) {
3844 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003845 CharUnits sz = getObjCEncodingTypeSize(PType);
Ken Dyck199c3d62010-01-11 17:06:35 +00003846 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall5e530af2009-11-17 19:33:30 +00003847 ParmOffset += sz;
3848 }
3849 // Size of the argument frame
Ken Dyck199c3d62010-01-11 17:06:35 +00003850 S += charUnitsToString(ParmOffset);
David Chisnall5e530af2009-11-17 19:33:30 +00003851 // Block pointer and offset.
3852 S += "@?0";
David Chisnall5e530af2009-11-17 19:33:30 +00003853
3854 // Argument types.
3855 ParmOffset = PtrSize;
3856 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3857 Decl->param_end(); PI != E; ++PI) {
3858 ParmVarDecl *PVDecl = *PI;
3859 QualType PType = PVDecl->getOriginalType();
3860 if (const ArrayType *AT =
3861 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3862 // Use array's original type only if it has known number of
3863 // elements.
3864 if (!isa<ConstantArrayType>(AT))
3865 PType = PVDecl->getType();
3866 } else if (PType->isFunctionType())
3867 PType = PVDecl->getType();
3868 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003869 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003870 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall5e530af2009-11-17 19:33:30 +00003871 }
John McCall6b5a61b2011-02-07 10:33:21 +00003872
3873 return S;
David Chisnall5e530af2009-11-17 19:33:30 +00003874}
3875
Douglas Gregorf968d832011-05-27 01:19:52 +00003876bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
David Chisnall5389f482010-12-30 14:05:53 +00003877 std::string& S) {
3878 // Encode result type.
3879 getObjCEncodingForType(Decl->getResultType(), S);
3880 CharUnits ParmOffset;
3881 // Compute size of all parameters.
3882 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3883 E = Decl->param_end(); PI != E; ++PI) {
3884 QualType PType = (*PI)->getType();
3885 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003886 if (sz.isZero())
3887 return true;
3888
David Chisnall5389f482010-12-30 14:05:53 +00003889 assert (sz.isPositive() &&
Douglas Gregorf968d832011-05-27 01:19:52 +00003890 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall5389f482010-12-30 14:05:53 +00003891 ParmOffset += sz;
3892 }
3893 S += charUnitsToString(ParmOffset);
3894 ParmOffset = CharUnits::Zero();
3895
3896 // Argument types.
3897 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
3898 E = Decl->param_end(); PI != E; ++PI) {
3899 ParmVarDecl *PVDecl = *PI;
3900 QualType PType = PVDecl->getOriginalType();
3901 if (const ArrayType *AT =
3902 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3903 // Use array's original type only if it has known number of
3904 // elements.
3905 if (!isa<ConstantArrayType>(AT))
3906 PType = PVDecl->getType();
3907 } else if (PType->isFunctionType())
3908 PType = PVDecl->getType();
3909 getObjCEncodingForType(PType, S);
3910 S += charUnitsToString(ParmOffset);
3911 ParmOffset += getObjCEncodingTypeSize(PType);
3912 }
Douglas Gregorf968d832011-05-27 01:19:52 +00003913
3914 return false;
David Chisnall5389f482010-12-30 14:05:53 +00003915}
3916
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003917/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003918/// declaration.
Douglas Gregorf968d832011-05-27 01:19:52 +00003919bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
Jay Foad4ba2a172011-01-12 09:06:06 +00003920 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003921 // FIXME: This is not very efficient.
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003922 // Encode type qualifer, 'in', 'inout', etc. for the return type.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003923 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003924 // Encode result type.
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003925 getObjCEncodingForType(Decl->getResultType(), S);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003926 // Compute size of all parameters.
3927 // Start with computing size of a pointer in number of bytes.
3928 // FIXME: There might(should) be a better way of doing this computation!
3929 SourceLocation Loc;
Ken Dyck199c3d62010-01-11 17:06:35 +00003930 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003931 // The first two arguments (self and _cmd) are pointers; account for
3932 // their size.
Ken Dyck199c3d62010-01-11 17:06:35 +00003933 CharUnits ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003934 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003935 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003936 QualType PType = (*PI)->getType();
Ken Dyckaa8741a2010-01-11 19:19:56 +00003937 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregorf968d832011-05-27 01:19:52 +00003938 if (sz.isZero())
3939 return true;
3940
Ken Dyck199c3d62010-01-11 17:06:35 +00003941 assert (sz.isPositive() &&
3942 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003943 ParmOffset += sz;
3944 }
Ken Dyck199c3d62010-01-11 17:06:35 +00003945 S += charUnitsToString(ParmOffset);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003946 S += "@0:";
Ken Dyck199c3d62010-01-11 17:06:35 +00003947 S += charUnitsToString(PtrSize);
Mike Stump1eb44332009-09-09 15:08:12 +00003948
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003949 // Argument types.
3950 ParmOffset = 2 * PtrSize;
Chris Lattner89951a82009-02-20 18:43:26 +00003951 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
Fariborz Jahanian7732cc92010-04-08 21:29:11 +00003952 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattner89951a82009-02-20 18:43:26 +00003953 ParmVarDecl *PVDecl = *PI;
Mike Stump1eb44332009-09-09 15:08:12 +00003954 QualType PType = PVDecl->getOriginalType();
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003955 if (const ArrayType *AT =
Steve Naroffab76d452009-04-14 00:03:58 +00003956 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3957 // Use array's original type only if it has known number of
3958 // elements.
Steve Naroffbb3fde32009-04-14 00:40:09 +00003959 if (!isa<ConstantArrayType>(AT))
Steve Naroffab76d452009-04-14 00:03:58 +00003960 PType = PVDecl->getType();
3961 } else if (PType->isFunctionType())
3962 PType = PVDecl->getType();
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00003963 // Process argument qualifiers for user supplied arguments; such as,
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003964 // 'in', 'inout', etc.
Fariborz Jahanian4306d3c2008-12-20 23:29:59 +00003965 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003966 getObjCEncodingForType(PType, S);
Ken Dyck199c3d62010-01-11 17:06:35 +00003967 S += charUnitsToString(ParmOffset);
Ken Dyckaa8741a2010-01-11 19:19:56 +00003968 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003969 }
Douglas Gregorf968d832011-05-27 01:19:52 +00003970
3971 return false;
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003972}
3973
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003974/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003975/// property declaration. If non-NULL, Container must be either an
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00003976/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3977/// NULL when getting encodings for protocol properties.
Mike Stump1eb44332009-09-09 15:08:12 +00003978/// Property attributes are stored as a comma-delimited C string. The simple
3979/// attributes readonly and bycopy are encoded as single characters. The
3980/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3981/// encoded as single characters, followed by an identifier. Property types
3982/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian83bccb82009-01-20 20:04:12 +00003983/// these attributes are defined by the following enumeration:
3984/// @code
3985/// enum PropertyAttributes {
3986/// kPropertyReadOnly = 'R', // property is read-only.
3987/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
3988/// kPropertyByref = '&', // property is a reference to the value last assigned
3989/// kPropertyDynamic = 'D', // property is dynamic
3990/// kPropertyGetter = 'G', // followed by getter selector name
3991/// kPropertySetter = 'S', // followed by setter selector name
3992/// kPropertyInstanceVariable = 'V' // followed by instance variable name
3993/// kPropertyType = 't' // followed by old-style type encoding.
3994/// kPropertyWeak = 'W' // 'weak' property
3995/// kPropertyStrong = 'P' // property GC'able
3996/// kPropertyNonAtomic = 'N' // property non-atomic
3997/// };
3998/// @endcode
Mike Stump1eb44332009-09-09 15:08:12 +00003999void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004000 const Decl *Container,
Jay Foad4ba2a172011-01-12 09:06:06 +00004001 std::string& S) const {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004002 // Collect information from the property implementation decl(s).
4003 bool Dynamic = false;
4004 ObjCPropertyImplDecl *SynthesizePID = 0;
4005
4006 // FIXME: Duplicated code due to poor abstraction.
4007 if (Container) {
Mike Stump1eb44332009-09-09 15:08:12 +00004008 if (const ObjCCategoryImplDecl *CID =
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004009 dyn_cast<ObjCCategoryImplDecl>(Container)) {
4010 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004011 i = CID->propimpl_begin(), e = CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004012 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004013 ObjCPropertyImplDecl *PID = *i;
4014 if (PID->getPropertyDecl() == PD) {
4015 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4016 Dynamic = true;
4017 } else {
4018 SynthesizePID = PID;
4019 }
4020 }
4021 }
4022 } else {
Chris Lattner61710852008-10-05 17:34:18 +00004023 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004024 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004025 i = OID->propimpl_begin(), e = OID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00004026 i != e; ++i) {
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004027 ObjCPropertyImplDecl *PID = *i;
4028 if (PID->getPropertyDecl() == PD) {
4029 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4030 Dynamic = true;
4031 } else {
4032 SynthesizePID = PID;
4033 }
4034 }
Mike Stump1eb44332009-09-09 15:08:12 +00004035 }
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004036 }
4037 }
4038
4039 // FIXME: This is not very efficient.
4040 S = "T";
4041
4042 // Encode result type.
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004043 // GCC has some special rules regarding encoding of properties which
4044 // closely resembles encoding of ivars.
Mike Stump1eb44332009-09-09 15:08:12 +00004045 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004046 true /* outermost type */,
4047 true /* encoding for property */);
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004048
4049 if (PD->isReadOnly()) {
4050 S += ",R";
4051 } else {
4052 switch (PD->getSetterKind()) {
4053 case ObjCPropertyDecl::Assign: break;
4054 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump1eb44332009-09-09 15:08:12 +00004055 case ObjCPropertyDecl::Retain: S += ",&"; break;
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004056 }
4057 }
4058
4059 // It really isn't clear at all what this means, since properties
4060 // are "dynamic by default".
4061 if (Dynamic)
4062 S += ",D";
4063
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004064 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4065 S += ",N";
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004067 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4068 S += ",G";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004069 S += PD->getGetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004070 }
4071
4072 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4073 S += ",S";
Chris Lattner077bf5e2008-11-24 03:33:13 +00004074 S += PD->getSetterName().getAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004075 }
4076
4077 if (SynthesizePID) {
4078 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4079 S += ",V";
Chris Lattner39f34e92008-11-24 04:00:27 +00004080 S += OID->getNameAsString();
Daniel Dunbarc56f34a2008-08-28 04:38:10 +00004081 }
4082
4083 // FIXME: OBJCGC: weak & strong
4084}
4085
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004086/// getLegacyIntegralTypeEncoding -
Mike Stump1eb44332009-09-09 15:08:12 +00004087/// Another legacy compatibility encoding: 32-bit longs are encoded as
4088/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004089/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4090///
4091void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump8e1fab22009-07-22 18:58:19 +00004092 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall183700f2009-09-21 23:43:11 +00004093 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad4ba2a172011-01-12 09:06:06 +00004094 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004095 PointeeTy = UnsignedIntTy;
Mike Stump1eb44332009-09-09 15:08:12 +00004096 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004097 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004098 PointeeTy = IntTy;
4099 }
4100 }
4101}
4102
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004103void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Jay Foad4ba2a172011-01-12 09:06:06 +00004104 const FieldDecl *Field) const {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004105 // We follow the behavior of gcc, expanding structures which are
4106 // directly pointed to, and expanding embedded structures. Note that
4107 // these rules are sufficient to prevent recursive encoding of the
4108 // same type.
Mike Stump1eb44332009-09-09 15:08:12 +00004109 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian5b8c7d92008-12-22 23:22:27 +00004110 true /* outermost type */);
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004111}
4112
David Chisnall64fd7e82010-06-04 01:10:52 +00004113static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4114 switch (T->getAs<BuiltinType>()->getKind()) {
4115 default: assert(0 && "Unhandled builtin type kind");
4116 case BuiltinType::Void: return 'v';
4117 case BuiltinType::Bool: return 'B';
4118 case BuiltinType::Char_U:
4119 case BuiltinType::UChar: return 'C';
4120 case BuiltinType::UShort: return 'S';
4121 case BuiltinType::UInt: return 'I';
4122 case BuiltinType::ULong:
Jay Foad4ba2a172011-01-12 09:06:06 +00004123 return C->getIntWidth(T) == 32 ? 'L' : 'Q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004124 case BuiltinType::UInt128: return 'T';
4125 case BuiltinType::ULongLong: return 'Q';
4126 case BuiltinType::Char_S:
4127 case BuiltinType::SChar: return 'c';
4128 case BuiltinType::Short: return 's';
Chris Lattner3f59c972010-12-25 23:25:43 +00004129 case BuiltinType::WChar_S:
4130 case BuiltinType::WChar_U:
David Chisnall64fd7e82010-06-04 01:10:52 +00004131 case BuiltinType::Int: return 'i';
4132 case BuiltinType::Long:
Jay Foad4ba2a172011-01-12 09:06:06 +00004133 return C->getIntWidth(T) == 32 ? 'l' : 'q';
David Chisnall64fd7e82010-06-04 01:10:52 +00004134 case BuiltinType::LongLong: return 'q';
4135 case BuiltinType::Int128: return 't';
4136 case BuiltinType::Float: return 'f';
4137 case BuiltinType::Double: return 'd';
Daniel Dunbar3a0be842010-10-11 21:13:48 +00004138 case BuiltinType::LongDouble: return 'D';
David Chisnall64fd7e82010-06-04 01:10:52 +00004139 }
4140}
4141
Jay Foad4ba2a172011-01-12 09:06:06 +00004142static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnall64fd7e82010-06-04 01:10:52 +00004143 QualType T, const FieldDecl *FD) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004144 const Expr *E = FD->getBitWidth();
4145 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004146 S += 'b';
David Chisnall64fd7e82010-06-04 01:10:52 +00004147 // The NeXT runtime encodes bit fields as b followed by the number of bits.
4148 // The GNU runtime requires more information; bitfields are encoded as b,
4149 // then the offset (in bits) of the first element, then the type of the
4150 // bitfield, then the size in bits. For example, in this structure:
4151 //
4152 // struct
4153 // {
4154 // int integer;
4155 // int flags:2;
4156 // };
4157 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4158 // runtime, but b32i2 for the GNU runtime. The reason for this extra
4159 // information is not especially sensible, but we're stuck with it for
4160 // compatibility with GCC, although providing it breaks anything that
4161 // actually uses runtime introspection and wants to work on both runtimes...
4162 if (!Ctx->getLangOptions().NeXTRuntime) {
4163 const RecordDecl *RD = FD->getParent();
4164 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedman82905742011-07-07 01:54:01 +00004165 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
David Chisnallc7ff82c2010-12-26 20:12:30 +00004166 if (T->isEnumeralType())
4167 S += 'i';
4168 else
Jay Foad4ba2a172011-01-12 09:06:06 +00004169 S += ObjCEncodingForPrimitiveKind(Ctx, T);
David Chisnall64fd7e82010-06-04 01:10:52 +00004170 }
4171 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004172 S += llvm::utostr(N);
4173}
4174
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00004175// FIXME: Use SmallString for accumulating string.
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004176void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4177 bool ExpandPointedToStructures,
4178 bool ExpandStructures,
Daniel Dunbar153bfe52009-04-20 06:37:24 +00004179 const FieldDecl *FD,
Fariborz Jahanian090b3f72009-01-20 19:14:18 +00004180 bool OutermostType,
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004181 bool EncodingProperty,
4182 bool StructField) const {
David Chisnall64fd7e82010-06-04 01:10:52 +00004183 if (T->getAs<BuiltinType>()) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004184 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004185 return EncodeBitField(this, S, T, FD);
4186 S += ObjCEncodingForPrimitiveKind(this, T);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004187 return;
4188 }
Mike Stump1eb44332009-09-09 15:08:12 +00004189
John McCall183700f2009-09-21 23:43:11 +00004190 if (const ComplexType *CT = T->getAs<ComplexType>()) {
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004191 S += 'j';
Mike Stump1eb44332009-09-09 15:08:12 +00004192 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
Anders Carlssonc612f7b2009-04-09 21:55:45 +00004193 false);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004194 return;
4195 }
Fariborz Jahanian60bce3e2009-11-23 20:40:50 +00004196
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004197 // encoding for pointer or r3eference types.
4198 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004199 if (const PointerType *PT = T->getAs<PointerType>()) {
Fariborz Jahanian8d2c0a92009-11-30 18:43:52 +00004200 if (PT->isObjCSelType()) {
4201 S += ':';
4202 return;
4203 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004204 PointeeTy = PT->getPointeeType();
4205 }
4206 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4207 PointeeTy = RT->getPointeeType();
4208 if (!PointeeTy.isNull()) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004209 bool isReadOnly = false;
4210 // For historical/compatibility reasons, the read-only qualifier of the
4211 // pointee gets emitted _before_ the '^'. The read-only qualifier of
4212 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump1eb44332009-09-09 15:08:12 +00004213 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump8e1fab22009-07-22 18:58:19 +00004214 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004215 if (OutermostType && T.isConstQualified()) {
4216 isReadOnly = true;
4217 S += 'r';
4218 }
Mike Stump9fdbab32009-07-31 02:02:20 +00004219 } else if (OutermostType) {
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004220 QualType P = PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00004221 while (P->getAs<PointerType>())
4222 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004223 if (P.isConstQualified()) {
4224 isReadOnly = true;
4225 S += 'r';
4226 }
4227 }
4228 if (isReadOnly) {
4229 // Another legacy compatibility encoding. Some ObjC qualifier and type
4230 // combinations need to be rearranged.
4231 // Rewrite "in const" from "nr" to "rn"
Chris Lattner5f9e2722011-07-23 10:55:15 +00004232 if (StringRef(S).endswith("nr"))
Benjamin Kramer02379412010-04-27 17:12:11 +00004233 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004234 }
Mike Stump1eb44332009-09-09 15:08:12 +00004235
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004236 if (PointeeTy->isCharType()) {
4237 // char pointer types should be encoded as '*' unless it is a
4238 // type that has been typedef'd to 'BOOL'.
Anders Carlssone8c49532007-10-29 06:33:42 +00004239 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004240 S += '*';
4241 return;
4242 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004243 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff9533a7f2009-07-22 17:14:51 +00004244 // GCC binary compat: Need to convert "struct objc_class *" to "#".
4245 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4246 S += '#';
4247 return;
4248 }
4249 // GCC binary compat: Need to convert "struct objc_object *" to "@".
4250 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4251 S += '@';
4252 return;
4253 }
4254 // fall through...
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004255 }
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004256 S += '^';
Fariborz Jahaniana1c033e2008-12-23 19:56:47 +00004257 getLegacyIntegralTypeEncoding(PointeeTy);
4258
Mike Stump1eb44332009-09-09 15:08:12 +00004259 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004260 NULL);
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004261 return;
4262 }
Fariborz Jahanianaa1d7612010-04-13 23:45:47 +00004263
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004264 if (const ArrayType *AT =
4265 // Ignore type qualifiers etc.
4266 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004267 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlsson559a8332009-02-22 01:38:57 +00004268 // Incomplete arrays are encoded as a pointer to the array element.
4269 S += '^';
4270
Mike Stump1eb44332009-09-09 15:08:12 +00004271 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004272 false, ExpandStructures, FD);
4273 } else {
4274 S += '[';
Mike Stump1eb44332009-09-09 15:08:12 +00004275
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004276 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4277 if (getTypeSize(CAT->getElementType()) == 0)
4278 S += '0';
4279 else
4280 S += llvm::utostr(CAT->getSize().getZExtValue());
4281 } else {
Anders Carlsson559a8332009-02-22 01:38:57 +00004282 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004283 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4284 "Unknown array type!");
Anders Carlsson559a8332009-02-22 01:38:57 +00004285 S += '0';
4286 }
Mike Stump1eb44332009-09-09 15:08:12 +00004287
4288 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlsson559a8332009-02-22 01:38:57 +00004289 false, ExpandStructures, FD);
4290 S += ']';
4291 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004292 return;
4293 }
Mike Stump1eb44332009-09-09 15:08:12 +00004294
John McCall183700f2009-09-21 23:43:11 +00004295 if (T->getAs<FunctionType>()) {
Anders Carlssonc0a87b72007-10-30 00:06:20 +00004296 S += '?';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004297 return;
4298 }
Mike Stump1eb44332009-09-09 15:08:12 +00004299
Ted Kremenek6217b802009-07-29 21:53:49 +00004300 if (const RecordType *RTy = T->getAs<RecordType>()) {
Daniel Dunbar82a6cfb2008-10-17 07:30:50 +00004301 RecordDecl *RDecl = RTy->getDecl();
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004302 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004303 // Anonymous structures print as '?'
4304 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4305 S += II->getName();
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004306 if (ClassTemplateSpecializationDecl *Spec
4307 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4308 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4309 std::string TemplateArgsStr
4310 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00004311 TemplateArgs.data(),
4312 TemplateArgs.size(),
Fariborz Jahanian6fb94392010-05-07 00:28:49 +00004313 (*this).PrintingPolicy);
4314
4315 S += TemplateArgsStr;
4316 }
Daniel Dunbar502a4a12008-10-17 06:22:57 +00004317 } else {
4318 S += '?';
4319 }
Daniel Dunbar0d504c12008-10-17 20:21:44 +00004320 if (ExpandStructures) {
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004321 S += '=';
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004322 if (!RDecl->isUnion()) {
4323 getObjCEncodingForStructureImpl(RDecl, S, FD);
4324 } else {
4325 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4326 FieldEnd = RDecl->field_end();
4327 Field != FieldEnd; ++Field) {
4328 if (FD) {
4329 S += '"';
4330 S += Field->getNameAsString();
4331 S += '"';
4332 }
Mike Stump1eb44332009-09-09 15:08:12 +00004333
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004334 // Special case bit-fields.
4335 if (Field->isBitField()) {
4336 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4337 (*Field));
4338 } else {
4339 QualType qt = Field->getType();
4340 getLegacyIntegralTypeEncoding(qt);
4341 getObjCEncodingForTypeImpl(qt, S, false, true,
4342 FD, /*OutermostType*/false,
4343 /*EncodingProperty*/false,
4344 /*StructField*/true);
4345 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004346 }
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00004347 }
Fariborz Jahanian6de88a82007-11-13 23:21:38 +00004348 }
Daniel Dunbard96b35b2008-10-17 16:17:37 +00004349 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004350 return;
4351 }
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004352
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004353 if (T->isEnumeralType()) {
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004354 if (FD && FD->isBitField())
David Chisnall64fd7e82010-06-04 01:10:52 +00004355 EncodeBitField(this, S, T, FD);
Fariborz Jahanian8b4bf902009-01-13 01:18:13 +00004356 else
4357 S += 'i';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004358 return;
4359 }
Mike Stump1eb44332009-09-09 15:08:12 +00004360
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004361 if (T->isBlockPointerType()) {
Steve Naroff21a98b12009-02-02 18:24:29 +00004362 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004363 return;
4364 }
Mike Stump1eb44332009-09-09 15:08:12 +00004365
John McCallc12c5bb2010-05-15 11:32:37 +00004366 // Ignore protocol qualifiers when mangling at this level.
4367 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4368 T = OT->getBaseType();
4369
John McCall0953e762009-09-24 19:53:00 +00004370 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004371 // @encode(class_name)
John McCall0953e762009-09-24 19:53:00 +00004372 ObjCInterfaceDecl *OI = OIT->getDecl();
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004373 S += '{';
4374 const IdentifierInfo *II = OI->getIdentifier();
4375 S += II->getName();
4376 S += '=';
Jordy Rosedb8264e2011-07-22 02:08:32 +00004377 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004378 DeepCollectObjCIvars(OI, true, Ivars);
4379 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00004380 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004381 if (Field->isBitField())
4382 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004383 else
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00004384 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004385 }
4386 S += '}';
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004387 return;
Fariborz Jahanian43822ea2008-12-19 23:34:38 +00004388 }
Mike Stump1eb44332009-09-09 15:08:12 +00004389
John McCall183700f2009-09-21 23:43:11 +00004390 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004391 if (OPT->isObjCIdType()) {
4392 S += '@';
4393 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004394 }
Mike Stump1eb44332009-09-09 15:08:12 +00004395
Steve Naroff27d20a22009-10-28 22:03:49 +00004396 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4397 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4398 // Since this is a binary compatibility issue, need to consult with runtime
4399 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff14108da2009-07-10 23:34:53 +00004400 S += '#';
4401 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004402 }
Mike Stump1eb44332009-09-09 15:08:12 +00004403
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004404 if (OPT->isObjCQualifiedIdType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004405 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff14108da2009-07-10 23:34:53 +00004406 ExpandPointedToStructures,
4407 ExpandStructures, FD);
4408 if (FD || EncodingProperty) {
4409 // Note that we do extended encoding of protocol qualifer list
4410 // Only when doing ivar or property encoding.
Steve Naroff14108da2009-07-10 23:34:53 +00004411 S += '"';
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004412 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4413 E = OPT->qual_end(); I != E; ++I) {
Steve Naroff14108da2009-07-10 23:34:53 +00004414 S += '<';
4415 S += (*I)->getNameAsString();
4416 S += '>';
4417 }
4418 S += '"';
4419 }
4420 return;
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004421 }
Mike Stump1eb44332009-09-09 15:08:12 +00004422
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004423 QualType PointeeTy = OPT->getPointeeType();
4424 if (!EncodingProperty &&
4425 isa<TypedefType>(PointeeTy.getTypePtr())) {
4426 // Another historical/compatibility reason.
Mike Stump1eb44332009-09-09 15:08:12 +00004427 // We encode the underlying type which comes out as
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004428 // {...};
4429 S += '^';
Mike Stump1eb44332009-09-09 15:08:12 +00004430 getObjCEncodingForTypeImpl(PointeeTy, S,
4431 false, ExpandPointedToStructures,
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004432 NULL);
Steve Naroff14108da2009-07-10 23:34:53 +00004433 return;
4434 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004435
4436 S += '@';
Steve Naroff27d20a22009-10-28 22:03:49 +00004437 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004438 S += '"';
Steve Naroff27d20a22009-10-28 22:03:49 +00004439 S += OPT->getInterfaceDecl()->getIdentifier()->getName();
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004440 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4441 E = OPT->qual_end(); I != E; ++I) {
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004442 S += '<';
4443 S += (*I)->getNameAsString();
4444 S += '>';
Mike Stump1eb44332009-09-09 15:08:12 +00004445 }
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004446 S += '"';
4447 }
4448 return;
4449 }
Mike Stump1eb44332009-09-09 15:08:12 +00004450
John McCall532ec7b2010-05-17 23:56:34 +00004451 // gcc just blithely ignores member pointers.
4452 // TODO: maybe there should be a mangling for these
4453 if (T->getAs<MemberPointerType>())
4454 return;
Fariborz Jahaniane6012c72010-10-07 21:25:25 +00004455
4456 if (T->isVectorType()) {
4457 // This matches gcc's encoding, even though technically it is
4458 // insufficient.
4459 // FIXME. We should do a better job than gcc.
4460 return;
4461 }
4462
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004463 assert(0 && "@encode for type not implemented!");
Anders Carlsson85f9bce2007-10-29 05:01:08 +00004464}
4465
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004466void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4467 std::string &S,
4468 const FieldDecl *FD,
4469 bool includeVBases) const {
4470 assert(RDecl && "Expected non-null RecordDecl");
4471 assert(!RDecl->isUnion() && "Should not be called for unions");
4472 if (!RDecl->getDefinition())
4473 return;
4474
4475 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4476 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4477 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4478
4479 if (CXXRec) {
4480 for (CXXRecordDecl::base_class_iterator
4481 BI = CXXRec->bases_begin(),
4482 BE = CXXRec->bases_end(); BI != BE; ++BI) {
4483 if (!BI->isVirtual()) {
4484 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004485 if (base->isEmpty())
4486 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004487 uint64_t offs = layout.getBaseClassOffsetInBits(base);
4488 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4489 std::make_pair(offs, base));
4490 }
4491 }
4492 }
4493
4494 unsigned i = 0;
4495 for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4496 FieldEnd = RDecl->field_end();
4497 Field != FieldEnd; ++Field, ++i) {
4498 uint64_t offs = layout.getFieldOffset(i);
4499 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4500 std::make_pair(offs, *Field));
4501 }
4502
4503 if (CXXRec && includeVBases) {
4504 for (CXXRecordDecl::base_class_iterator
4505 BI = CXXRec->vbases_begin(),
4506 BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4507 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004508 if (base->isEmpty())
4509 continue;
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004510 uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4511 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4512 std::make_pair(offs, base));
4513 }
4514 }
4515
4516 CharUnits size;
4517 if (CXXRec) {
4518 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4519 } else {
4520 size = layout.getSize();
4521 }
4522
4523 uint64_t CurOffs = 0;
4524 std::multimap<uint64_t, NamedDecl *>::iterator
4525 CurLayObj = FieldOrBaseOffsets.begin();
4526
4527 if (CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) {
4528 assert(CXXRec && CXXRec->isDynamicClass() &&
4529 "Offset 0 was empty but no VTable ?");
4530 if (FD) {
4531 S += "\"_vptr$";
4532 std::string recname = CXXRec->getNameAsString();
4533 if (recname.empty()) recname = "?";
4534 S += recname;
4535 S += '"';
4536 }
4537 S += "^^?";
4538 CurOffs += getTypeSize(VoidPtrTy);
4539 }
4540
4541 if (!RDecl->hasFlexibleArrayMember()) {
4542 // Mark the end of the structure.
4543 uint64_t offs = toBits(size);
4544 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4545 std::make_pair(offs, (NamedDecl*)0));
4546 }
4547
4548 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4549 assert(CurOffs <= CurLayObj->first);
4550
4551 if (CurOffs < CurLayObj->first) {
4552 uint64_t padding = CurLayObj->first - CurOffs;
4553 // FIXME: There doesn't seem to be a way to indicate in the encoding that
4554 // packing/alignment of members is different that normal, in which case
4555 // the encoding will be out-of-sync with the real layout.
4556 // If the runtime switches to just consider the size of types without
4557 // taking into account alignment, we could make padding explicit in the
4558 // encoding (e.g. using arrays of chars). The encoding strings would be
4559 // longer then though.
4560 CurOffs += padding;
4561 }
4562
4563 NamedDecl *dcl = CurLayObj->second;
4564 if (dcl == 0)
4565 break; // reached end of structure.
4566
4567 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4568 // We expand the bases without their virtual bases since those are going
4569 // in the initial structure. Note that this differs from gcc which
4570 // expands virtual bases each time one is encountered in the hierarchy,
4571 // making the encoding type bigger than it really is.
4572 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
Argyrios Kyrtzidis829f2002011-06-17 23:19:38 +00004573 assert(!base->isEmpty());
4574 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Argyrios Kyrtzidis26361972011-05-17 00:46:38 +00004575 } else {
4576 FieldDecl *field = cast<FieldDecl>(dcl);
4577 if (FD) {
4578 S += '"';
4579 S += field->getNameAsString();
4580 S += '"';
4581 }
4582
4583 if (field->isBitField()) {
4584 EncodeBitField(this, S, field->getType(), field);
4585 CurOffs += field->getBitWidth()->EvaluateAsInt(*this).getZExtValue();
4586 } else {
4587 QualType qt = field->getType();
4588 getLegacyIntegralTypeEncoding(qt);
4589 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4590 /*OutermostType*/false,
4591 /*EncodingProperty*/false,
4592 /*StructField*/true);
4593 CurOffs += getTypeSize(field->getType());
4594 }
4595 }
4596 }
4597}
4598
Mike Stump1eb44332009-09-09 15:08:12 +00004599void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianecb01e62007-11-01 17:18:37 +00004600 std::string& S) const {
4601 if (QT & Decl::OBJC_TQ_In)
4602 S += 'n';
4603 if (QT & Decl::OBJC_TQ_Inout)
4604 S += 'N';
4605 if (QT & Decl::OBJC_TQ_Out)
4606 S += 'o';
4607 if (QT & Decl::OBJC_TQ_Bycopy)
4608 S += 'O';
4609 if (QT & Decl::OBJC_TQ_Byref)
4610 S += 'R';
4611 if (QT & Decl::OBJC_TQ_Oneway)
4612 S += 'V';
4613}
4614
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004615void ASTContext::setBuiltinVaListType(QualType T) {
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004616 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Anders Carlssonb2cf3572007-10-11 01:00:40 +00004618 BuiltinVaListType = T;
4619}
4620
Douglas Gregor4dfd02a2011-08-12 05:46:01 +00004621TypedefDecl *ASTContext::getObjCIdDecl() const {
4622 if (!ObjCIdDecl) {
4623 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4624 T = getObjCObjectPointerType(T);
4625 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4626 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4627 getTranslationUnitDecl(),
4628 SourceLocation(), SourceLocation(),
4629 &Idents.get("id"), IdInfo);
4630 }
4631
4632 return ObjCIdDecl;
Steve Naroff7e219e42007-10-15 14:41:52 +00004633}
4634
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004635void ASTContext::setObjCSelType(QualType T) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +00004636 ObjCSelTypedefType = T;
Fariborz Jahanianb62f6812007-10-16 20:40:23 +00004637}
4638
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004639void ASTContext::setObjCProtoType(QualType QT) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004640 ObjCProtoType = QT;
Fariborz Jahanian390d50a2007-10-17 16:58:11 +00004641}
4642
Chris Lattnerce7b38c2009-07-13 00:10:46 +00004643void ASTContext::setObjCClassType(QualType T) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00004644 ObjCClassTypedefType = T;
Anders Carlsson8baaca52007-10-31 02:53:19 +00004645}
4646
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004647void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump1eb44332009-09-09 15:08:12 +00004648 assert(ObjCConstantStringType.isNull() &&
Steve Naroff21988912007-10-15 23:35:17 +00004649 "'NSConstantString' type already set!");
Mike Stump1eb44332009-09-09 15:08:12 +00004650
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004651 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Naroff21988912007-10-15 23:35:17 +00004652}
4653
John McCall0bd6feb2009-12-02 08:04:21 +00004654/// \brief Retrieve the template name that corresponds to a non-empty
4655/// lookup.
Jay Foad4ba2a172011-01-12 09:06:06 +00004656TemplateName
4657ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4658 UnresolvedSetIterator End) const {
John McCall0bd6feb2009-12-02 08:04:21 +00004659 unsigned size = End - Begin;
4660 assert(size > 1 && "set is not overloaded!");
4661
4662 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4663 size * sizeof(FunctionTemplateDecl*));
4664 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4665
4666 NamedDecl **Storage = OT->getStorage();
John McCalleec51cf2010-01-20 00:46:10 +00004667 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCall0bd6feb2009-12-02 08:04:21 +00004668 NamedDecl *D = *I;
4669 assert(isa<FunctionTemplateDecl>(D) ||
4670 (isa<UsingShadowDecl>(D) &&
4671 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4672 *Storage++ = D;
4673 }
4674
4675 return TemplateName(OT);
4676}
4677
Douglas Gregor7532dc62009-03-30 22:58:21 +00004678/// \brief Retrieve the template name that represents a qualified
4679/// template name such as \c std::vector.
Jay Foad4ba2a172011-01-12 09:06:06 +00004680TemplateName
4681ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4682 bool TemplateKeyword,
4683 TemplateDecl *Template) const {
Douglas Gregor0f0ea2a2011-03-03 17:04:51 +00004684 assert(NNS && "Missing nested-name-specifier in qualified template name");
4685
Douglas Gregor789b1f62010-02-04 18:10:26 +00004686 // FIXME: Canonicalization?
Douglas Gregor7532dc62009-03-30 22:58:21 +00004687 llvm::FoldingSetNodeID ID;
4688 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4689
4690 void *InsertPos = 0;
4691 QualifiedTemplateName *QTN =
4692 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4693 if (!QTN) {
4694 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4695 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4696 }
4697
4698 return TemplateName(QTN);
4699}
4700
4701/// \brief Retrieve the template name that represents a dependent
4702/// template name such as \c MetaFun::template apply.
Jay Foad4ba2a172011-01-12 09:06:06 +00004703TemplateName
4704ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4705 const IdentifierInfo *Name) const {
Mike Stump1eb44332009-09-09 15:08:12 +00004706 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00004707 "Nested name specifier must be dependent");
Douglas Gregor7532dc62009-03-30 22:58:21 +00004708
4709 llvm::FoldingSetNodeID ID;
4710 DependentTemplateName::Profile(ID, NNS, Name);
4711
4712 void *InsertPos = 0;
4713 DependentTemplateName *QTN =
4714 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4715
4716 if (QTN)
4717 return TemplateName(QTN);
4718
4719 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4720 if (CanonNNS == NNS) {
4721 QTN = new (*this,4) DependentTemplateName(NNS, Name);
4722 } else {
4723 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4724 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004725 DependentTemplateName *CheckQTN =
4726 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4727 assert(!CheckQTN && "Dependent type name canonicalization broken");
4728 (void)CheckQTN;
Douglas Gregor7532dc62009-03-30 22:58:21 +00004729 }
4730
4731 DependentTemplateNames.InsertNode(QTN, InsertPos);
4732 return TemplateName(QTN);
4733}
4734
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004735/// \brief Retrieve the template name that represents a dependent
4736/// template name such as \c MetaFun::template operator+.
4737TemplateName
4738ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad4ba2a172011-01-12 09:06:06 +00004739 OverloadedOperatorKind Operator) const {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004740 assert((!NNS || NNS->isDependent()) &&
4741 "Nested name specifier must be dependent");
4742
4743 llvm::FoldingSetNodeID ID;
4744 DependentTemplateName::Profile(ID, NNS, Operator);
4745
4746 void *InsertPos = 0;
Douglas Gregor789b1f62010-02-04 18:10:26 +00004747 DependentTemplateName *QTN
4748 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004749
4750 if (QTN)
4751 return TemplateName(QTN);
4752
4753 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4754 if (CanonNNS == NNS) {
4755 QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4756 } else {
4757 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4758 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
Douglas Gregor789b1f62010-02-04 18:10:26 +00004759
4760 DependentTemplateName *CheckQTN
4761 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4762 assert(!CheckQTN && "Dependent template name canonicalization broken");
4763 (void)CheckQTN;
Douglas Gregorca1bdd72009-11-04 00:56:37 +00004764 }
4765
4766 DependentTemplateNames.InsertNode(QTN, InsertPos);
4767 return TemplateName(QTN);
4768}
4769
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004770TemplateName
John McCall14606042011-06-30 08:33:18 +00004771ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
4772 TemplateName replacement) const {
4773 llvm::FoldingSetNodeID ID;
4774 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
4775
4776 void *insertPos = 0;
4777 SubstTemplateTemplateParmStorage *subst
4778 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
4779
4780 if (!subst) {
4781 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
4782 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
4783 }
4784
4785 return TemplateName(subst);
4786}
4787
4788TemplateName
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004789ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
4790 const TemplateArgument &ArgPack) const {
4791 ASTContext &Self = const_cast<ASTContext &>(*this);
4792 llvm::FoldingSetNodeID ID;
4793 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
4794
4795 void *InsertPos = 0;
4796 SubstTemplateTemplateParmPackStorage *Subst
4797 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
4798
4799 if (!Subst) {
John McCall14606042011-06-30 08:33:18 +00004800 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor1aee05d2011-01-15 06:45:20 +00004801 ArgPack.pack_size(),
4802 ArgPack.pack_begin());
4803 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
4804 }
4805
4806 return TemplateName(Subst);
4807}
4808
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004809/// getFromTargetType - Given one of the integer types provided by
Douglas Gregord9341122008-11-03 15:57:00 +00004810/// TargetInfo, produce the corresponding type. The unsigned @p Type
4811/// is actually a value of type @c TargetInfo::IntType.
John McCalle27ec8a2009-10-23 23:03:21 +00004812CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004813 switch (Type) {
John McCalle27ec8a2009-10-23 23:03:21 +00004814 case TargetInfo::NoInt: return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004815 case TargetInfo::SignedShort: return ShortTy;
4816 case TargetInfo::UnsignedShort: return UnsignedShortTy;
4817 case TargetInfo::SignedInt: return IntTy;
4818 case TargetInfo::UnsignedInt: return UnsignedIntTy;
4819 case TargetInfo::SignedLong: return LongTy;
4820 case TargetInfo::UnsignedLong: return UnsignedLongTy;
4821 case TargetInfo::SignedLongLong: return LongLongTy;
4822 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4823 }
4824
4825 assert(false && "Unhandled TargetInfo::IntType value");
John McCalle27ec8a2009-10-23 23:03:21 +00004826 return CanQualType();
Douglas Gregorb4e66d52008-11-03 14:12:49 +00004827}
Ted Kremenekb6ccaac2008-07-24 23:58:27 +00004828
4829//===----------------------------------------------------------------------===//
4830// Type Predicates.
4831//===----------------------------------------------------------------------===//
4832
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004833/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4834/// garbage collection attribute.
4835///
John McCallae278a32011-01-12 00:34:59 +00004836Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
4837 if (getLangOptions().getGCMode() == LangOptions::NonGC)
4838 return Qualifiers::GCNone;
4839
4840 assert(getLangOptions().ObjC1);
4841 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
4842
4843 // Default behaviour under objective-C's gc is for ObjC pointers
4844 // (or pointers to them) be treated as though they were declared
4845 // as __strong.
4846 if (GCAttrs == Qualifiers::GCNone) {
4847 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4848 return Qualifiers::Strong;
4849 else if (Ty->isPointerType())
4850 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4851 } else {
4852 // It's not valid to set GC attributes on anything that isn't a
4853 // pointer.
4854#ifndef NDEBUG
4855 QualType CT = Ty->getCanonicalTypeInternal();
4856 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
4857 CT = AT->getElementType();
4858 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
4859#endif
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004860 }
Chris Lattnerb7d25532009-02-18 22:53:11 +00004861 return GCAttrs;
Fariborz Jahanian4fd83ea2009-02-18 21:49:28 +00004862}
4863
Chris Lattner6ac46a42008-04-07 06:51:04 +00004864//===----------------------------------------------------------------------===//
4865// Type Compatibility Testing
4866//===----------------------------------------------------------------------===//
Chris Lattner770951b2007-11-01 05:03:41 +00004867
Mike Stump1eb44332009-09-09 15:08:12 +00004868/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00004869/// compatible.
4870static bool areCompatVectorTypes(const VectorType *LHS,
4871 const VectorType *RHS) {
John McCall467b27b2009-10-22 20:10:53 +00004872 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner6ac46a42008-04-07 06:51:04 +00004873 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner61710852008-10-05 17:34:18 +00004874 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner6ac46a42008-04-07 06:51:04 +00004875}
4876
Douglas Gregor255210e2010-08-06 10:14:59 +00004877bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
4878 QualType SecondVec) {
4879 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
4880 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
4881
4882 if (hasSameUnqualifiedType(FirstVec, SecondVec))
4883 return true;
4884
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004885 // Treat Neon vector types and most AltiVec vector types as if they are the
4886 // equivalent GCC vector types.
Douglas Gregor255210e2010-08-06 10:14:59 +00004887 const VectorType *First = FirstVec->getAs<VectorType>();
4888 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004889 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor255210e2010-08-06 10:14:59 +00004890 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsonf69eb7c2010-11-12 17:24:54 +00004891 First->getVectorKind() != VectorType::AltiVecPixel &&
4892 First->getVectorKind() != VectorType::AltiVecBool &&
4893 Second->getVectorKind() != VectorType::AltiVecPixel &&
4894 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor255210e2010-08-06 10:14:59 +00004895 return true;
4896
4897 return false;
4898}
4899
Steve Naroff4084c302009-07-23 01:01:38 +00004900//===----------------------------------------------------------------------===//
4901// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4902//===----------------------------------------------------------------------===//
4903
4904/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4905/// inheritance hierarchy of 'rProto'.
Jay Foad4ba2a172011-01-12 09:06:06 +00004906bool
4907ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4908 ObjCProtocolDecl *rProto) const {
Steve Naroff4084c302009-07-23 01:01:38 +00004909 if (lProto == rProto)
4910 return true;
4911 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4912 E = rProto->protocol_end(); PI != E; ++PI)
4913 if (ProtocolCompatibleWithProtocol(lProto, *PI))
4914 return true;
4915 return false;
4916}
4917
Steve Naroff4084c302009-07-23 01:01:38 +00004918/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4919/// return true if lhs's protocols conform to rhs's protocol; false
4920/// otherwise.
4921bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4922 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4923 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4924 return false;
4925}
4926
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00004927/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and
4928/// Class<p1, ...>.
4929bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
4930 QualType rhs) {
4931 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
4932 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4933 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
4934
4935 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4936 E = lhsQID->qual_end(); I != E; ++I) {
4937 bool match = false;
4938 ObjCProtocolDecl *lhsProto = *I;
4939 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4940 E = rhsOPT->qual_end(); J != E; ++J) {
4941 ObjCProtocolDecl *rhsProto = *J;
4942 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
4943 match = true;
4944 break;
4945 }
4946 }
4947 if (!match)
4948 return false;
4949 }
4950 return true;
4951}
4952
Steve Naroff4084c302009-07-23 01:01:38 +00004953/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4954/// ObjCQualifiedIDType.
4955bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4956 bool compare) {
4957 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump1eb44332009-09-09 15:08:12 +00004958 if (lhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004959 lhs->isObjCIdType() || lhs->isObjCClassType())
4960 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004961 else if (rhs->isVoidPointerType() ||
Steve Naroff4084c302009-07-23 01:01:38 +00004962 rhs->isObjCIdType() || rhs->isObjCClassType())
4963 return true;
4964
4965 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall183700f2009-09-21 23:43:11 +00004966 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00004967
Steve Naroff4084c302009-07-23 01:01:38 +00004968 if (!rhsOPT) return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004969
Steve Naroff4084c302009-07-23 01:01:38 +00004970 if (rhsOPT->qual_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004971 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff4084c302009-07-23 01:01:38 +00004972 // make sure we check the class hierarchy.
4973 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4974 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4975 E = lhsQID->qual_end(); I != E; ++I) {
4976 // when comparing an id<P> on lhs with a static type on rhs,
4977 // see if static class implements all of id's protocols, directly or
4978 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00004979 if (!rhsID->ClassImplementsProtocol(*I, true))
Steve Naroff4084c302009-07-23 01:01:38 +00004980 return false;
4981 }
4982 }
4983 // If there are no qualifiers and no interface, we have an 'id'.
4984 return true;
4985 }
Mike Stump1eb44332009-09-09 15:08:12 +00004986 // Both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00004987 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4988 E = lhsQID->qual_end(); I != E; ++I) {
4989 ObjCProtocolDecl *lhsProto = *I;
4990 bool match = false;
4991
4992 // when comparing an id<P> on lhs with a static type on rhs,
4993 // see if static class implements all of id's protocols, directly or
4994 // through its super class and categories.
4995 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4996 E = rhsOPT->qual_end(); J != E; ++J) {
4997 ObjCProtocolDecl *rhsProto = *J;
4998 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4999 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5000 match = true;
5001 break;
5002 }
5003 }
Mike Stump1eb44332009-09-09 15:08:12 +00005004 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff4084c302009-07-23 01:01:38 +00005005 // make sure we check the class hierarchy.
5006 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5007 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5008 E = lhsQID->qual_end(); I != E; ++I) {
5009 // when comparing an id<P> on lhs with a static type on rhs,
5010 // see if static class implements all of id's protocols, directly or
5011 // through its super class and categories.
Fariborz Jahanian0fd89042009-08-11 22:02:25 +00005012 if (rhsID->ClassImplementsProtocol(*I, true)) {
Steve Naroff4084c302009-07-23 01:01:38 +00005013 match = true;
5014 break;
5015 }
5016 }
5017 }
5018 if (!match)
5019 return false;
5020 }
Mike Stump1eb44332009-09-09 15:08:12 +00005021
Steve Naroff4084c302009-07-23 01:01:38 +00005022 return true;
5023 }
Mike Stump1eb44332009-09-09 15:08:12 +00005024
Steve Naroff4084c302009-07-23 01:01:38 +00005025 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5026 assert(rhsQID && "One of the LHS/RHS should be id<x>");
5027
Mike Stump1eb44332009-09-09 15:08:12 +00005028 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff4084c302009-07-23 01:01:38 +00005029 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005030 // If both the right and left sides have qualifiers.
Steve Naroff4084c302009-07-23 01:01:38 +00005031 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5032 E = lhsOPT->qual_end(); I != E; ++I) {
5033 ObjCProtocolDecl *lhsProto = *I;
5034 bool match = false;
5035
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005036 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff4084c302009-07-23 01:01:38 +00005037 // see if static class implements all of id's protocols, directly or
5038 // through its super class and categories.
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005039 // First, lhs protocols in the qualifier list must be found, direct
5040 // or indirect in rhs's qualifier list or it is a mismatch.
Steve Naroff4084c302009-07-23 01:01:38 +00005041 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5042 E = rhsQID->qual_end(); J != E; ++J) {
5043 ObjCProtocolDecl *rhsProto = *J;
5044 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5045 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5046 match = true;
5047 break;
5048 }
5049 }
5050 if (!match)
5051 return false;
5052 }
Fariborz Jahaniande5b17e2010-11-01 20:47:16 +00005053
5054 // Static class's protocols, or its super class or category protocols
5055 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5056 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5057 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5058 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5059 // This is rather dubious but matches gcc's behavior. If lhs has
5060 // no type qualifier and its class has no static protocol(s)
5061 // assume that it is mismatch.
5062 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5063 return false;
5064 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5065 LHSInheritedProtocols.begin(),
5066 E = LHSInheritedProtocols.end(); I != E; ++I) {
5067 bool match = false;
5068 ObjCProtocolDecl *lhsProto = (*I);
5069 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5070 E = rhsQID->qual_end(); J != E; ++J) {
5071 ObjCProtocolDecl *rhsProto = *J;
5072 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5073 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5074 match = true;
5075 break;
5076 }
5077 }
5078 if (!match)
5079 return false;
5080 }
5081 }
Steve Naroff4084c302009-07-23 01:01:38 +00005082 return true;
5083 }
5084 return false;
5085}
5086
Eli Friedman3d815e72008-08-22 00:56:42 +00005087/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner6ac46a42008-04-07 06:51:04 +00005088/// compatible for assignment from RHS to LHS. This handles validation of any
5089/// protocol qualifiers on the LHS or RHS.
5090///
Steve Naroff14108da2009-07-10 23:34:53 +00005091bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5092 const ObjCObjectPointerType *RHSOPT) {
John McCallc12c5bb2010-05-15 11:32:37 +00005093 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5094 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5095
Steve Naroffde2e22d2009-07-15 18:40:39 +00005096 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCallc12c5bb2010-05-15 11:32:37 +00005097 if (LHS->isObjCUnqualifiedIdOrClass() ||
5098 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff14108da2009-07-10 23:34:53 +00005099 return true;
5100
John McCallc12c5bb2010-05-15 11:32:37 +00005101 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
Mike Stump1eb44332009-09-09 15:08:12 +00005102 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5103 QualType(RHSOPT,0),
Steve Naroff4084c302009-07-23 01:01:38 +00005104 false);
Fariborz Jahaniana8f8dac2010-07-19 22:02:22 +00005105
5106 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5107 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5108 QualType(RHSOPT,0));
5109
John McCallc12c5bb2010-05-15 11:32:37 +00005110 // If we have 2 user-defined types, fall into that path.
5111 if (LHS->getInterface() && RHS->getInterface())
Steve Naroff4084c302009-07-23 01:01:38 +00005112 return canAssignObjCInterfaces(LHS, RHS);
Mike Stump1eb44332009-09-09 15:08:12 +00005113
Steve Naroff4084c302009-07-23 01:01:38 +00005114 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005115}
5116
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005117/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00005118/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005119/// arguments in block literals. When passed as arguments, passing 'A*' where
5120/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5121/// not OK. For the return type, the opposite is not OK.
5122bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5123 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005124 const ObjCObjectPointerType *RHSOPT,
5125 bool BlockReturnType) {
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005126 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005127 return true;
5128
5129 if (LHSOPT->isObjCBuiltinType()) {
5130 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5131 }
5132
Fariborz Jahaniana9834482010-04-06 17:23:39 +00005133 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005134 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5135 QualType(RHSOPT,0),
5136 false);
5137
5138 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5139 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5140 if (LHS && RHS) { // We have 2 user-defined types.
5141 if (LHS != RHS) {
5142 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005143 return BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005144 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005145 return !BlockReturnType;
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005146 }
5147 else
5148 return true;
5149 }
5150 return false;
5151}
5152
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005153/// getIntersectionOfProtocols - This routine finds the intersection of set
5154/// of protocols inherited from two distinct objective-c pointer objects.
5155/// It is used to build composite qualifier list of the composite type of
5156/// the conditional expression involving two objective-c pointer objects.
5157static
5158void getIntersectionOfProtocols(ASTContext &Context,
5159 const ObjCObjectPointerType *LHSOPT,
5160 const ObjCObjectPointerType *RHSOPT,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005161 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005162
John McCallc12c5bb2010-05-15 11:32:37 +00005163 const ObjCObjectType* LHS = LHSOPT->getObjectType();
5164 const ObjCObjectType* RHS = RHSOPT->getObjectType();
5165 assert(LHS->getInterface() && "LHS must have an interface base");
5166 assert(RHS->getInterface() && "RHS must have an interface base");
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005167
5168 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5169 unsigned LHSNumProtocols = LHS->getNumProtocols();
5170 if (LHSNumProtocols > 0)
5171 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5172 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005173 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005174 Context.CollectInheritedProtocols(LHS->getInterface(),
5175 LHSInheritedProtocols);
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005176 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5177 LHSInheritedProtocols.end());
5178 }
5179
5180 unsigned RHSNumProtocols = RHS->getNumProtocols();
5181 if (RHSNumProtocols > 0) {
Dan Gohmancb421fa2010-04-19 16:39:44 +00005182 ObjCProtocolDecl **RHSProtocols =
5183 const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005184 for (unsigned i = 0; i < RHSNumProtocols; ++i)
5185 if (InheritedProtocolSet.count(RHSProtocols[i]))
5186 IntersectionOfProtocols.push_back(RHSProtocols[i]);
5187 }
5188 else {
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005189 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005190 Context.CollectInheritedProtocols(RHS->getInterface(),
5191 RHSInheritedProtocols);
Fariborz Jahanian432a8892010-02-12 19:27:33 +00005192 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5193 RHSInheritedProtocols.begin(),
5194 E = RHSInheritedProtocols.end(); I != E; ++I)
5195 if (InheritedProtocolSet.count((*I)))
5196 IntersectionOfProtocols.push_back((*I));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005197 }
5198}
5199
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005200/// areCommonBaseCompatible - Returns common base class of the two classes if
5201/// one found. Note that this is O'2 algorithm. But it will be called as the
5202/// last type comparison in a ?-exp of ObjC pointer types before a
5203/// warning is issued. So, its invokation is extremely rare.
5204QualType ASTContext::areCommonBaseCompatible(
John McCallc12c5bb2010-05-15 11:32:37 +00005205 const ObjCObjectPointerType *Lptr,
5206 const ObjCObjectPointerType *Rptr) {
5207 const ObjCObjectType *LHS = Lptr->getObjectType();
5208 const ObjCObjectType *RHS = Rptr->getObjectType();
5209 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5210 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005211 if (!LDecl || !RDecl || (LDecl == RDecl))
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005212 return QualType();
5213
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005214 do {
John McCallc12c5bb2010-05-15 11:32:37 +00005215 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005216 if (canAssignObjCInterfaces(LHS, RHS)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005217 SmallVector<ObjCProtocolDecl *, 8> Protocols;
John McCallc12c5bb2010-05-15 11:32:37 +00005218 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5219
5220 QualType Result = QualType(LHS, 0);
5221 if (!Protocols.empty())
5222 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5223 Result = getObjCObjectPointerType(Result);
5224 return Result;
Fariborz Jahaniane23fa2d2009-10-30 01:13:23 +00005225 }
Fariborz Jahanian7c2bdcb2011-04-18 21:16:59 +00005226 } while ((LDecl = LDecl->getSuperClass()));
Fariborz Jahaniandb07b3f2009-10-27 23:02:38 +00005227
5228 return QualType();
5229}
5230
John McCallc12c5bb2010-05-15 11:32:37 +00005231bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5232 const ObjCObjectType *RHS) {
5233 assert(LHS->getInterface() && "LHS is not an interface type");
5234 assert(RHS->getInterface() && "RHS is not an interface type");
5235
Chris Lattner6ac46a42008-04-07 06:51:04 +00005236 // Verify that the base decls are compatible: the RHS must be a subclass of
5237 // the LHS.
John McCallc12c5bb2010-05-15 11:32:37 +00005238 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
Chris Lattner6ac46a42008-04-07 06:51:04 +00005239 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005240
Chris Lattner6ac46a42008-04-07 06:51:04 +00005241 // RHS must have a superset of the protocols in the LHS. If the LHS is not
5242 // protocol qualified at all, then we are good.
Steve Naroffc15cb2a2009-07-18 15:33:26 +00005243 if (LHS->getNumProtocols() == 0)
Chris Lattner6ac46a42008-04-07 06:51:04 +00005244 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005245
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005246 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't,
5247 // more detailed analysis is required.
5248 if (RHS->getNumProtocols() == 0) {
5249 // OK, if LHS is a superclass of RHS *and*
5250 // this superclass is assignment compatible with LHS.
5251 // false otherwise.
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005252 bool IsSuperClass =
5253 LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5254 if (IsSuperClass) {
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005255 // OK if conversion of LHS to SuperClass results in narrowing of types
5256 // ; i.e., SuperClass may implement at least one of the protocols
5257 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5258 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5259 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
Fariborz Jahanian627788c2011-04-12 16:34:14 +00005260 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
Fariborz Jahanianb7bc34a2011-04-08 18:25:29 +00005261 // If super class has no protocols, it is not a match.
5262 if (SuperClassInheritedProtocols.empty())
5263 return false;
5264
5265 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5266 LHSPE = LHS->qual_end();
5267 LHSPI != LHSPE; LHSPI++) {
5268 bool SuperImplementsProtocol = false;
5269 ObjCProtocolDecl *LHSProto = (*LHSPI);
5270
5271 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5272 SuperClassInheritedProtocols.begin(),
5273 E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5274 ObjCProtocolDecl *SuperClassProto = (*I);
5275 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5276 SuperImplementsProtocol = true;
5277 break;
5278 }
5279 }
5280 if (!SuperImplementsProtocol)
5281 return false;
5282 }
5283 return true;
5284 }
5285 return false;
5286 }
Mike Stump1eb44332009-09-09 15:08:12 +00005287
John McCallc12c5bb2010-05-15 11:32:37 +00005288 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5289 LHSPE = LHS->qual_end();
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005290 LHSPI != LHSPE; LHSPI++) {
5291 bool RHSImplementsProtocol = false;
5292
5293 // If the RHS doesn't implement the protocol on the left, the types
5294 // are incompatible.
John McCallc12c5bb2010-05-15 11:32:37 +00005295 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5296 RHSPE = RHS->qual_end();
Steve Naroff8f167562009-07-16 16:21:02 +00005297 RHSPI != RHSPE; RHSPI++) {
5298 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005299 RHSImplementsProtocol = true;
Steve Naroff8f167562009-07-16 16:21:02 +00005300 break;
5301 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005302 }
5303 // FIXME: For better diagnostics, consider passing back the protocol name.
5304 if (!RHSImplementsProtocol)
5305 return false;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005306 }
Steve Naroff91b0b0c2009-03-01 16:12:44 +00005307 // The RHS implements all protocols listed on the LHS.
5308 return true;
Chris Lattner6ac46a42008-04-07 06:51:04 +00005309}
5310
Steve Naroff389bf462009-02-12 17:52:19 +00005311bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5312 // get the "pointed to" types
John McCall183700f2009-09-21 23:43:11 +00005313 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5314 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00005315
Steve Naroff14108da2009-07-10 23:34:53 +00005316 if (!LHSOPT || !RHSOPT)
Steve Naroff389bf462009-02-12 17:52:19 +00005317 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00005318
5319 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5320 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroff389bf462009-02-12 17:52:19 +00005321}
5322
Douglas Gregor569c3162010-08-07 11:51:51 +00005323bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5324 return canAssignObjCInterfaces(
5325 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5326 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5327}
5328
Mike Stump1eb44332009-09-09 15:08:12 +00005329/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroffec0550f2007-10-15 20:41:53 +00005330/// both shall have the identically qualified version of a compatible type.
Mike Stump1eb44332009-09-09 15:08:12 +00005331/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroffec0550f2007-10-15 20:41:53 +00005332/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor447234d2010-07-29 15:18:02 +00005333bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5334 bool CompareUnqualified) {
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005335 if (getLangOptions().CPlusPlus)
5336 return hasSameType(LHS, RHS);
5337
Douglas Gregor447234d2010-07-29 15:18:02 +00005338 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman3d815e72008-08-22 00:56:42 +00005339}
5340
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005341bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanian82378392011-07-12 23:20:13 +00005342 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc286f382011-07-12 22:05:16 +00005343}
5344
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005345bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5346 return !mergeTypes(LHS, RHS, true).isNull();
5347}
5348
Peter Collingbourne48466752010-10-24 18:30:18 +00005349/// mergeTransparentUnionType - if T is a transparent union type and a member
5350/// of T is compatible with SubType, return the merged type, else return
5351/// QualType()
5352QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5353 bool OfBlockPointer,
5354 bool Unqualified) {
5355 if (const RecordType *UT = T->getAsUnionType()) {
5356 RecordDecl *UD = UT->getDecl();
5357 if (UD->hasAttr<TransparentUnionAttr>()) {
5358 for (RecordDecl::field_iterator it = UD->field_begin(),
5359 itend = UD->field_end(); it != itend; ++it) {
Peter Collingbournef91d7572010-12-02 21:00:06 +00005360 QualType ET = it->getType().getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005361 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5362 if (!MT.isNull())
5363 return MT;
5364 }
5365 }
5366 }
5367
5368 return QualType();
5369}
5370
5371/// mergeFunctionArgumentTypes - merge two types which appear as function
5372/// argument types
5373QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5374 bool OfBlockPointer,
5375 bool Unqualified) {
5376 // GNU extension: two types are compatible if they appear as a function
5377 // argument, one of the types is a transparent union type and the other
5378 // type is compatible with a union member
5379 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5380 Unqualified);
5381 if (!lmerge.isNull())
5382 return lmerge;
5383
5384 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5385 Unqualified);
5386 if (!rmerge.isNull())
5387 return rmerge;
5388
5389 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5390}
5391
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005392QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor447234d2010-07-29 15:18:02 +00005393 bool OfBlockPointer,
5394 bool Unqualified) {
John McCall183700f2009-09-21 23:43:11 +00005395 const FunctionType *lbase = lhs->getAs<FunctionType>();
5396 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00005397 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5398 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman3d815e72008-08-22 00:56:42 +00005399 bool allLTypes = true;
5400 bool allRTypes = true;
5401
5402 // Check return type
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005403 QualType retType;
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005404 if (OfBlockPointer) {
5405 QualType RHS = rbase->getResultType();
5406 QualType LHS = lbase->getResultType();
5407 bool UnqualifiedResult = Unqualified;
5408 if (!UnqualifiedResult)
5409 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005410 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahaniand263fd12011-02-11 18:46:17 +00005411 }
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005412 else
John McCall8cc246c2010-12-15 01:06:38 +00005413 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5414 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005415 if (retType.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005416
5417 if (Unqualified)
5418 retType = retType.getUnqualifiedType();
5419
5420 CanQualType LRetType = getCanonicalType(lbase->getResultType());
5421 CanQualType RRetType = getCanonicalType(rbase->getResultType());
5422 if (Unqualified) {
5423 LRetType = LRetType.getUnqualifiedType();
5424 RRetType = RRetType.getUnqualifiedType();
5425 }
5426
5427 if (getCanonicalType(retType) != LRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005428 allLTypes = false;
Douglas Gregor447234d2010-07-29 15:18:02 +00005429 if (getCanonicalType(retType) != RRetType)
Chris Lattner61710852008-10-05 17:34:18 +00005430 allRTypes = false;
John McCall8cc246c2010-12-15 01:06:38 +00005431
Daniel Dunbar6a15c852010-04-28 16:20:58 +00005432 // FIXME: double check this
5433 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5434 // rbase->getRegParmAttr() != 0 &&
5435 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindola264ba482010-03-30 20:24:48 +00005436 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5437 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8cc246c2010-12-15 01:06:38 +00005438
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005439 // Compatible functions must have compatible calling conventions
John McCall8cc246c2010-12-15 01:06:38 +00005440 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
Douglas Gregorab8bbf42010-01-18 17:14:39 +00005441 return QualType();
Mike Stump1eb44332009-09-09 15:08:12 +00005442
John McCall8cc246c2010-12-15 01:06:38 +00005443 // Regparm is part of the calling convention.
Eli Friedmana49218e2011-04-09 08:18:08 +00005444 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5445 return QualType();
John McCall8cc246c2010-12-15 01:06:38 +00005446 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5447 return QualType();
5448
John McCallf85e1932011-06-15 23:02:42 +00005449 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5450 return QualType();
5451
John McCall8cc246c2010-12-15 01:06:38 +00005452 // It's noreturn if either type is.
5453 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5454 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5455 if (NoReturn != lbaseInfo.getNoReturn())
5456 allLTypes = false;
5457 if (NoReturn != rbaseInfo.getNoReturn())
5458 allRTypes = false;
5459
John McCallf85e1932011-06-15 23:02:42 +00005460 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalle23cf432010-12-14 08:05:40 +00005461
Eli Friedman3d815e72008-08-22 00:56:42 +00005462 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl465226e2009-05-27 22:11:52 +00005463 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5464 "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005465 unsigned lproto_nargs = lproto->getNumArgs();
5466 unsigned rproto_nargs = rproto->getNumArgs();
5467
5468 // Compatible functions must have the same number of arguments
5469 if (lproto_nargs != rproto_nargs)
5470 return QualType();
5471
5472 // Variadic and non-variadic functions aren't compatible
5473 if (lproto->isVariadic() != rproto->isVariadic())
5474 return QualType();
5475
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00005476 if (lproto->getTypeQuals() != rproto->getTypeQuals())
5477 return QualType();
5478
Eli Friedman3d815e72008-08-22 00:56:42 +00005479 // Check argument compatibility
Chris Lattner5f9e2722011-07-23 10:55:15 +00005480 SmallVector<QualType, 10> types;
Eli Friedman3d815e72008-08-22 00:56:42 +00005481 for (unsigned i = 0; i < lproto_nargs; i++) {
5482 QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5483 QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
Peter Collingbourne48466752010-10-24 18:30:18 +00005484 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5485 OfBlockPointer,
5486 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005487 if (argtype.isNull()) return QualType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005488
5489 if (Unqualified)
5490 argtype = argtype.getUnqualifiedType();
5491
Eli Friedman3d815e72008-08-22 00:56:42 +00005492 types.push_back(argtype);
Douglas Gregor447234d2010-07-29 15:18:02 +00005493 if (Unqualified) {
5494 largtype = largtype.getUnqualifiedType();
5495 rargtype = rargtype.getUnqualifiedType();
5496 }
5497
Chris Lattner61710852008-10-05 17:34:18 +00005498 if (getCanonicalType(argtype) != getCanonicalType(largtype))
5499 allLTypes = false;
5500 if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5501 allRTypes = false;
Eli Friedman3d815e72008-08-22 00:56:42 +00005502 }
5503 if (allLTypes) return lhs;
5504 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005505
5506 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5507 EPI.ExtInfo = einfo;
5508 return getFunctionType(retType, types.begin(), types.size(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005509 }
5510
5511 if (lproto) allRTypes = false;
5512 if (rproto) allLTypes = false;
5513
Douglas Gregor72564e72009-02-26 23:50:07 +00005514 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman3d815e72008-08-22 00:56:42 +00005515 if (proto) {
Sebastian Redl465226e2009-05-27 22:11:52 +00005516 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman3d815e72008-08-22 00:56:42 +00005517 if (proto->isVariadic()) return QualType();
5518 // Check that the types are compatible with the types that
5519 // would result from default argument promotions (C99 6.7.5.3p15).
5520 // The only types actually affected are promotable integer
5521 // types and floats, which would be passed as a different
5522 // type depending on whether the prototype is visible.
5523 unsigned proto_nargs = proto->getNumArgs();
5524 for (unsigned i = 0; i < proto_nargs; ++i) {
5525 QualType argTy = proto->getArgType(i);
Douglas Gregorb0f8eac2010-02-03 19:27:29 +00005526
5527 // Look at the promotion type of enum types, since that is the type used
5528 // to pass enum values.
5529 if (const EnumType *Enum = argTy->getAs<EnumType>())
5530 argTy = Enum->getDecl()->getPromotionType();
5531
Eli Friedman3d815e72008-08-22 00:56:42 +00005532 if (argTy->isPromotableIntegerType() ||
5533 getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5534 return QualType();
5535 }
5536
5537 if (allLTypes) return lhs;
5538 if (allRTypes) return rhs;
John McCalle23cf432010-12-14 08:05:40 +00005539
5540 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5541 EPI.ExtInfo = einfo;
Eli Friedman3d815e72008-08-22 00:56:42 +00005542 return getFunctionType(retType, proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005543 proto->getNumArgs(), EPI);
Eli Friedman3d815e72008-08-22 00:56:42 +00005544 }
5545
5546 if (allLTypes) return lhs;
5547 if (allRTypes) return rhs;
John McCall8cc246c2010-12-15 01:06:38 +00005548 return getFunctionNoProtoType(retType, einfo);
Eli Friedman3d815e72008-08-22 00:56:42 +00005549}
5550
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005551QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor447234d2010-07-29 15:18:02 +00005552 bool OfBlockPointer,
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005553 bool Unqualified, bool BlockReturnType) {
Bill Wendling43d69752007-12-03 07:33:35 +00005554 // C++ [expr]: If an expression initially has the type "reference to T", the
5555 // type is adjusted to "T" prior to any further analysis, the expression
5556 // designates the object or function denoted by the reference, and the
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005557 // expression is an lvalue unless the reference is an rvalue reference and
5558 // the expression is a function call (possibly inside parentheses).
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005559 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5560 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor447234d2010-07-29 15:18:02 +00005561
5562 if (Unqualified) {
5563 LHS = LHS.getUnqualifiedType();
5564 RHS = RHS.getUnqualifiedType();
5565 }
Douglas Gregor0e709ab2010-02-03 21:02:30 +00005566
Eli Friedman3d815e72008-08-22 00:56:42 +00005567 QualType LHSCan = getCanonicalType(LHS),
5568 RHSCan = getCanonicalType(RHS);
5569
5570 // If two types are identical, they are compatible.
5571 if (LHSCan == RHSCan)
5572 return LHS;
5573
John McCall0953e762009-09-24 19:53:00 +00005574 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005575 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5576 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall0953e762009-09-24 19:53:00 +00005577 if (LQuals != RQuals) {
5578 // If any of these qualifiers are different, we have a type
5579 // mismatch.
5580 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCallf85e1932011-06-15 23:02:42 +00005581 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5582 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall0953e762009-09-24 19:53:00 +00005583 return QualType();
5584
5585 // Exactly one GC qualifier difference is allowed: __strong is
5586 // okay if the other type has no GC qualifier but is an Objective
5587 // C object pointer (i.e. implicitly strong by default). We fix
5588 // this by pretending that the unqualified type was actually
5589 // qualified __strong.
5590 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5591 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5592 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5593
5594 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5595 return QualType();
5596
5597 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5598 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5599 }
5600 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5601 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5602 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005603 return QualType();
John McCall0953e762009-09-24 19:53:00 +00005604 }
5605
5606 // Okay, qualifiers are equal.
Eli Friedman3d815e72008-08-22 00:56:42 +00005607
Eli Friedman852d63b2009-06-01 01:22:52 +00005608 Type::TypeClass LHSClass = LHSCan->getTypeClass();
5609 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman3d815e72008-08-22 00:56:42 +00005610
Chris Lattner1adb8832008-01-14 05:45:46 +00005611 // We want to consider the two function types to be the same for these
5612 // comparisons, just force one to the other.
5613 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5614 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman4c721d32008-02-12 08:23:06 +00005615
5616 // Same as above for arrays
Chris Lattnera36a61f2008-04-07 05:43:21 +00005617 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5618 LHSClass = Type::ConstantArray;
5619 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5620 RHSClass = Type::ConstantArray;
Mike Stump1eb44332009-09-09 15:08:12 +00005621
John McCallc12c5bb2010-05-15 11:32:37 +00005622 // ObjCInterfaces are just specialized ObjCObjects.
5623 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5624 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5625
Nate Begeman213541a2008-04-18 23:10:10 +00005626 // Canonicalize ExtVector -> Vector.
5627 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5628 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump1eb44332009-09-09 15:08:12 +00005629
Chris Lattnera36a61f2008-04-07 05:43:21 +00005630 // If the canonical type classes don't match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005631 if (LHSClass != RHSClass) {
Chris Lattner1adb8832008-01-14 05:45:46 +00005632 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
Mike Stump1eb44332009-09-09 15:08:12 +00005633 // a signed integer type, or an unsigned integer type.
John McCall842aef82009-12-09 09:09:27 +00005634 // Compatibility is based on the underlying type, not the promotion
5635 // type.
John McCall183700f2009-09-21 23:43:11 +00005636 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005637 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
5638 return RHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005639 }
John McCall183700f2009-09-21 23:43:11 +00005640 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
Eli Friedman3d815e72008-08-22 00:56:42 +00005641 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
5642 return LHS;
Eli Friedmanbab96962008-02-12 08:46:17 +00005643 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005644
Eli Friedman3d815e72008-08-22 00:56:42 +00005645 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005646 }
Eli Friedman3d815e72008-08-22 00:56:42 +00005647
Steve Naroff4a746782008-01-09 22:43:08 +00005648 // The canonical type classes match.
Chris Lattner1adb8832008-01-14 05:45:46 +00005649 switch (LHSClass) {
Douglas Gregor72564e72009-02-26 23:50:07 +00005650#define TYPE(Class, Base)
5651#define ABSTRACT_TYPE(Class, Base)
John McCallad5e7382010-03-01 23:49:17 +00005652#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregor72564e72009-02-26 23:50:07 +00005653#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5654#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5655#include "clang/AST/TypeNodes.def"
5656 assert(false && "Non-canonical and dependent types shouldn't get here");
5657 return QualType();
5658
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005659 case Type::LValueReference:
5660 case Type::RValueReference:
Douglas Gregor72564e72009-02-26 23:50:07 +00005661 case Type::MemberPointer:
5662 assert(false && "C++ should never be in mergeTypes");
5663 return QualType();
5664
John McCallc12c5bb2010-05-15 11:32:37 +00005665 case Type::ObjCInterface:
Douglas Gregor72564e72009-02-26 23:50:07 +00005666 case Type::IncompleteArray:
5667 case Type::VariableArray:
5668 case Type::FunctionProto:
5669 case Type::ExtVector:
Douglas Gregor72564e72009-02-26 23:50:07 +00005670 assert(false && "Types are eliminated above");
5671 return QualType();
5672
Chris Lattner1adb8832008-01-14 05:45:46 +00005673 case Type::Pointer:
Eli Friedman3d815e72008-08-22 00:56:42 +00005674 {
5675 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005676 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5677 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005678 if (Unqualified) {
5679 LHSPointee = LHSPointee.getUnqualifiedType();
5680 RHSPointee = RHSPointee.getUnqualifiedType();
5681 }
5682 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5683 Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005684 if (ResultType.isNull()) return QualType();
Eli Friedman07d25872009-06-02 05:28:56 +00005685 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005686 return LHS;
Eli Friedman07d25872009-06-02 05:28:56 +00005687 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner61710852008-10-05 17:34:18 +00005688 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005689 return getPointerType(ResultType);
5690 }
Steve Naroffc0febd52008-12-10 17:49:55 +00005691 case Type::BlockPointer:
5692 {
5693 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenek6217b802009-07-29 21:53:49 +00005694 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5695 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005696 if (Unqualified) {
5697 LHSPointee = LHSPointee.getUnqualifiedType();
5698 RHSPointee = RHSPointee.getUnqualifiedType();
5699 }
5700 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5701 Unqualified);
Steve Naroffc0febd52008-12-10 17:49:55 +00005702 if (ResultType.isNull()) return QualType();
5703 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5704 return LHS;
5705 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5706 return RHS;
5707 return getBlockPointerType(ResultType);
5708 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005709 case Type::ConstantArray:
Eli Friedman3d815e72008-08-22 00:56:42 +00005710 {
5711 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
5712 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
5713 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
5714 return QualType();
5715
5716 QualType LHSElem = getAsArrayType(LHS)->getElementType();
5717 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor447234d2010-07-29 15:18:02 +00005718 if (Unqualified) {
5719 LHSElem = LHSElem.getUnqualifiedType();
5720 RHSElem = RHSElem.getUnqualifiedType();
5721 }
5722
5723 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman3d815e72008-08-22 00:56:42 +00005724 if (ResultType.isNull()) return QualType();
Chris Lattner61710852008-10-05 17:34:18 +00005725 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5726 return LHS;
5727 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5728 return RHS;
Eli Friedman3bc0f452008-08-22 01:48:21 +00005729 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
5730 ArrayType::ArraySizeModifier(), 0);
5731 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
5732 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005733 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
5734 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner61710852008-10-05 17:34:18 +00005735 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
5736 return LHS;
5737 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
5738 return RHS;
Eli Friedman3d815e72008-08-22 00:56:42 +00005739 if (LVAT) {
5740 // FIXME: This isn't correct! But tricky to implement because
5741 // the array's size has to be the size of LHS, but the type
5742 // has to be different.
5743 return LHS;
5744 }
5745 if (RVAT) {
5746 // FIXME: This isn't correct! But tricky to implement because
5747 // the array's size has to be the size of RHS, but the type
5748 // has to be different.
5749 return RHS;
5750 }
Eli Friedman3bc0f452008-08-22 01:48:21 +00005751 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
5752 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +00005753 return getIncompleteArrayType(ResultType,
5754 ArrayType::ArraySizeModifier(), 0);
Eli Friedman3d815e72008-08-22 00:56:42 +00005755 }
Chris Lattner1adb8832008-01-14 05:45:46 +00005756 case Type::FunctionNoProto:
Douglas Gregor447234d2010-07-29 15:18:02 +00005757 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregor72564e72009-02-26 23:50:07 +00005758 case Type::Record:
Douglas Gregor72564e72009-02-26 23:50:07 +00005759 case Type::Enum:
Eli Friedman3d815e72008-08-22 00:56:42 +00005760 return QualType();
Chris Lattner1adb8832008-01-14 05:45:46 +00005761 case Type::Builtin:
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005762 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman3d815e72008-08-22 00:56:42 +00005763 return QualType();
Daniel Dunbar64cfdb72009-01-28 21:22:12 +00005764 case Type::Complex:
5765 // Distinct complex types are incompatible.
5766 return QualType();
Chris Lattner3cc4c0c2008-04-07 05:55:38 +00005767 case Type::Vector:
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005768 // FIXME: The merged type should be an ExtVector!
John McCall1c471f32010-03-12 23:14:13 +00005769 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
5770 RHSCan->getAs<VectorType>()))
Eli Friedman3d815e72008-08-22 00:56:42 +00005771 return LHS;
Chris Lattner61710852008-10-05 17:34:18 +00005772 return QualType();
John McCallc12c5bb2010-05-15 11:32:37 +00005773 case Type::ObjCObject: {
5774 // Check if the types are assignment compatible.
Eli Friedman5a61f0e2009-02-27 23:04:43 +00005775 // FIXME: This should be type compatibility, e.g. whether
5776 // "LHS x; RHS x;" at global scope is legal.
John McCallc12c5bb2010-05-15 11:32:37 +00005777 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
5778 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
5779 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff5fd659d2009-02-21 16:18:07 +00005780 return LHS;
5781
Eli Friedman3d815e72008-08-22 00:56:42 +00005782 return QualType();
Cedric Venet61490e92009-02-21 17:14:49 +00005783 }
Steve Naroff14108da2009-07-10 23:34:53 +00005784 case Type::ObjCObjectPointer: {
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005785 if (OfBlockPointer) {
5786 if (canAssignObjCInterfacesInBlockPointer(
5787 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahaniana4fdbfa2011-03-14 16:07:00 +00005788 RHS->getAs<ObjCObjectPointerType>(),
5789 BlockReturnType))
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005790 return LHS;
5791 return QualType();
5792 }
John McCall183700f2009-09-21 23:43:11 +00005793 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
5794 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff14108da2009-07-10 23:34:53 +00005795 return LHS;
5796
Steve Naroffbc76dd02008-12-10 22:14:21 +00005797 return QualType();
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00005798 }
Steve Naroffec0550f2007-10-15 20:41:53 +00005799 }
Douglas Gregor72564e72009-02-26 23:50:07 +00005800
5801 return QualType();
Steve Naroffec0550f2007-10-15 20:41:53 +00005802}
Ted Kremenek7192f8e2007-10-31 17:10:13 +00005803
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005804/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
5805/// 'RHS' attributes and returns the merged version; including for function
5806/// return types.
5807QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
5808 QualType LHSCan = getCanonicalType(LHS),
5809 RHSCan = getCanonicalType(RHS);
5810 // If two types are identical, they are compatible.
5811 if (LHSCan == RHSCan)
5812 return LHS;
5813 if (RHSCan->isFunctionType()) {
5814 if (!LHSCan->isFunctionType())
5815 return QualType();
5816 QualType OldReturnType =
5817 cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
5818 QualType NewReturnType =
5819 cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
5820 QualType ResReturnType =
5821 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
5822 if (ResReturnType.isNull())
5823 return QualType();
5824 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
5825 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
5826 // In either case, use OldReturnType to build the new function type.
5827 const FunctionType *F = LHS->getAs<FunctionType>();
5828 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalle23cf432010-12-14 08:05:40 +00005829 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
5830 EPI.ExtInfo = getFunctionExtInfo(LHS);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005831 QualType ResultType
5832 = getFunctionType(OldReturnType, FPT->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005833 FPT->getNumArgs(), EPI);
Fariborz Jahanian2390a722010-05-19 21:37:30 +00005834 return ResultType;
5835 }
5836 }
5837 return QualType();
5838 }
5839
5840 // If the qualifiers are different, the types can still be merged.
5841 Qualifiers LQuals = LHSCan.getLocalQualifiers();
5842 Qualifiers RQuals = RHSCan.getLocalQualifiers();
5843 if (LQuals != RQuals) {
5844 // If any of these qualifiers are different, we have a type mismatch.
5845 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5846 LQuals.getAddressSpace() != RQuals.getAddressSpace())
5847 return QualType();
5848
5849 // Exactly one GC qualifier difference is allowed: __strong is
5850 // okay if the other type has no GC qualifier but is an Objective
5851 // C object pointer (i.e. implicitly strong by default). We fix
5852 // this by pretending that the unqualified type was actually
5853 // qualified __strong.
5854 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5855 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5856 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5857
5858 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5859 return QualType();
5860
5861 if (GC_L == Qualifiers::Strong)
5862 return LHS;
5863 if (GC_R == Qualifiers::Strong)
5864 return RHS;
5865 return QualType();
5866 }
5867
5868 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
5869 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5870 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
5871 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
5872 if (ResQT == LHSBaseQT)
5873 return LHS;
5874 if (ResQT == RHSBaseQT)
5875 return RHS;
5876 }
5877 return QualType();
5878}
5879
Chris Lattner5426bf62008-04-07 07:01:58 +00005880//===----------------------------------------------------------------------===//
Eli Friedmanad74a752008-06-28 06:23:08 +00005881// Integer Predicates
5882//===----------------------------------------------------------------------===//
Chris Lattner88054de2009-01-16 07:15:35 +00005883
Jay Foad4ba2a172011-01-12 09:06:06 +00005884unsigned ASTContext::getIntWidth(QualType T) const {
John McCallf4c73712011-01-19 06:33:43 +00005885 if (const EnumType *ET = dyn_cast<EnumType>(T))
Eli Friedman29a7f332009-12-10 22:29:29 +00005886 T = ET->getDecl()->getIntegerType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005887 if (T->isBooleanType())
5888 return 1;
Eli Friedmanf98aba32009-02-13 02:31:07 +00005889 // For builtin types, just use the standard type sizing method
Eli Friedmanad74a752008-06-28 06:23:08 +00005890 return (unsigned)getTypeSize(T);
5891}
5892
5893QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
Douglas Gregorf6094622010-07-23 15:58:24 +00005894 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattner6a2b9262009-10-17 20:33:28 +00005895
5896 // Turn <4 x signed int> -> <4 x unsigned int>
5897 if (const VectorType *VTy = T->getAs<VectorType>())
5898 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsone86d78c2010-11-10 21:56:12 +00005899 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattner6a2b9262009-10-17 20:33:28 +00005900
5901 // For enums, we return the unsigned version of the base type.
5902 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedmanad74a752008-06-28 06:23:08 +00005903 T = ETy->getDecl()->getIntegerType();
Chris Lattner6a2b9262009-10-17 20:33:28 +00005904
5905 const BuiltinType *BTy = T->getAs<BuiltinType>();
5906 assert(BTy && "Unexpected signed integer type");
Eli Friedmanad74a752008-06-28 06:23:08 +00005907 switch (BTy->getKind()) {
5908 case BuiltinType::Char_S:
5909 case BuiltinType::SChar:
5910 return UnsignedCharTy;
5911 case BuiltinType::Short:
5912 return UnsignedShortTy;
5913 case BuiltinType::Int:
5914 return UnsignedIntTy;
5915 case BuiltinType::Long:
5916 return UnsignedLongTy;
5917 case BuiltinType::LongLong:
5918 return UnsignedLongLongTy;
Chris Lattner2df9ced2009-04-30 02:43:43 +00005919 case BuiltinType::Int128:
5920 return UnsignedInt128Ty;
Eli Friedmanad74a752008-06-28 06:23:08 +00005921 default:
5922 assert(0 && "Unexpected signed integer type");
5923 return QualType();
5924 }
5925}
5926
Argyrios Kyrtzidis7b903402010-10-24 17:26:36 +00005927ASTMutationListener::~ASTMutationListener() { }
5928
Chris Lattner86df27b2009-06-14 00:45:47 +00005929
5930//===----------------------------------------------------------------------===//
5931// Builtin Type Computation
5932//===----------------------------------------------------------------------===//
5933
5934/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattner33daae62010-10-01 22:42:38 +00005935/// pointer over the consumed characters. This returns the resultant type. If
5936/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
5937/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
5938/// a vector of "i*".
Chris Lattner14e0e742010-10-01 22:53:11 +00005939///
5940/// RequiresICE is filled in on return to indicate whether the value is required
5941/// to be an Integer Constant Expression.
Jay Foad4ba2a172011-01-12 09:06:06 +00005942static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattner86df27b2009-06-14 00:45:47 +00005943 ASTContext::GetBuiltinTypeError &Error,
Chris Lattner14e0e742010-10-01 22:53:11 +00005944 bool &RequiresICE,
Chris Lattner33daae62010-10-01 22:42:38 +00005945 bool AllowTypeModifiers) {
Chris Lattner86df27b2009-06-14 00:45:47 +00005946 // Modifiers.
5947 int HowLong = 0;
5948 bool Signed = false, Unsigned = false;
Chris Lattner14e0e742010-10-01 22:53:11 +00005949 RequiresICE = false;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005950
Chris Lattner33daae62010-10-01 22:42:38 +00005951 // Read the prefixed modifiers first.
Chris Lattner86df27b2009-06-14 00:45:47 +00005952 bool Done = false;
5953 while (!Done) {
5954 switch (*Str++) {
Mike Stump1eb44332009-09-09 15:08:12 +00005955 default: Done = true; --Str; break;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005956 case 'I':
Chris Lattner14e0e742010-10-01 22:53:11 +00005957 RequiresICE = true;
Chris Lattner393bd8e2010-10-01 07:13:18 +00005958 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00005959 case 'S':
5960 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
5961 assert(!Signed && "Can't use 'S' modifier multiple times!");
5962 Signed = true;
5963 break;
5964 case 'U':
5965 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
5966 assert(!Unsigned && "Can't use 'S' modifier multiple times!");
5967 Unsigned = true;
5968 break;
5969 case 'L':
5970 assert(HowLong <= 2 && "Can't have LLLL modifier");
5971 ++HowLong;
5972 break;
5973 }
5974 }
5975
5976 QualType Type;
Mike Stump1eb44332009-09-09 15:08:12 +00005977
Chris Lattner86df27b2009-06-14 00:45:47 +00005978 // Read the base type.
5979 switch (*Str++) {
5980 default: assert(0 && "Unknown builtin type letter!");
5981 case 'v':
5982 assert(HowLong == 0 && !Signed && !Unsigned &&
5983 "Bad modifiers used with 'v'!");
5984 Type = Context.VoidTy;
5985 break;
5986 case 'f':
5987 assert(HowLong == 0 && !Signed && !Unsigned &&
5988 "Bad modifiers used with 'f'!");
5989 Type = Context.FloatTy;
5990 break;
5991 case 'd':
5992 assert(HowLong < 2 && !Signed && !Unsigned &&
5993 "Bad modifiers used with 'd'!");
5994 if (HowLong)
5995 Type = Context.LongDoubleTy;
5996 else
5997 Type = Context.DoubleTy;
5998 break;
5999 case 's':
6000 assert(HowLong == 0 && "Bad modifiers used with 's'!");
6001 if (Unsigned)
6002 Type = Context.UnsignedShortTy;
6003 else
6004 Type = Context.ShortTy;
6005 break;
6006 case 'i':
6007 if (HowLong == 3)
6008 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6009 else if (HowLong == 2)
6010 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6011 else if (HowLong == 1)
6012 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6013 else
6014 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6015 break;
6016 case 'c':
6017 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6018 if (Signed)
6019 Type = Context.SignedCharTy;
6020 else if (Unsigned)
6021 Type = Context.UnsignedCharTy;
6022 else
6023 Type = Context.CharTy;
6024 break;
6025 case 'b': // boolean
6026 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6027 Type = Context.BoolTy;
6028 break;
6029 case 'z': // size_t.
6030 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6031 Type = Context.getSizeType();
6032 break;
6033 case 'F':
6034 Type = Context.getCFConstantStringType();
6035 break;
Fariborz Jahanianba8bda02010-11-09 21:38:20 +00006036 case 'G':
6037 Type = Context.getObjCIdType();
6038 break;
6039 case 'H':
6040 Type = Context.getObjCSelType();
6041 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006042 case 'a':
6043 Type = Context.getBuiltinVaListType();
6044 assert(!Type.isNull() && "builtin va list type not initialized!");
6045 break;
6046 case 'A':
6047 // This is a "reference" to a va_list; however, what exactly
6048 // this means depends on how va_list is defined. There are two
6049 // different kinds of va_list: ones passed by value, and ones
6050 // passed by reference. An example of a by-value va_list is
6051 // x86, where va_list is a char*. An example of by-ref va_list
6052 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6053 // we want this argument to be a char*&; for x86-64, we want
6054 // it to be a __va_list_tag*.
6055 Type = Context.getBuiltinVaListType();
6056 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattner14e0e742010-10-01 22:53:11 +00006057 if (Type->isArrayType())
Chris Lattner86df27b2009-06-14 00:45:47 +00006058 Type = Context.getArrayDecayedType(Type);
Chris Lattner14e0e742010-10-01 22:53:11 +00006059 else
Chris Lattner86df27b2009-06-14 00:45:47 +00006060 Type = Context.getLValueReferenceType(Type);
Chris Lattner86df27b2009-06-14 00:45:47 +00006061 break;
6062 case 'V': {
6063 char *End;
Chris Lattner86df27b2009-06-14 00:45:47 +00006064 unsigned NumElements = strtoul(Str, &End, 10);
6065 assert(End != Str && "Missing vector size");
Chris Lattner86df27b2009-06-14 00:45:47 +00006066 Str = End;
Mike Stump1eb44332009-09-09 15:08:12 +00006067
Chris Lattner14e0e742010-10-01 22:53:11 +00006068 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6069 RequiresICE, false);
6070 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattner33daae62010-10-01 22:42:38 +00006071
6072 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner788b0fd2010-06-23 06:00:24 +00006073 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00006074 VectorType::GenericVector);
Chris Lattner86df27b2009-06-14 00:45:47 +00006075 break;
6076 }
Douglas Gregord3a23b22009-09-28 21:45:01 +00006077 case 'X': {
Chris Lattner14e0e742010-10-01 22:53:11 +00006078 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6079 false);
6080 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregord3a23b22009-09-28 21:45:01 +00006081 Type = Context.getComplexType(ElementType);
6082 break;
6083 }
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006084 case 'P':
Douglas Gregorc29f77b2009-07-07 16:35:42 +00006085 Type = Context.getFILEType();
6086 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006087 Error = ASTContext::GE_Missing_stdio;
Chris Lattner86df27b2009-06-14 00:45:47 +00006088 return QualType();
6089 }
Mike Stumpfd612db2009-07-28 23:47:15 +00006090 break;
Chris Lattner9a5a7e72009-07-28 22:49:34 +00006091 case 'J':
Mike Stumpf711c412009-07-28 23:57:15 +00006092 if (Signed)
Mike Stump782fa302009-07-28 02:25:19 +00006093 Type = Context.getsigjmp_bufType();
Mike Stumpf711c412009-07-28 23:57:15 +00006094 else
6095 Type = Context.getjmp_bufType();
6096
Mike Stumpfd612db2009-07-28 23:47:15 +00006097 if (Type.isNull()) {
Mike Stumpf711c412009-07-28 23:57:15 +00006098 Error = ASTContext::GE_Missing_setjmp;
Mike Stumpfd612db2009-07-28 23:47:15 +00006099 return QualType();
6100 }
6101 break;
Mike Stump782fa302009-07-28 02:25:19 +00006102 }
Mike Stump1eb44332009-09-09 15:08:12 +00006103
Chris Lattner33daae62010-10-01 22:42:38 +00006104 // If there are modifiers and if we're allowed to parse them, go for it.
6105 Done = !AllowTypeModifiers;
Chris Lattner86df27b2009-06-14 00:45:47 +00006106 while (!Done) {
John McCall187ab372010-03-12 04:21:28 +00006107 switch (char c = *Str++) {
Chris Lattner33daae62010-10-01 22:42:38 +00006108 default: Done = true; --Str; break;
6109 case '*':
6110 case '&': {
6111 // Both pointers and references can have their pointee types
6112 // qualified with an address space.
6113 char *End;
6114 unsigned AddrSpace = strtoul(Str, &End, 10);
6115 if (End != Str && AddrSpace != 0) {
6116 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6117 Str = End;
6118 }
6119 if (c == '*')
6120 Type = Context.getPointerType(Type);
6121 else
6122 Type = Context.getLValueReferenceType(Type);
6123 break;
6124 }
6125 // FIXME: There's no way to have a built-in with an rvalue ref arg.
6126 case 'C':
6127 Type = Type.withConst();
6128 break;
6129 case 'D':
6130 Type = Context.getVolatileType(Type);
6131 break;
Chris Lattner86df27b2009-06-14 00:45:47 +00006132 }
6133 }
Chris Lattner393bd8e2010-10-01 07:13:18 +00006134
Chris Lattner14e0e742010-10-01 22:53:11 +00006135 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner393bd8e2010-10-01 07:13:18 +00006136 "Integer constant 'I' type must be an integer");
Mike Stump1eb44332009-09-09 15:08:12 +00006137
Chris Lattner86df27b2009-06-14 00:45:47 +00006138 return Type;
6139}
6140
6141/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattner33daae62010-10-01 22:42:38 +00006142QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattner14e0e742010-10-01 22:53:11 +00006143 GetBuiltinTypeError &Error,
Jay Foad4ba2a172011-01-12 09:06:06 +00006144 unsigned *IntegerConstantArgs) const {
Chris Lattner33daae62010-10-01 22:42:38 +00006145 const char *TypeStr = BuiltinInfo.GetTypeString(Id);
Mike Stump1eb44332009-09-09 15:08:12 +00006146
Chris Lattner5f9e2722011-07-23 10:55:15 +00006147 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00006148
Chris Lattner14e0e742010-10-01 22:53:11 +00006149 bool RequiresICE = false;
Chris Lattner86df27b2009-06-14 00:45:47 +00006150 Error = GE_None;
Chris Lattner14e0e742010-10-01 22:53:11 +00006151 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6152 RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006153 if (Error != GE_None)
6154 return QualType();
Chris Lattner14e0e742010-10-01 22:53:11 +00006155
6156 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6157
Chris Lattner86df27b2009-06-14 00:45:47 +00006158 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattner14e0e742010-10-01 22:53:11 +00006159 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattner86df27b2009-06-14 00:45:47 +00006160 if (Error != GE_None)
6161 return QualType();
6162
Chris Lattner14e0e742010-10-01 22:53:11 +00006163 // If this argument is required to be an IntegerConstantExpression and the
6164 // caller cares, fill in the bitmask we return.
6165 if (RequiresICE && IntegerConstantArgs)
6166 *IntegerConstantArgs |= 1 << ArgTypes.size();
6167
Chris Lattner86df27b2009-06-14 00:45:47 +00006168 // Do array -> pointer decay. The builtin should use the decayed type.
6169 if (Ty->isArrayType())
6170 Ty = getArrayDecayedType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00006171
Chris Lattner86df27b2009-06-14 00:45:47 +00006172 ArgTypes.push_back(Ty);
6173 }
6174
6175 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6176 "'.' should only occur at end of builtin type list!");
6177
John McCall00ccbef2010-12-21 00:44:39 +00006178 FunctionType::ExtInfo EI;
6179 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6180
6181 bool Variadic = (TypeStr[0] == '.');
6182
6183 // We really shouldn't be making a no-proto type here, especially in C++.
6184 if (ArgTypes.empty() && Variadic)
6185 return getFunctionNoProtoType(ResType, EI);
Douglas Gregorce056bc2010-02-21 22:15:06 +00006186
John McCalle23cf432010-12-14 08:05:40 +00006187 FunctionProtoType::ExtProtoInfo EPI;
John McCall00ccbef2010-12-21 00:44:39 +00006188 EPI.ExtInfo = EI;
6189 EPI.Variadic = Variadic;
John McCalle23cf432010-12-14 08:05:40 +00006190
6191 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
Chris Lattner86df27b2009-06-14 00:45:47 +00006192}
Eli Friedmana95d7572009-08-19 07:44:53 +00006193
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006194GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6195 GVALinkage External = GVA_StrongExternal;
6196
6197 Linkage L = FD->getLinkage();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006198 switch (L) {
6199 case NoLinkage:
6200 case InternalLinkage:
6201 case UniqueExternalLinkage:
6202 return GVA_Internal;
6203
6204 case ExternalLinkage:
6205 switch (FD->getTemplateSpecializationKind()) {
6206 case TSK_Undeclared:
6207 case TSK_ExplicitSpecialization:
6208 External = GVA_StrongExternal;
6209 break;
6210
6211 case TSK_ExplicitInstantiationDefinition:
6212 return GVA_ExplicitTemplateInstantiation;
6213
6214 case TSK_ExplicitInstantiationDeclaration:
6215 case TSK_ImplicitInstantiation:
6216 External = GVA_TemplateInstantiation;
6217 break;
6218 }
6219 }
6220
6221 if (!FD->isInlined())
6222 return External;
6223
6224 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6225 // GNU or C99 inline semantics. Determine whether this symbol should be
6226 // externally visible.
6227 if (FD->isInlineDefinitionExternallyVisible())
6228 return External;
6229
6230 // C99 inline semantics, where the symbol is not externally visible.
6231 return GVA_C99Inline;
6232 }
6233
6234 // C++0x [temp.explicit]p9:
6235 // [ Note: The intent is that an inline function that is the subject of
6236 // an explicit instantiation declaration will still be implicitly
6237 // instantiated when used so that the body can be considered for
6238 // inlining, but that no out-of-line copy of the inline function would be
6239 // generated in the translation unit. -- end note ]
6240 if (FD->getTemplateSpecializationKind()
6241 == TSK_ExplicitInstantiationDeclaration)
6242 return GVA_C99Inline;
6243
6244 return GVA_CXXInline;
6245}
6246
6247GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6248 // If this is a static data member, compute the kind of template
6249 // specialization. Otherwise, this variable is not part of a
6250 // template.
6251 TemplateSpecializationKind TSK = TSK_Undeclared;
6252 if (VD->isStaticDataMember())
6253 TSK = VD->getTemplateSpecializationKind();
6254
6255 Linkage L = VD->getLinkage();
6256 if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6257 VD->getType()->getLinkage() == UniqueExternalLinkage)
6258 L = UniqueExternalLinkage;
6259
6260 switch (L) {
6261 case NoLinkage:
6262 case InternalLinkage:
6263 case UniqueExternalLinkage:
6264 return GVA_Internal;
6265
6266 case ExternalLinkage:
6267 switch (TSK) {
6268 case TSK_Undeclared:
6269 case TSK_ExplicitSpecialization:
6270 return GVA_StrongExternal;
6271
6272 case TSK_ExplicitInstantiationDeclaration:
6273 llvm_unreachable("Variable should not be instantiated");
6274 // Fall through to treat this like any other instantiation.
6275
6276 case TSK_ExplicitInstantiationDefinition:
6277 return GVA_ExplicitTemplateInstantiation;
6278
6279 case TSK_ImplicitInstantiation:
6280 return GVA_TemplateInstantiation;
6281 }
6282 }
6283
6284 return GVA_StrongExternal;
6285}
6286
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +00006287bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006288 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6289 if (!VD->isFileVarDecl())
6290 return false;
6291 } else if (!isa<FunctionDecl>(D))
6292 return false;
6293
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006294 // Weak references don't produce any output by themselves.
6295 if (D->hasAttr<WeakRefAttr>())
6296 return false;
6297
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006298 // Aliases and used decls are required.
6299 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6300 return true;
6301
6302 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6303 // Forward declarations aren't required.
Sean Hunt10620eb2011-05-06 20:44:56 +00006304 if (!FD->doesThisDeclarationHaveABody())
Nick Lewyckydce67a72011-07-18 05:26:13 +00006305 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006306
6307 // Constructors and destructors are required.
6308 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6309 return true;
6310
6311 // The key function for a class is required.
6312 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6313 const CXXRecordDecl *RD = MD->getParent();
6314 if (MD->isOutOfLine() && RD->isDynamicClass()) {
6315 const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6316 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6317 return true;
6318 }
6319 }
6320
6321 GVALinkage Linkage = GetGVALinkageForFunction(FD);
6322
6323 // static, static inline, always_inline, and extern inline functions can
6324 // always be deferred. Normal inline functions can be deferred in C99/C++.
6325 // Implicit template instantiations can also be deferred in C++.
6326 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
6327 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6328 return false;
6329 return true;
6330 }
6331
6332 const VarDecl *VD = cast<VarDecl>(D);
6333 assert(VD->isFileVarDecl() && "Expected file scoped var");
6334
Argyrios Kyrtzidisab411c82010-07-29 20:07:52 +00006335 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6336 return false;
6337
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006338 // Structs that have non-trivial constructors or destructors are required.
6339
6340 // FIXME: Handle references.
Sean Hunt023df372011-05-09 18:22:59 +00006341 // FIXME: Be more selective about which constructors we care about.
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006342 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6343 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
Sean Hunt023df372011-05-09 18:22:59 +00006344 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6345 RD->hasTrivialCopyConstructor() &&
6346 RD->hasTrivialMoveConstructor() &&
6347 RD->hasTrivialDestructor()))
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00006348 return true;
6349 }
6350 }
6351
6352 GVALinkage L = GetGVALinkageForVariable(VD);
6353 if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6354 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6355 return false;
6356 }
6357
6358 return true;
6359}
Charles Davis071cc7d2010-08-16 03:33:14 +00006360
Charles Davisee743f92010-11-09 18:04:24 +00006361CallingConv ASTContext::getDefaultMethodCallConv() {
6362 // Pass through to the C++ ABI object
6363 return ABI->getDefaultMethodCallConv();
6364}
6365
Jay Foad4ba2a172011-01-12 09:06:06 +00006366bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlssondae0cb52010-11-25 01:51:53 +00006367 // Pass through to the C++ ABI object
6368 return ABI->isNearlyEmpty(RD);
6369}
6370
Peter Collingbourne14110472011-01-13 18:57:25 +00006371MangleContext *ASTContext::createMangleContext() {
6372 switch (Target.getCXXABI()) {
6373 case CXXABI_ARM:
6374 case CXXABI_Itanium:
6375 return createItaniumMangleContext(*this, getDiagnostics());
6376 case CXXABI_Microsoft:
6377 return createMicrosoftMangleContext(*this, getDiagnostics());
6378 }
6379 assert(0 && "Unsupported ABI");
6380 return 0;
6381}
6382
Charles Davis071cc7d2010-08-16 03:33:14 +00006383CXXABI::~CXXABI() {}
Ted Kremenekba29bd22011-04-28 04:53:38 +00006384
6385size_t ASTContext::getSideTableAllocatedMemory() const {
Ted Kremenek0c8cd1a2011-07-27 18:41:12 +00006386 return ASTRecordLayouts.getMemorySize()
6387 + llvm::capacity_in_bytes(ObjCLayouts)
6388 + llvm::capacity_in_bytes(KeyFunctions)
6389 + llvm::capacity_in_bytes(ObjCImpls)
6390 + llvm::capacity_in_bytes(BlockVarCopyInits)
6391 + llvm::capacity_in_bytes(DeclAttrs)
6392 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6393 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6394 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6395 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6396 + llvm::capacity_in_bytes(OverriddenMethods)
6397 + llvm::capacity_in_bytes(Types)
6398 + llvm::capacity_in_bytes(VariableArrayTypes);
Ted Kremenekba29bd22011-04-28 04:53:38 +00006399}