blob: 9132b0a1903812a6cfdd09f46b0740c99ae9f8da [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
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//
Argyrios Kyrtzidise184bae2008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Douglas Gregor2a3009a2009-02-03 19:21:40 +000015#include "clang/AST/DeclCXX.h"
Steve Naroff0de21fd2009-02-22 19:35:57 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregor7da97d02009-05-10 22:57:19 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattner6c2b6eb2008-03-15 06:12:44 +000018#include "clang/AST/ASTContext.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/Stmt.h"
Nuno Lopes99f06ba2008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson337cba42009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregord249e1d1f2009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +000024#include "clang/AST/ASTMutationListener.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000026#include "clang/Basic/IdentifierTable.h"
Douglas Gregor15de72c2011-12-02 23:23:56 +000027#include "clang/Basic/Module.h"
Abramo Bagnara465d41b2010-05-11 21:36:43 +000028#include "clang/Basic/Specifiers.h"
Douglas Gregor4421d2b2011-03-26 12:10:19 +000029#include "clang/Basic/TargetInfo.h"
John McCallf1bbbb42009-09-04 01:14:41 +000030#include "llvm/Support/ErrorHandling.h"
Ted Kremenek27f8a282008-05-20 00:43:19 +000031
David Blaikie4278c652011-09-21 18:16:56 +000032#include <algorithm>
33
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Chris Lattnerd3b90652008-03-15 05:43:15 +000036//===----------------------------------------------------------------------===//
Douglas Gregor4afa39d2009-01-20 01:17:11 +000037// NamedDecl Implementation
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000038//===----------------------------------------------------------------------===//
39
Douglas Gregor4421d2b2011-03-26 12:10:19 +000040static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
41 // If this declaration has an explicit visibility attribute, use it.
42 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
43 switch (A->getVisibility()) {
44 case VisibilityAttr::Default:
45 return DefaultVisibility;
46 case VisibilityAttr::Hidden:
47 return HiddenVisibility;
48 case VisibilityAttr::Protected:
49 return ProtectedVisibility;
50 }
John McCall7f1b9872010-12-18 03:30:47 +000051
John McCall1fb0caa2010-10-22 21:05:15 +000052 return DefaultVisibility;
John McCall1fb0caa2010-10-22 21:05:15 +000053 }
Douglas Gregor4421d2b2011-03-26 12:10:19 +000054
55 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
56 // implies visibility(default).
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000057 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +000058 for (specific_attr_iterator<AvailabilityAttr>
59 A = D->specific_attr_begin<AvailabilityAttr>(),
60 AEnd = D->specific_attr_end<AvailabilityAttr>();
61 A != AEnd; ++A)
62 if ((*A)->getPlatform()->getName().equals("macosx"))
63 return DefaultVisibility;
64 }
65
66 return llvm::Optional<Visibility>();
John McCall1fb0caa2010-10-22 21:05:15 +000067}
68
John McCallaf146032010-10-30 11:50:40 +000069typedef NamedDecl::LinkageInfo LinkageInfo;
John McCallaf146032010-10-30 11:50:40 +000070
Benjamin Kramer752c2e92010-11-05 19:56:37 +000071namespace {
John McCall36987482010-11-02 01:45:15 +000072/// Flags controlling the computation of linkage and visibility.
73struct LVFlags {
74 bool ConsiderGlobalVisibility;
75 bool ConsiderVisibilityAttributes;
John McCall1a0918a2011-03-04 10:39:25 +000076 bool ConsiderTemplateParameterTypes;
John McCall36987482010-11-02 01:45:15 +000077
78 LVFlags() : ConsiderGlobalVisibility(true),
John McCall1a0918a2011-03-04 10:39:25 +000079 ConsiderVisibilityAttributes(true),
80 ConsiderTemplateParameterTypes(true) {
John McCall36987482010-11-02 01:45:15 +000081 }
82
Douglas Gregor381d34e2010-12-06 18:36:25 +000083 /// \brief Returns a set of flags that is only useful for computing the
84 /// linkage, not the visibility, of a declaration.
85 static LVFlags CreateOnlyDeclLinkage() {
86 LVFlags F;
87 F.ConsiderGlobalVisibility = false;
88 F.ConsiderVisibilityAttributes = false;
John McCall1a0918a2011-03-04 10:39:25 +000089 F.ConsiderTemplateParameterTypes = false;
Douglas Gregor381d34e2010-12-06 18:36:25 +000090 return F;
91 }
92
John McCall36987482010-11-02 01:45:15 +000093 /// Returns a set of flags, otherwise based on these, which ignores
94 /// off all sources of visibility except template arguments.
95 LVFlags onlyTemplateVisibility() const {
96 LVFlags F = *this;
97 F.ConsiderGlobalVisibility = false;
98 F.ConsiderVisibilityAttributes = false;
John McCall1a0918a2011-03-04 10:39:25 +000099 F.ConsiderTemplateParameterTypes = false;
John McCall36987482010-11-02 01:45:15 +0000100 return F;
101 }
Douglas Gregor89d63e52010-12-06 18:50:56 +0000102};
Benjamin Kramer752c2e92010-11-05 19:56:37 +0000103} // end anonymous namespace
John McCall36987482010-11-02 01:45:15 +0000104
Rafael Espindola093ecc92012-01-14 00:30:36 +0000105static LinkageInfo getLVForType(QualType T) {
106 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
107 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
108}
109
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000110/// \brief Get the most restrictive linkage for the types in the given
111/// template parameter list.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000112static LinkageInfo
John McCall1fb0caa2010-10-22 21:05:15 +0000113getLVForTemplateParameterList(const TemplateParameterList *Params) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000114 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000115 for (TemplateParameterList::const_iterator P = Params->begin(),
116 PEnd = Params->end();
117 P != PEnd; ++P) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000118 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
119 if (NTTP->isExpandedParameterPack()) {
120 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
121 QualType T = NTTP->getExpansionType(I);
122 if (!T->isDependentType())
Rafael Espindola093ecc92012-01-14 00:30:36 +0000123 LV.merge(getLVForType(T));
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000124 }
125 continue;
126 }
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000127
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000128 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000129 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000130 continue;
131 }
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000132 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000133
134 if (TemplateTemplateParmDecl *TTP
135 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000136 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000137 }
138 }
139
John McCall1fb0caa2010-10-22 21:05:15 +0000140 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000141}
142
Douglas Gregor381d34e2010-12-06 18:36:25 +0000143/// getLVForDecl - Get the linkage and visibility for the given declaration.
144static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
145
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000146/// \brief Get the most restrictive linkage for the types and
147/// declarations in the given template argument list.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000148static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
149 unsigned NumArgs,
150 LVFlags &F) {
151 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000152
153 for (unsigned I = 0; I != NumArgs; ++I) {
154 switch (Args[I].getKind()) {
155 case TemplateArgument::Null:
156 case TemplateArgument::Integral:
157 case TemplateArgument::Expression:
158 break;
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000159
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000160 case TemplateArgument::Type:
Rafael Espindola093ecc92012-01-14 00:30:36 +0000161 LV.merge(getLVForType(Args[I].getAsType()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000162 break;
163
164 case TemplateArgument::Declaration:
John McCall1fb0caa2010-10-22 21:05:15 +0000165 // The decl can validly be null as the representation of nullptr
166 // arguments, valid only in C++0x.
167 if (Decl *D = Args[I].getAsDecl()) {
Douglas Gregor89d63e52010-12-06 18:50:56 +0000168 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
169 LV = merge(LV, getLVForDecl(ND, F));
John McCall1fb0caa2010-10-22 21:05:15 +0000170 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000171 break;
172
173 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +0000174 case TemplateArgument::TemplateExpansion:
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000175 if (TemplateDecl *Template
Douglas Gregora7fc9012011-01-05 18:58:31 +0000176 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindola093ecc92012-01-14 00:30:36 +0000177 LV.merge(getLVForDecl(Template, F));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000178 break;
179
180 case TemplateArgument::Pack:
Rafael Espindola093ecc92012-01-14 00:30:36 +0000181 LV.merge(getLVForTemplateArgumentList(Args[I].pack_begin(),
182 Args[I].pack_size(),
183 F));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000184 break;
185 }
186 }
187
John McCall1fb0caa2010-10-22 21:05:15 +0000188 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000189}
190
Rafael Espindola093ecc92012-01-14 00:30:36 +0000191static LinkageInfo
Douglas Gregor381d34e2010-12-06 18:36:25 +0000192getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
193 LVFlags &F) {
194 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
John McCall3cdfc4d2010-08-13 08:35:10 +0000195}
196
John McCall6ce51ee2011-06-27 23:06:04 +0000197static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
198 const FunctionTemplateSpecializationInfo *spec) {
199 return !(spec->isExplicitSpecialization() &&
200 fn->hasAttr<VisibilityAttr>());
201}
202
203static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
204 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
205}
206
John McCall36987482010-11-02 01:45:15 +0000207static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000208 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregord85b5b92009-11-25 22:24:25 +0000209 "Not a name having namespace scope");
210 ASTContext &Context = D->getASTContext();
211
212 // C++ [basic.link]p3:
213 // A name having namespace scope (3.3.6) has internal linkage if it
214 // is the name of
215 // - an object, reference, function or function template that is
216 // explicitly declared static; or,
217 // (This bullet corresponds to C99 6.2.2p3.)
218 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
219 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000220 if (Var->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000221 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000222
223 // - an object or reference that is explicitly declared const
224 // and neither explicitly declared extern nor previously
225 // declared to have external linkage; or
226 // (there is no equivalent in C99)
227 if (Context.getLangOptions().CPlusPlus &&
Eli Friedmane9d65542009-11-26 03:04:01 +0000228 Var->getType().isConstant(Context) &&
John McCalld931b082010-08-26 03:08:43 +0000229 Var->getStorageClass() != SC_Extern &&
230 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregord85b5b92009-11-25 22:24:25 +0000231 bool FoundExtern = false;
232 for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
233 PrevVar && !FoundExtern;
234 PrevVar = PrevVar->getPreviousDeclaration())
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000235 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregord85b5b92009-11-25 22:24:25 +0000236 FoundExtern = true;
237
238 if (!FoundExtern)
John McCallaf146032010-10-30 11:50:40 +0000239 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000240 }
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000241 if (Var->getStorageClass() == SC_None) {
242 const VarDecl *PrevVar = Var->getPreviousDeclaration();
243 for (; PrevVar; PrevVar = PrevVar->getPreviousDeclaration())
244 if (PrevVar->getStorageClass() == SC_PrivateExtern)
245 break;
246 if (PrevVar)
247 return PrevVar->getLinkageAndVisibility();
248 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000249 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000250 // C++ [temp]p4:
251 // A non-member function template can have internal linkage; any
252 // other template name shall have external linkage.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000253 const FunctionDecl *Function = 0;
254 if (const FunctionTemplateDecl *FunTmpl
255 = dyn_cast<FunctionTemplateDecl>(D))
256 Function = FunTmpl->getTemplatedDecl();
257 else
258 Function = cast<FunctionDecl>(D);
259
260 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000261 if (Function->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000262 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000263 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
264 // - a data member of an anonymous union.
265 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallaf146032010-10-30 11:50:40 +0000266 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000267 }
268
Chandler Carruth094b6432011-02-24 19:03:39 +0000269 if (D->isInAnonymousNamespace()) {
270 const VarDecl *Var = dyn_cast<VarDecl>(D);
271 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
272 if ((!Var || !Var->isExternC()) && (!Func || !Func->isExternC()))
273 return LinkageInfo::uniqueExternal();
274 }
John McCalle7bc9722010-10-28 04:18:25 +0000275
John McCall1fb0caa2010-10-22 21:05:15 +0000276 // Set up the defaults.
277
278 // C99 6.2.2p5:
279 // If the declaration of an identifier for an object has file
280 // scope and no storage-class specifier, its linkage is
281 // external.
John McCallaf146032010-10-30 11:50:40 +0000282 LinkageInfo LV;
283
John McCall36987482010-11-02 01:45:15 +0000284 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000285 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
286 LV.setVisibility(*Vis, true);
John McCall36987482010-11-02 01:45:15 +0000287 F.ConsiderGlobalVisibility = false;
John McCall90f14502010-12-10 02:59:44 +0000288 } else {
289 // If we're declared in a namespace with a visibility attribute,
290 // use that namespace's visibility, but don't call it explicit.
291 for (const DeclContext *DC = D->getDeclContext();
292 !isa<TranslationUnitDecl>(DC);
293 DC = DC->getParent()) {
Rafael Espindola6f26b5e2012-01-01 17:48:19 +0000294 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
295 if (!ND) continue;
296 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
Rafael Espindola71cb8a22012-01-01 18:06:40 +0000297 LV.setVisibility(*Vis, true);
John McCall90f14502010-12-10 02:59:44 +0000298 F.ConsiderGlobalVisibility = false;
299 break;
300 }
301 }
John McCall36987482010-11-02 01:45:15 +0000302 }
John McCallaf146032010-10-30 11:50:40 +0000303 }
John McCall1fb0caa2010-10-22 21:05:15 +0000304
Douglas Gregord85b5b92009-11-25 22:24:25 +0000305 // C++ [basic.link]p4:
John McCall1fb0caa2010-10-22 21:05:15 +0000306
Douglas Gregord85b5b92009-11-25 22:24:25 +0000307 // A name having namespace scope has external linkage if it is the
308 // name of
309 //
310 // - an object or reference, unless it has internal linkage; or
311 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall110e8e52010-10-29 22:22:43 +0000312 // GCC applies the following optimization to variables and static
313 // data members, but not to functions:
314 //
John McCall1fb0caa2010-10-22 21:05:15 +0000315 // Modify the variable's LV by the LV of its type unless this is
316 // C or extern "C". This follows from [basic.link]p9:
317 // A type without linkage shall not be used as the type of a
318 // variable or function with external linkage unless
319 // - the entity has C language linkage, or
320 // - the entity is declared within an unnamed namespace, or
321 // - the entity is not used or is defined in the same
322 // translation unit.
323 // and [basic.link]p10:
324 // ...the types specified by all declarations referring to a
325 // given variable or function shall be identical...
326 // C does not have an equivalent rule.
327 //
John McCallac65c622010-10-26 04:59:26 +0000328 // Ignore this if we've got an explicit attribute; the user
329 // probably knows what they're doing.
330 //
John McCall1fb0caa2010-10-22 21:05:15 +0000331 // Note that we don't want to make the variable non-external
332 // because of this, but unique-external linkage suits us.
John McCallee301022010-10-30 09:18:49 +0000333 if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000334 LinkageInfo TypeLV = getLVForType(Var->getType());
335 if (TypeLV.linkage() != ExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000336 return LinkageInfo::uniqueExternal();
337 if (!LV.visibilityExplicit())
Rafael Espindola093ecc92012-01-14 00:30:36 +0000338 LV.mergeVisibility(TypeLV.visibility(), TypeLV.visibilityExplicit());
John McCall110e8e52010-10-29 22:22:43 +0000339 }
340
John McCall35cebc32010-11-02 18:38:13 +0000341 if (Var->getStorageClass() == SC_PrivateExtern)
342 LV.setVisibility(HiddenVisibility, true);
343
Douglas Gregord85b5b92009-11-25 22:24:25 +0000344 if (!Context.getLangOptions().CPlusPlus &&
John McCalld931b082010-08-26 03:08:43 +0000345 (Var->getStorageClass() == SC_Extern ||
346 Var->getStorageClass() == SC_PrivateExtern)) {
John McCall1fb0caa2010-10-22 21:05:15 +0000347
Douglas Gregord85b5b92009-11-25 22:24:25 +0000348 // C99 6.2.2p4:
349 // For an identifier declared with the storage-class specifier
350 // extern in a scope in which a prior declaration of that
351 // identifier is visible, if the prior declaration specifies
352 // internal or external linkage, the linkage of the identifier
353 // at the later declaration is the same as the linkage
354 // specified at the prior declaration. If no prior declaration
355 // is visible, or if the prior declaration specifies no
356 // linkage, then the identifier has external linkage.
357 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000358 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
John McCallaf146032010-10-30 11:50:40 +0000359 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
360 LV.mergeVisibility(PrevLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000361 }
362 }
363
Douglas Gregord85b5b92009-11-25 22:24:25 +0000364 // - a function, unless it has internal linkage; or
John McCall1fb0caa2010-10-22 21:05:15 +0000365 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall67fa6d52010-10-28 07:07:52 +0000366 // In theory, we can modify the function's LV by the LV of its
367 // type unless it has C linkage (see comment above about variables
368 // for justification). In practice, GCC doesn't do this, so it's
369 // just too painful to make work.
John McCall1fb0caa2010-10-22 21:05:15 +0000370
John McCall35cebc32010-11-02 18:38:13 +0000371 if (Function->getStorageClass() == SC_PrivateExtern)
372 LV.setVisibility(HiddenVisibility, true);
373
Douglas Gregord85b5b92009-11-25 22:24:25 +0000374 // C99 6.2.2p5:
375 // If the declaration of an identifier for a function has no
376 // storage-class specifier, its linkage is determined exactly
377 // as if it were declared with the storage-class specifier
378 // extern.
379 if (!Context.getLangOptions().CPlusPlus &&
John McCalld931b082010-08-26 03:08:43 +0000380 (Function->getStorageClass() == SC_Extern ||
381 Function->getStorageClass() == SC_PrivateExtern ||
382 Function->getStorageClass() == SC_None)) {
Douglas Gregord85b5b92009-11-25 22:24:25 +0000383 // C99 6.2.2p4:
384 // For an identifier declared with the storage-class specifier
385 // extern in a scope in which a prior declaration of that
386 // identifier is visible, if the prior declaration specifies
387 // internal or external linkage, the linkage of the identifier
388 // at the later declaration is the same as the linkage
389 // specified at the prior declaration. If no prior declaration
390 // is visible, or if the prior declaration specifies no
391 // linkage, then the identifier has external linkage.
392 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000393 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
John McCallaf146032010-10-30 11:50:40 +0000394 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
395 LV.mergeVisibility(PrevLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000396 }
397 }
398
John McCallaf8ca372011-02-10 06:50:24 +0000399 // In C++, then if the type of the function uses a type with
400 // unique-external linkage, it's not legally usable from outside
401 // this translation unit. However, we should use the C linkage
402 // rules instead for extern "C" declarations.
403 if (Context.getLangOptions().CPlusPlus && !Function->isExternC() &&
404 Function->getType()->getLinkage() == UniqueExternalLinkage)
405 return LinkageInfo::uniqueExternal();
406
John McCall6ce51ee2011-06-27 23:06:04 +0000407 // Consider LV from the template and the template arguments unless
408 // this is an explicit specialization with a visibility attribute.
409 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000410 = Function->getTemplateSpecializationInfo()) {
John McCall6ce51ee2011-06-27 23:06:04 +0000411 if (shouldConsiderTemplateLV(Function, specInfo)) {
412 LV.merge(getLVForDecl(specInfo->getTemplate(),
413 F.onlyTemplateVisibility()));
414 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
415 LV.merge(getLVForTemplateArgumentList(templateArgs, F));
416 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000417 }
418
Douglas Gregord85b5b92009-11-25 22:24:25 +0000419 // - a named class (Clause 9), or an unnamed class defined in a
420 // typedef declaration in which the class has the typedef name
421 // for linkage purposes (7.1.3); or
422 // - a named enumeration (7.2), or an unnamed enumeration
423 // defined in a typedef declaration in which the enumeration
424 // has the typedef name for linkage purposes (7.1.3); or
John McCall1fb0caa2010-10-22 21:05:15 +0000425 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
426 // Unnamed tags have no linkage.
Richard Smith162e1c12011-04-15 14:24:37 +0000427 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallaf146032010-10-30 11:50:40 +0000428 return LinkageInfo::none();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000429
John McCall1fb0caa2010-10-22 21:05:15 +0000430 // If this is a class template specialization, consider the
431 // linkage of the template and template arguments.
John McCall6ce51ee2011-06-27 23:06:04 +0000432 if (const ClassTemplateSpecializationDecl *spec
John McCall1fb0caa2010-10-22 21:05:15 +0000433 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000434 if (shouldConsiderTemplateLV(spec)) {
435 // From the template.
436 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
437 F.onlyTemplateVisibility()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000438
John McCall6ce51ee2011-06-27 23:06:04 +0000439 // The arguments at which the template was instantiated.
440 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
441 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
442 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000443 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000444
John McCallac65c622010-10-26 04:59:26 +0000445 // Consider -fvisibility unless the type has C linkage.
John McCall36987482010-11-02 01:45:15 +0000446 if (F.ConsiderGlobalVisibility)
447 F.ConsiderGlobalVisibility =
John McCallac65c622010-10-26 04:59:26 +0000448 (Context.getLangOptions().CPlusPlus &&
449 !Tag->getDeclContext()->isExternCContext());
John McCall1fb0caa2010-10-22 21:05:15 +0000450
Douglas Gregord85b5b92009-11-25 22:24:25 +0000451 // - an enumerator belonging to an enumeration with external linkage;
John McCall1fb0caa2010-10-22 21:05:15 +0000452 } else if (isa<EnumConstantDecl>(D)) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000453 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
John McCallaf146032010-10-30 11:50:40 +0000454 if (!isExternalLinkage(EnumLV.linkage()))
455 return LinkageInfo::none();
456 LV.merge(EnumLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000457
458 // - a template, unless it is a function template that has
459 // internal linkage (Clause 14);
John McCall1a0918a2011-03-04 10:39:25 +0000460 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
461 if (F.ConsiderTemplateParameterTypes)
462 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000463
Douglas Gregord85b5b92009-11-25 22:24:25 +0000464 // - a namespace (7.3), unless it is declared within an unnamed
465 // namespace.
John McCall1fb0caa2010-10-22 21:05:15 +0000466 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
467 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000468
John McCall1fb0caa2010-10-22 21:05:15 +0000469 // By extension, we assign external linkage to Objective-C
470 // interfaces.
471 } else if (isa<ObjCInterfaceDecl>(D)) {
472 // fallout
473
474 // Everything not covered here has no linkage.
475 } else {
John McCallaf146032010-10-30 11:50:40 +0000476 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000477 }
478
479 // If we ended up with non-external linkage, visibility should
480 // always be default.
John McCallaf146032010-10-30 11:50:40 +0000481 if (LV.linkage() != ExternalLinkage)
482 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall1fb0caa2010-10-22 21:05:15 +0000483
484 // If we didn't end up with hidden visibility, consider attributes
485 // and -fvisibility.
John McCall36987482010-11-02 01:45:15 +0000486 if (F.ConsiderGlobalVisibility)
John McCallaf146032010-10-30 11:50:40 +0000487 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
John McCall1fb0caa2010-10-22 21:05:15 +0000488
489 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000490}
491
John McCall36987482010-11-02 01:45:15 +0000492static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
John McCall1fb0caa2010-10-22 21:05:15 +0000493 // Only certain class members have linkage. Note that fields don't
494 // really have linkage, but it's convenient to say they do for the
495 // purposes of calculating linkage of pointer-to-data-member
496 // template arguments.
John McCall3cdfc4d2010-08-13 08:35:10 +0000497 if (!(isa<CXXMethodDecl>(D) ||
498 isa<VarDecl>(D) ||
John McCall1fb0caa2010-10-22 21:05:15 +0000499 isa<FieldDecl>(D) ||
John McCall3cdfc4d2010-08-13 08:35:10 +0000500 (isa<TagDecl>(D) &&
Richard Smith162e1c12011-04-15 14:24:37 +0000501 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
John McCallaf146032010-10-30 11:50:40 +0000502 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000503
John McCall36987482010-11-02 01:45:15 +0000504 LinkageInfo LV;
505
506 // The flags we're going to use to compute the class's visibility.
507 LVFlags ClassF = F;
508
509 // If we have an explicit visibility attribute, merge that in.
510 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000511 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
512 LV.mergeVisibility(*Vis, true);
John McCall36987482010-11-02 01:45:15 +0000513
514 // Ignore global visibility later, but not this attribute.
515 F.ConsiderGlobalVisibility = false;
516
517 // Ignore both global visibility and attributes when computing our
518 // parent's visibility.
519 ClassF = F.onlyTemplateVisibility();
520 }
521 }
John McCallaf146032010-10-30 11:50:40 +0000522
523 // Class members only have linkage if their class has external
John McCall36987482010-11-02 01:45:15 +0000524 // linkage.
525 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
526 if (!isExternalLinkage(LV.linkage()))
John McCallaf146032010-10-30 11:50:40 +0000527 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000528
529 // If the class already has unique-external linkage, we can't improve.
John McCall36987482010-11-02 01:45:15 +0000530 if (LV.linkage() == UniqueExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000531 return LinkageInfo::uniqueExternal();
John McCall3cdfc4d2010-08-13 08:35:10 +0000532
John McCall3cdfc4d2010-08-13 08:35:10 +0000533 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallaf8ca372011-02-10 06:50:24 +0000534 // If the type of the function uses a type with unique-external
535 // linkage, it's not legally usable from outside this translation unit.
536 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
537 return LinkageInfo::uniqueExternal();
538
John McCall110e8e52010-10-29 22:22:43 +0000539 TemplateSpecializationKind TSK = TSK_Undeclared;
540
John McCall1fb0caa2010-10-22 21:05:15 +0000541 // If this is a method template specialization, use the linkage for
542 // the template parameters and arguments.
John McCall6ce51ee2011-06-27 23:06:04 +0000543 if (FunctionTemplateSpecializationInfo *spec
John McCall3cdfc4d2010-08-13 08:35:10 +0000544 = MD->getTemplateSpecializationInfo()) {
John McCall6ce51ee2011-06-27 23:06:04 +0000545 if (shouldConsiderTemplateLV(MD, spec)) {
546 LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F));
547 if (F.ConsiderTemplateParameterTypes)
548 LV.merge(getLVForTemplateParameterList(
549 spec->getTemplate()->getTemplateParameters()));
550 }
John McCall110e8e52010-10-29 22:22:43 +0000551
John McCall6ce51ee2011-06-27 23:06:04 +0000552 TSK = spec->getTemplateSpecializationKind();
John McCall110e8e52010-10-29 22:22:43 +0000553 } else if (MemberSpecializationInfo *MSI =
554 MD->getMemberSpecializationInfo()) {
555 TSK = MSI->getTemplateSpecializationKind();
John McCall3cdfc4d2010-08-13 08:35:10 +0000556 }
557
John McCall110e8e52010-10-29 22:22:43 +0000558 // If we're paying attention to global visibility, apply
559 // -finline-visibility-hidden if this is an inline method.
560 //
John McCallaf146032010-10-30 11:50:40 +0000561 // Note that ConsiderGlobalVisibility doesn't yet have information
562 // about whether containing classes have visibility attributes,
563 // and that's intentional.
564 if (TSK != TSK_ExplicitInstantiationDeclaration &&
Rafael Espindolafedb6ec2011-12-27 21:15:28 +0000565 TSK != TSK_ExplicitInstantiationDefinition &&
John McCall36987482010-11-02 01:45:15 +0000566 F.ConsiderGlobalVisibility &&
John McCall66cbcf32010-11-01 01:29:57 +0000567 MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
568 // InlineVisibilityHidden only applies to definitions, and
569 // isInlined() only gives meaningful answers on definitions
570 // anyway.
571 const FunctionDecl *Def = 0;
572 if (MD->hasBody(Def) && Def->isInlined())
573 LV.setVisibility(HiddenVisibility);
574 }
John McCall1fb0caa2010-10-22 21:05:15 +0000575
John McCall110e8e52010-10-29 22:22:43 +0000576 // Note that in contrast to basically every other situation, we
577 // *do* apply -fvisibility to method declarations.
578
579 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000580 if (const ClassTemplateSpecializationDecl *spec
John McCall110e8e52010-10-29 22:22:43 +0000581 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000582 if (shouldConsiderTemplateLV(spec)) {
583 // Merge template argument/parameter information for member
584 // class template specializations.
585 LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
John McCall1a0918a2011-03-04 10:39:25 +0000586 if (F.ConsiderTemplateParameterTypes)
587 LV.merge(getLVForTemplateParameterList(
John McCall6ce51ee2011-06-27 23:06:04 +0000588 spec->getSpecializedTemplate()->getTemplateParameters()));
589 }
John McCall110e8e52010-10-29 22:22:43 +0000590 }
591
John McCall110e8e52010-10-29 22:22:43 +0000592 // Static data members.
593 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallee301022010-10-30 09:18:49 +0000594 // Modify the variable's linkage by its type, but ignore the
595 // type's visibility unless it's a definition.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000596 LinkageInfo TypeLV = getLVForType(VD->getType());
597 if (TypeLV.linkage() != ExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000598 LV.mergeLinkage(UniqueExternalLinkage);
599 if (!LV.visibilityExplicit())
Rafael Espindola093ecc92012-01-14 00:30:36 +0000600 LV.mergeVisibility(TypeLV.visibility(), TypeLV.visibilityExplicit());
John McCall110e8e52010-10-29 22:22:43 +0000601 }
602
John McCall36987482010-11-02 01:45:15 +0000603 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
John McCall110e8e52010-10-29 22:22:43 +0000604
605 // Apply -fvisibility if desired.
John McCall36987482010-11-02 01:45:15 +0000606 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
John McCallaf146032010-10-30 11:50:40 +0000607 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
John McCall3cdfc4d2010-08-13 08:35:10 +0000608 }
609
John McCall1fb0caa2010-10-22 21:05:15 +0000610 return LV;
John McCall3cdfc4d2010-08-13 08:35:10 +0000611}
612
John McCallf76b0922011-02-08 19:01:05 +0000613static void clearLinkageForClass(const CXXRecordDecl *record) {
614 for (CXXRecordDecl::decl_iterator
615 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
616 Decl *child = *i;
617 if (isa<NamedDecl>(child))
618 cast<NamedDecl>(child)->ClearLinkageCache();
619 }
620}
621
David Blaikie99ba9e32011-12-20 02:48:34 +0000622void NamedDecl::anchor() { }
623
John McCallf76b0922011-02-08 19:01:05 +0000624void NamedDecl::ClearLinkageCache() {
625 // Note that we can't skip clearing the linkage of children just
626 // because the parent doesn't have cached linkage: we don't cache
627 // when computing linkage for parent contexts.
628
629 HasCachedLinkage = 0;
630
631 // If we're changing the linkage of a class, we need to reset the
632 // linkage of child declarations, too.
633 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
634 clearLinkageForClass(record);
635
John McCall15e310a2011-02-19 02:53:41 +0000636 if (ClassTemplateDecl *temp =
637 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
John McCallf76b0922011-02-08 19:01:05 +0000638 // Clear linkage for the template pattern.
639 CXXRecordDecl *record = temp->getTemplatedDecl();
640 record->HasCachedLinkage = 0;
641 clearLinkageForClass(record);
642
John McCall15e310a2011-02-19 02:53:41 +0000643 // We need to clear linkage for specializations, too.
644 for (ClassTemplateDecl::spec_iterator
645 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
646 i->ClearLinkageCache();
John McCallf76b0922011-02-08 19:01:05 +0000647 }
John McCall15e310a2011-02-19 02:53:41 +0000648
649 // Clear cached linkage for function template decls, too.
650 if (FunctionTemplateDecl *temp =
John McCall78951942011-03-22 06:58:49 +0000651 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
652 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall15e310a2011-02-19 02:53:41 +0000653 for (FunctionTemplateDecl::spec_iterator
654 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
655 i->ClearLinkageCache();
John McCall78951942011-03-22 06:58:49 +0000656 }
John McCall15e310a2011-02-19 02:53:41 +0000657
John McCallf76b0922011-02-08 19:01:05 +0000658}
659
Douglas Gregor381d34e2010-12-06 18:36:25 +0000660Linkage NamedDecl::getLinkage() const {
661 if (HasCachedLinkage) {
Benjamin Kramer56ed7922010-12-07 15:51:48 +0000662 assert(Linkage(CachedLinkage) ==
663 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
Douglas Gregor381d34e2010-12-06 18:36:25 +0000664 return Linkage(CachedLinkage);
665 }
666
667 CachedLinkage = getLVForDecl(this,
668 LVFlags::CreateOnlyDeclLinkage()).linkage();
669 HasCachedLinkage = 1;
670 return Linkage(CachedLinkage);
671}
672
John McCallaf146032010-10-30 11:50:40 +0000673LinkageInfo NamedDecl::getLinkageAndVisibility() const {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000674 LinkageInfo LI = getLVForDecl(this, LVFlags());
Benjamin Kramer56ed7922010-12-07 15:51:48 +0000675 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
Douglas Gregor381d34e2010-12-06 18:36:25 +0000676 HasCachedLinkage = 1;
677 CachedLinkage = LI.linkage();
678 return LI;
John McCall0df95872010-10-29 00:29:13 +0000679}
Ted Kremenekbecc3082010-04-20 23:15:35 +0000680
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000681llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
682 // Use the most recent declaration of a variable.
683 if (const VarDecl *var = dyn_cast<VarDecl>(this))
684 return getVisibilityOf(var->getMostRecentDeclaration());
685
686 // Use the most recent declaration of a function, and also handle
687 // function template specializations.
688 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
689 if (llvm::Optional<Visibility> V
690 = getVisibilityOf(fn->getMostRecentDeclaration()))
691 return V;
692
693 // If the function is a specialization of a template with an
694 // explicit visibility attribute, use that.
695 if (FunctionTemplateSpecializationInfo *templateInfo
696 = fn->getTemplateSpecializationInfo())
697 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
698
699 return llvm::Optional<Visibility>();
700 }
701
702 // Otherwise, just check the declaration itself first.
703 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
704 return V;
705
706 // If there wasn't explicit visibility there, and this is a
707 // specialization of a class template, check for visibility
708 // on the pattern.
709 if (const ClassTemplateSpecializationDecl *spec
710 = dyn_cast<ClassTemplateSpecializationDecl>(this))
711 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
712
713 return llvm::Optional<Visibility>();
714}
715
John McCall36987482010-11-02 01:45:15 +0000716static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
Ted Kremenekbecc3082010-04-20 23:15:35 +0000717 // Objective-C: treat all Objective-C declarations as having external
718 // linkage.
John McCall0df95872010-10-29 00:29:13 +0000719 switch (D->getKind()) {
Ted Kremenekbecc3082010-04-20 23:15:35 +0000720 default:
721 break;
Argyrios Kyrtzidisf8d34ed2011-12-01 01:28:21 +0000722 case Decl::ParmVar:
723 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000724 case Decl::TemplateTemplateParm: // count these as external
725 case Decl::NonTypeTemplateParm:
Ted Kremenekbecc3082010-04-20 23:15:35 +0000726 case Decl::ObjCAtDefsField:
727 case Decl::ObjCCategory:
728 case Decl::ObjCCategoryImpl:
Ted Kremenekbecc3082010-04-20 23:15:35 +0000729 case Decl::ObjCCompatibleAlias:
Ted Kremenekbecc3082010-04-20 23:15:35 +0000730 case Decl::ObjCImplementation:
Ted Kremenekbecc3082010-04-20 23:15:35 +0000731 case Decl::ObjCMethod:
732 case Decl::ObjCProperty:
733 case Decl::ObjCPropertyImpl:
734 case Decl::ObjCProtocol:
John McCallaf146032010-10-30 11:50:40 +0000735 return LinkageInfo::external();
Ted Kremenekbecc3082010-04-20 23:15:35 +0000736 }
737
Douglas Gregord85b5b92009-11-25 22:24:25 +0000738 // Handle linkage for namespace-scope names.
John McCall0df95872010-10-29 00:29:13 +0000739 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall36987482010-11-02 01:45:15 +0000740 return getLVForNamespaceScopeDecl(D, Flags);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000741
742 // C++ [basic.link]p5:
743 // In addition, a member function, static data member, a named
744 // class or enumeration of class scope, or an unnamed class or
745 // enumeration defined in a class-scope typedef declaration such
746 // that the class or enumeration has the typedef name for linkage
747 // purposes (7.1.3), has external linkage if the name of the class
748 // has external linkage.
John McCall0df95872010-10-29 00:29:13 +0000749 if (D->getDeclContext()->isRecord())
John McCall36987482010-11-02 01:45:15 +0000750 return getLVForClassMember(D, Flags);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000751
752 // C++ [basic.link]p6:
753 // The name of a function declared in block scope and the name of
754 // an object declared by a block scope extern declaration have
755 // linkage. If there is a visible declaration of an entity with
756 // linkage having the same name and type, ignoring entities
757 // declared outside the innermost enclosing namespace scope, the
758 // block scope declaration declares that same entity and receives
759 // the linkage of the previous declaration. If there is more than
760 // one such matching entity, the program is ill-formed. Otherwise,
761 // if no matching entity is found, the block scope entity receives
762 // external linkage.
John McCall0df95872010-10-29 00:29:13 +0000763 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
764 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Chandler Carruth10aad442011-02-25 00:05:02 +0000765 if (Function->isInAnonymousNamespace() && !Function->isExternC())
John McCallaf146032010-10-30 11:50:40 +0000766 return LinkageInfo::uniqueExternal();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000767
John McCallaf146032010-10-30 11:50:40 +0000768 LinkageInfo LV;
Douglas Gregor381d34e2010-12-06 18:36:25 +0000769 if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000770 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
771 LV.setVisibility(*Vis);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000772 }
773
John McCall1fb0caa2010-10-22 21:05:15 +0000774 if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000775 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallaf146032010-10-30 11:50:40 +0000776 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
777 LV.mergeVisibility(PrevLV);
John McCall1fb0caa2010-10-22 21:05:15 +0000778 }
779
780 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000781 }
782
John McCall0df95872010-10-29 00:29:13 +0000783 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
John McCalld931b082010-08-26 03:08:43 +0000784 if (Var->getStorageClass() == SC_Extern ||
785 Var->getStorageClass() == SC_PrivateExtern) {
Chandler Carruth10aad442011-02-25 00:05:02 +0000786 if (Var->isInAnonymousNamespace() && !Var->isExternC())
John McCallaf146032010-10-30 11:50:40 +0000787 return LinkageInfo::uniqueExternal();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000788
John McCallaf146032010-10-30 11:50:40 +0000789 LinkageInfo LV;
John McCall1fb0caa2010-10-22 21:05:15 +0000790 if (Var->getStorageClass() == SC_PrivateExtern)
John McCallaf146032010-10-30 11:50:40 +0000791 LV.setVisibility(HiddenVisibility);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000792 else if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000793 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
794 LV.setVisibility(*Vis);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000795 }
796
John McCall1fb0caa2010-10-22 21:05:15 +0000797 if (const VarDecl *Prev = Var->getPreviousDeclaration()) {
Douglas Gregor381d34e2010-12-06 18:36:25 +0000798 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallaf146032010-10-30 11:50:40 +0000799 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
800 LV.mergeVisibility(PrevLV);
John McCall1fb0caa2010-10-22 21:05:15 +0000801 }
802
803 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000804 }
805 }
806
807 // C++ [basic.link]p6:
808 // Names not covered by these rules have no linkage.
John McCallaf146032010-10-30 11:50:40 +0000809 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000810}
Douglas Gregord85b5b92009-11-25 22:24:25 +0000811
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000812std::string NamedDecl::getQualifiedNameAsString() const {
Anders Carlsson3a082d82009-09-08 18:24:21 +0000813 return getQualifiedNameAsString(getASTContext().getLangOptions());
814}
815
816std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000817 const DeclContext *Ctx = getDeclContext();
818
819 if (Ctx->isFunctionOrMethod())
820 return getNameAsString();
821
Chris Lattner5f9e2722011-07-23 10:55:15 +0000822 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000823 ContextsTy Contexts;
824
825 // Collect contexts.
826 while (Ctx && isa<NamedDecl>(Ctx)) {
827 Contexts.push_back(Ctx);
828 Ctx = Ctx->getParent();
829 };
830
831 std::string QualName;
832 llvm::raw_string_ostream OS(QualName);
833
834 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
835 I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +0000836 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000837 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000838 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
839 std::string TemplateArgsStr
840 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +0000841 TemplateArgs.data(),
842 TemplateArgs.size(),
Anders Carlsson3a082d82009-09-08 18:24:21 +0000843 P);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000844 OS << Spec->getName() << TemplateArgsStr;
845 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig6be11202009-12-24 23:15:03 +0000846 if (ND->isAnonymousNamespace())
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000847 OS << "<anonymous namespace>";
Sam Weinig6be11202009-12-24 23:15:03 +0000848 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000849 OS << *ND;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000850 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
851 if (!RD->getIdentifier())
852 OS << "<anonymous " << RD->getKindName() << '>';
853 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000854 OS << *RD;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000855 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinig3521d012009-12-28 03:19:38 +0000856 const FunctionProtoType *FT = 0;
857 if (FD->hasWrittenPrototype())
858 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
859
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000860 OS << *FD << '(';
Sam Weinig3521d012009-12-28 03:19:38 +0000861 if (FT) {
Sam Weinig3521d012009-12-28 03:19:38 +0000862 unsigned NumParams = FD->getNumParams();
863 for (unsigned i = 0; i < NumParams; ++i) {
864 if (i)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000865 OS << ", ";
Sam Weinig3521d012009-12-28 03:19:38 +0000866 std::string Param;
867 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000868 OS << Param;
Sam Weinig3521d012009-12-28 03:19:38 +0000869 }
870
871 if (FT->isVariadic()) {
872 if (NumParams > 0)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000873 OS << ", ";
874 OS << "...";
Sam Weinig3521d012009-12-28 03:19:38 +0000875 }
876 }
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000877 OS << ')';
878 } else {
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000879 OS << *cast<NamedDecl>(*I);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000880 }
881 OS << "::";
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000882 }
883
John McCall8472af42010-03-16 21:48:18 +0000884 if (getDeclName())
Benjamin Kramerb8989f22011-10-14 18:45:37 +0000885 OS << *this;
John McCall8472af42010-03-16 21:48:18 +0000886 else
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000887 OS << "<anonymous>";
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000888
Benjamin Kramer68eebbb2010-04-28 14:33:51 +0000889 return OS.str();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000890}
891
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000892bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000893 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
894
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000895 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
896 // We want to keep it, unless it nominates same namespace.
897 if (getKind() == Decl::UsingDirective) {
Douglas Gregordb992412011-02-25 16:33:46 +0000898 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
899 ->getOriginalNamespace() ==
900 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
901 ->getOriginalNamespace();
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000902 }
Mike Stump1eb44332009-09-09 15:08:12 +0000903
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000904 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
905 // For function declarations, we keep track of redeclarations.
906 return FD->getPreviousDeclaration() == OldD;
907
Douglas Gregore53060f2009-06-25 22:08:12 +0000908 // For function templates, the underlying function declarations are linked.
909 if (const FunctionTemplateDecl *FunctionTemplate
910 = dyn_cast<FunctionTemplateDecl>(this))
911 if (const FunctionTemplateDecl *OldFunctionTemplate
912 = dyn_cast<FunctionTemplateDecl>(OldD))
913 return FunctionTemplate->getTemplatedDecl()
914 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Steve Naroff0de21fd2009-02-22 19:35:57 +0000916 // For method declarations, we keep track of redeclarations.
917 if (isa<ObjCMethodDecl>(this))
918 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
John McCallf36e02d2009-10-09 21:13:30 +0000920 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
921 return true;
922
John McCall9488ea12009-11-17 05:59:44 +0000923 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
924 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
925 cast<UsingShadowDecl>(OldD)->getTargetDecl();
926
Douglas Gregordc355712011-02-25 00:36:19 +0000927 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
928 ASTContext &Context = getASTContext();
929 return Context.getCanonicalNestedNameSpecifier(
930 cast<UsingDecl>(this)->getQualifier()) ==
931 Context.getCanonicalNestedNameSpecifier(
932 cast<UsingDecl>(OldD)->getQualifier());
933 }
Argyrios Kyrtzidisc80117e2010-11-04 08:48:52 +0000934
Douglas Gregor7a537402012-01-03 23:26:26 +0000935 // A typedef of an Objective-C class type can replace an Objective-C class
936 // declaration or definition, and vice versa.
937 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
938 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
939 return true;
940
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000941 // For non-function declarations, if the declarations are of the
942 // same kind then this must be a redeclaration, or semantic analysis
943 // would not have given us the new declaration.
944 return this->getKind() == OldD->getKind();
945}
946
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000947bool NamedDecl::hasLinkage() const {
Douglas Gregord85b5b92009-11-25 22:24:25 +0000948 return getLinkage() != NoLinkage;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000949}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000950
Anders Carlssone136e0e2009-06-26 06:29:23 +0000951NamedDecl *NamedDecl::getUnderlyingDecl() {
952 NamedDecl *ND = this;
953 while (true) {
John McCall9488ea12009-11-17 05:59:44 +0000954 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
Anders Carlssone136e0e2009-06-26 06:29:23 +0000955 ND = UD->getTargetDecl();
956 else if (ObjCCompatibleAliasDecl *AD
957 = dyn_cast<ObjCCompatibleAliasDecl>(ND))
958 return AD->getClassInterface();
959 else
960 return ND;
961 }
962}
963
John McCall161755a2010-04-06 21:38:20 +0000964bool NamedDecl::isCXXInstanceMember() const {
965 assert(isCXXClassMember() &&
966 "checking whether non-member is instance member");
967
968 const NamedDecl *D = this;
969 if (isa<UsingShadowDecl>(D))
970 D = cast<UsingShadowDecl>(D)->getTargetDecl();
971
Francois Pichet87c2e122010-11-21 06:08:52 +0000972 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCall161755a2010-04-06 21:38:20 +0000973 return true;
974 if (isa<CXXMethodDecl>(D))
975 return cast<CXXMethodDecl>(D)->isInstance();
976 if (isa<FunctionTemplateDecl>(D))
977 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
978 ->getTemplatedDecl())->isInstance();
979 return false;
980}
981
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000982//===----------------------------------------------------------------------===//
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000983// DeclaratorDecl Implementation
984//===----------------------------------------------------------------------===//
985
Douglas Gregor1693e152010-07-06 18:42:40 +0000986template <typename DeclT>
987static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
988 if (decl->getNumTemplateParameterLists() > 0)
989 return decl->getTemplateParameterList(0)->getTemplateLoc();
990 else
991 return decl->getInnerLocStart();
992}
993
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000994SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCall4e449832010-05-28 23:32:21 +0000995 TypeSourceInfo *TSI = getTypeSourceInfo();
996 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000997 return SourceLocation();
998}
999
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001000void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1001 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00001002 // Make sure the extended decl info is allocated.
1003 if (!hasExtInfo()) {
1004 // Save (non-extended) type source info pointer.
1005 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1006 // Allocate external info struct.
1007 DeclInfo = new (getASTContext()) ExtInfo;
1008 // Restore savedTInfo into (extended) decl info.
1009 getExtInfo()->TInfo = savedTInfo;
1010 }
1011 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001012 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00001013 } else {
John McCallb6217662010-03-15 10:12:16 +00001014 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00001015 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001016 if (getExtInfo()->NumTemplParamLists == 0) {
1017 // Save type source info pointer.
1018 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1019 // Deallocate the extended decl info.
1020 getASTContext().Deallocate(getExtInfo());
1021 // Restore savedTInfo into (non-extended) decl info.
1022 DeclInfo = savedTInfo;
1023 }
1024 else
1025 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00001026 }
1027 }
1028}
1029
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001030void
1031DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1032 unsigned NumTPLists,
1033 TemplateParameterList **TPLists) {
1034 assert(NumTPLists > 0);
1035 // Make sure the extended decl info is allocated.
1036 if (!hasExtInfo()) {
1037 // Save (non-extended) type source info pointer.
1038 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1039 // Allocate external info struct.
1040 DeclInfo = new (getASTContext()) ExtInfo;
1041 // Restore savedTInfo into (extended) decl info.
1042 getExtInfo()->TInfo = savedTInfo;
1043 }
1044 // Set the template parameter lists info.
1045 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1046}
1047
Douglas Gregor1693e152010-07-06 18:42:40 +00001048SourceLocation DeclaratorDecl::getOuterLocStart() const {
1049 return getTemplateOrInnerLocStart(this);
1050}
1051
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001052namespace {
1053
1054// Helper function: returns true if QT is or contains a type
1055// having a postfix component.
1056bool typeIsPostfix(clang::QualType QT) {
1057 while (true) {
1058 const Type* T = QT.getTypePtr();
1059 switch (T->getTypeClass()) {
1060 default:
1061 return false;
1062 case Type::Pointer:
1063 QT = cast<PointerType>(T)->getPointeeType();
1064 break;
1065 case Type::BlockPointer:
1066 QT = cast<BlockPointerType>(T)->getPointeeType();
1067 break;
1068 case Type::MemberPointer:
1069 QT = cast<MemberPointerType>(T)->getPointeeType();
1070 break;
1071 case Type::LValueReference:
1072 case Type::RValueReference:
1073 QT = cast<ReferenceType>(T)->getPointeeType();
1074 break;
1075 case Type::PackExpansion:
1076 QT = cast<PackExpansionType>(T)->getPattern();
1077 break;
1078 case Type::Paren:
1079 case Type::ConstantArray:
1080 case Type::DependentSizedArray:
1081 case Type::IncompleteArray:
1082 case Type::VariableArray:
1083 case Type::FunctionProto:
1084 case Type::FunctionNoProto:
1085 return true;
1086 }
1087 }
1088}
1089
1090} // namespace
1091
1092SourceRange DeclaratorDecl::getSourceRange() const {
1093 SourceLocation RangeEnd = getLocation();
1094 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1095 if (typeIsPostfix(TInfo->getType()))
1096 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1097 }
1098 return SourceRange(getOuterLocStart(), RangeEnd);
1099}
1100
Abramo Bagnara9b934882010-06-12 08:15:14 +00001101void
Douglas Gregorc722ea42010-06-15 17:44:38 +00001102QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1103 unsigned NumTPLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00001104 TemplateParameterList **TPLists) {
1105 assert((NumTPLists == 0 || TPLists != 0) &&
1106 "Empty array of template parameters with positive size!");
Abramo Bagnara9b934882010-06-12 08:15:14 +00001107
1108 // Free previous template parameters (if any).
1109 if (NumTemplParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001110 Context.Deallocate(TemplParamLists);
Abramo Bagnara9b934882010-06-12 08:15:14 +00001111 TemplParamLists = 0;
1112 NumTemplParamLists = 0;
1113 }
1114 // Set info on matched template parameter lists (if any).
1115 if (NumTPLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001116 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnara9b934882010-06-12 08:15:14 +00001117 NumTemplParamLists = NumTPLists;
1118 for (unsigned i = NumTPLists; i-- > 0; )
1119 TemplParamLists[i] = TPLists[i];
1120 }
1121}
1122
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001123//===----------------------------------------------------------------------===//
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001124// VarDecl Implementation
1125//===----------------------------------------------------------------------===//
1126
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001127const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1128 switch (SC) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00001129 case SC_None: break;
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001130 case SC_Auto: return "auto";
1131 case SC_Extern: return "extern";
1132 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1133 case SC_PrivateExtern: return "__private_extern__";
1134 case SC_Register: return "register";
1135 case SC_Static: return "static";
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001136 }
1137
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001138 llvm_unreachable("Invalid storage class");
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001139 return 0;
1140}
1141
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001142VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1143 SourceLocation StartL, SourceLocation IdL,
John McCalla93c9342009-12-07 02:54:59 +00001144 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001145 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001146 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001147}
1148
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001149VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1150 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1151 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1152 QualType(), 0, SC_None, SC_None);
1153}
1154
Douglas Gregor381d34e2010-12-06 18:36:25 +00001155void VarDecl::setStorageClass(StorageClass SC) {
1156 assert(isLegalForVariable(SC));
1157 if (getStorageClass() != SC)
1158 ClearLinkageCache();
1159
John McCallf1e4fbf2011-05-01 02:13:58 +00001160 VarDeclBits.SClass = SC;
Douglas Gregor381d34e2010-12-06 18:36:25 +00001161}
1162
Douglas Gregor1693e152010-07-06 18:42:40 +00001163SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001164 if (getInit())
Douglas Gregor1693e152010-07-06 18:42:40 +00001165 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001166 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001167}
1168
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001169bool VarDecl::isExternC() const {
1170 ASTContext &Context = getASTContext();
1171 if (!Context.getLangOptions().CPlusPlus)
1172 return (getDeclContext()->isTranslationUnit() &&
John McCalld931b082010-08-26 03:08:43 +00001173 getStorageClass() != SC_Static) ||
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001174 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
1175
Chandler Carruth10aad442011-02-25 00:05:02 +00001176 const DeclContext *DC = getDeclContext();
1177 if (DC->isFunctionOrMethod())
1178 return false;
1179
1180 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001181 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1182 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
John McCalld931b082010-08-26 03:08:43 +00001183 return getStorageClass() != SC_Static;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001184
1185 break;
1186 }
1187
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001188 }
1189
1190 return false;
1191}
1192
1193VarDecl *VarDecl::getCanonicalDecl() {
1194 return getFirstDeclaration();
1195}
1196
Sebastian Redle9d12b62010-01-31 22:27:38 +00001197VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
1198 // C++ [basic.def]p2:
1199 // A declaration is a definition unless [...] it contains the 'extern'
1200 // specifier or a linkage-specification and neither an initializer [...],
1201 // it declares a static data member in a class declaration [...].
1202 // C++ [temp.expl.spec]p15:
1203 // An explicit specialization of a static data member of a template is a
1204 // definition if the declaration includes an initializer; otherwise, it is
1205 // a declaration.
1206 if (isStaticDataMember()) {
1207 if (isOutOfLine() && (hasInit() ||
1208 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1209 return Definition;
1210 else
1211 return DeclarationOnly;
1212 }
1213 // C99 6.7p5:
1214 // A definition of an identifier is a declaration for that identifier that
1215 // [...] causes storage to be reserved for that object.
1216 // Note: that applies for all non-file-scope objects.
1217 // C99 6.9.2p1:
1218 // If the declaration of an identifier for an object has file scope and an
1219 // initializer, the declaration is an external definition for the identifier
1220 if (hasInit())
1221 return Definition;
1222 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1223 if (hasExternalStorage())
1224 return DeclarationOnly;
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001225
John McCalld931b082010-08-26 03:08:43 +00001226 if (getStorageClassAsWritten() == SC_Extern ||
1227 getStorageClassAsWritten() == SC_PrivateExtern) {
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001228 for (const VarDecl *PrevVar = getPreviousDeclaration();
1229 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
1230 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1231 return DeclarationOnly;
1232 }
1233 }
Sebastian Redle9d12b62010-01-31 22:27:38 +00001234 // C99 6.9.2p2:
1235 // A declaration of an object that has file scope without an initializer,
1236 // and without a storage class specifier or the scs 'static', constitutes
1237 // a tentative definition.
1238 // No such thing in C++.
1239 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
1240 return TentativeDefinition;
1241
1242 // What's left is (in C, block-scope) declarations without initializers or
1243 // external storage. These are definitions.
1244 return Definition;
1245}
1246
Sebastian Redle9d12b62010-01-31 22:27:38 +00001247VarDecl *VarDecl::getActingDefinition() {
1248 DefinitionKind Kind = isThisDeclarationADefinition();
1249 if (Kind != TentativeDefinition)
1250 return 0;
1251
Chris Lattnerf0ed9ef2010-06-14 18:31:46 +00001252 VarDecl *LastTentative = 0;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001253 VarDecl *First = getFirstDeclaration();
1254 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1255 I != E; ++I) {
1256 Kind = (*I)->isThisDeclarationADefinition();
1257 if (Kind == Definition)
1258 return 0;
1259 else if (Kind == TentativeDefinition)
1260 LastTentative = *I;
1261 }
1262 return LastTentative;
1263}
1264
1265bool VarDecl::isTentativeDefinitionNow() const {
1266 DefinitionKind Kind = isThisDeclarationADefinition();
1267 if (Kind != TentativeDefinition)
1268 return false;
1269
1270 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1271 if ((*I)->isThisDeclarationADefinition() == Definition)
1272 return false;
1273 }
Sebastian Redl31310a22010-02-01 20:16:42 +00001274 return true;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001275}
1276
Sebastian Redl31310a22010-02-01 20:16:42 +00001277VarDecl *VarDecl::getDefinition() {
Sebastian Redle2c52d22010-02-02 17:55:12 +00001278 VarDecl *First = getFirstDeclaration();
1279 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1280 I != E; ++I) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001281 if ((*I)->isThisDeclarationADefinition() == Definition)
1282 return *I;
1283 }
1284 return 0;
1285}
1286
John McCall110e8e52010-10-29 22:22:43 +00001287VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1288 DefinitionKind Kind = DeclarationOnly;
1289
1290 const VarDecl *First = getFirstDeclaration();
1291 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1292 I != E; ++I)
1293 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1294
1295 return Kind;
1296}
1297
Sebastian Redl31310a22010-02-01 20:16:42 +00001298const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001299 redecl_iterator I = redecls_begin(), E = redecls_end();
1300 while (I != E && !I->getInit())
1301 ++I;
1302
1303 if (I != E) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001304 D = *I;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001305 return I->getInit();
1306 }
1307 return 0;
1308}
1309
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001310bool VarDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00001311 if (Decl::isOutOfLine())
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001312 return true;
Chandler Carruth8761d682010-02-21 07:08:09 +00001313
1314 if (!isStaticDataMember())
1315 return false;
1316
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001317 // If this static data member was instantiated from a static data member of
1318 // a class template, check whether that static data member was defined
1319 // out-of-line.
1320 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1321 return VD->isOutOfLine();
1322
1323 return false;
1324}
1325
Douglas Gregor0d035142009-10-27 18:42:08 +00001326VarDecl *VarDecl::getOutOfLineDefinition() {
1327 if (!isStaticDataMember())
1328 return 0;
1329
1330 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1331 RD != RDEnd; ++RD) {
1332 if (RD->getLexicalDeclContext()->isFileContext())
1333 return *RD;
1334 }
1335
1336 return 0;
1337}
1338
Douglas Gregor838db382010-02-11 01:19:42 +00001339void VarDecl::setInit(Expr *I) {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001340 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1341 Eval->~EvaluatedStmt();
Douglas Gregor838db382010-02-11 01:19:42 +00001342 getASTContext().Deallocate(Eval);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001343 }
1344
1345 Init = I;
1346}
1347
Richard Smith1d238ea2011-12-21 02:55:12 +00001348bool VarDecl::isUsableInConstantExpressions() const {
1349 const LangOptions &Lang = getASTContext().getLangOptions();
1350
1351 // Only const variables can be used in constant expressions in C++. C++98 does
1352 // not require the variable to be non-volatile, but we consider this to be a
1353 // defect.
1354 if (!Lang.CPlusPlus ||
1355 !getType().isConstQualified() || getType().isVolatileQualified())
1356 return false;
1357
1358 // In C++, const, non-volatile variables of integral or enumeration types
1359 // can be used in constant expressions.
1360 if (getType()->isIntegralOrEnumerationType())
1361 return true;
1362
1363 // Additionally, in C++11, non-volatile constexpr variables and references can
1364 // be used in constant expressions.
1365 return Lang.CPlusPlus0x && (isConstexpr() || getType()->isReferenceType());
1366}
1367
Richard Smith099e7f62011-12-19 06:19:21 +00001368/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1369/// form, which contains extra information on the evaluated value of the
1370/// initializer.
1371EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1372 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1373 if (!Eval) {
1374 Stmt *S = Init.get<Stmt *>();
1375 Eval = new (getASTContext()) EvaluatedStmt;
1376 Eval->Value = S;
1377 Init = Eval;
1378 }
1379 return Eval;
1380}
1381
1382bool VarDecl::evaluateValue(
1383 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1384 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1385
1386 // We only produce notes indicating why an initializer is non-constant the
1387 // first time it is evaluated. FIXME: The notes won't always be emitted the
1388 // first time we try evaluation, so might not be produced at all.
1389 if (Eval->WasEvaluated)
1390 return !Eval->Evaluated.isUninit();
1391
1392 const Expr *Init = cast<Expr>(Eval->Value);
1393 assert(!Init->isValueDependent());
1394
1395 if (Eval->IsEvaluating) {
1396 // FIXME: Produce a diagnostic for self-initialization.
1397 Eval->CheckedICE = true;
1398 Eval->IsICE = false;
1399 return false;
1400 }
1401
1402 Eval->IsEvaluating = true;
1403
1404 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1405 this, Notes);
1406
1407 // Ensure the result is an uninitialized APValue if evaluation fails.
1408 if (!Result)
1409 Eval->Evaluated = APValue();
1410
1411 Eval->IsEvaluating = false;
1412 Eval->WasEvaluated = true;
1413
1414 // In C++11, we have determined whether the initializer was a constant
1415 // expression as a side-effect.
1416 if (getASTContext().getLangOptions().CPlusPlus0x && !Eval->CheckedICE) {
1417 Eval->CheckedICE = true;
1418 Eval->IsICE = Notes.empty();
1419 }
1420
1421 return Result;
1422}
1423
1424bool VarDecl::checkInitIsICE() const {
John McCall73076432012-01-05 00:13:19 +00001425 // Initializers of weak variables are never ICEs.
1426 if (isWeak())
1427 return false;
1428
Richard Smith099e7f62011-12-19 06:19:21 +00001429 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1430 if (Eval->CheckedICE)
1431 // We have already checked whether this subexpression is an
1432 // integral constant expression.
1433 return Eval->IsICE;
1434
1435 const Expr *Init = cast<Expr>(Eval->Value);
1436 assert(!Init->isValueDependent());
1437
1438 // In C++11, evaluate the initializer to check whether it's a constant
1439 // expression.
1440 if (getASTContext().getLangOptions().CPlusPlus0x) {
1441 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1442 evaluateValue(Notes);
1443 return Eval->IsICE;
1444 }
1445
1446 // It's an ICE whether or not the definition we found is
1447 // out-of-line. See DR 721 and the discussion in Clang PR
1448 // 6206 for details.
1449
1450 if (Eval->CheckingICE)
1451 return false;
1452 Eval->CheckingICE = true;
1453
1454 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1455 Eval->CheckingICE = false;
1456 Eval->CheckedICE = true;
1457 return Eval->IsICE;
1458}
1459
Douglas Gregor03e80032011-06-21 17:03:29 +00001460bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregor0b581082011-06-21 18:20:46 +00001461 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregor03e80032011-06-21 17:03:29 +00001462
1463 const Expr *E = getInit();
1464 if (!E)
1465 return false;
1466
1467 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1468 E = Cleanups->getSubExpr();
1469
1470 return isa<MaterializeTemporaryExpr>(E);
1471}
1472
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001473VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001474 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001475 return cast<VarDecl>(MSI->getInstantiatedFrom());
1476
1477 return 0;
1478}
1479
Douglas Gregor663b5a02009-10-14 20:14:33 +00001480TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redle9d12b62010-01-31 22:27:38 +00001481 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001482 return MSI->getTemplateSpecializationKind();
1483
1484 return TSK_Undeclared;
1485}
1486
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001487MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001488 return getASTContext().getInstantiatedFromStaticDataMember(this);
1489}
1490
Douglas Gregor0a897e32009-10-15 17:21:20 +00001491void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1492 SourceLocation PointOfInstantiation) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001493 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001494 assert(MSI && "Not an instantiated static data member?");
1495 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor0a897e32009-10-15 17:21:20 +00001496 if (TSK != TSK_ExplicitSpecialization &&
1497 PointOfInstantiation.isValid() &&
1498 MSI->getPointOfInstantiation().isInvalid())
1499 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001500}
1501
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001502//===----------------------------------------------------------------------===//
1503// ParmVarDecl Implementation
1504//===----------------------------------------------------------------------===//
Douglas Gregor275a3692009-03-10 23:43:53 +00001505
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001506ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001507 SourceLocation StartLoc,
1508 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001509 QualType T, TypeSourceInfo *TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001510 StorageClass S, StorageClass SCAsWritten,
1511 Expr *DefArg) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001512 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001513 S, SCAsWritten, DefArg);
Douglas Gregor275a3692009-03-10 23:43:53 +00001514}
1515
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001516ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1517 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1518 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1519 0, QualType(), 0, SC_None, SC_None, 0);
1520}
1521
Argyrios Kyrtzidis0bfe83b2011-07-30 17:23:26 +00001522SourceRange ParmVarDecl::getSourceRange() const {
1523 if (!hasInheritedDefaultArg()) {
1524 SourceRange ArgRange = getDefaultArgRange();
1525 if (ArgRange.isValid())
1526 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1527 }
1528
1529 return DeclaratorDecl::getSourceRange();
1530}
1531
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001532Expr *ParmVarDecl::getDefaultArg() {
1533 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1534 assert(!hasUninstantiatedDefaultArg() &&
1535 "Default argument is not yet instantiated!");
1536
1537 Expr *Arg = getInit();
John McCall4765fa02010-12-06 08:20:24 +00001538 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001539 return E->getSubExpr();
Douglas Gregor275a3692009-03-10 23:43:53 +00001540
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001541 return Arg;
1542}
1543
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001544SourceRange ParmVarDecl::getDefaultArgRange() const {
1545 if (const Expr *E = getInit())
1546 return E->getSourceRange();
1547
1548 if (hasUninstantiatedDefaultArg())
1549 return getUninstantiatedDefaultArg()->getSourceRange();
1550
1551 return SourceRange();
Argyrios Kyrtzidisfc7e2a82009-07-05 22:21:56 +00001552}
1553
Douglas Gregor1fe85ea2011-01-05 21:11:38 +00001554bool ParmVarDecl::isParameterPack() const {
1555 return isa<PackExpansionType>(getType());
1556}
1557
Ted Kremenekd211cb72011-10-06 05:00:56 +00001558void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1559 getASTContext().setParameterIndex(this, parameterIndex);
1560 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1561}
1562
1563unsigned ParmVarDecl::getParameterIndexLarge() const {
1564 return getASTContext().getParameterIndex(this);
1565}
1566
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001567//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00001568// FunctionDecl Implementation
1569//===----------------------------------------------------------------------===//
1570
Douglas Gregorda2142f2011-02-19 18:51:44 +00001571void FunctionDecl::getNameForDiagnostic(std::string &S,
1572 const PrintingPolicy &Policy,
1573 bool Qualified) const {
1574 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1575 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1576 if (TemplateArgs)
1577 S += TemplateSpecializationType::PrintTemplateArgumentList(
1578 TemplateArgs->data(),
1579 TemplateArgs->size(),
1580 Policy);
1581
1582}
1583
Ted Kremenek9498d382010-04-29 16:49:01 +00001584bool FunctionDecl::isVariadic() const {
1585 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1586 return FT->isVariadic();
1587 return false;
1588}
1589
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001590bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1591 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001592 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001593 Definition = *I;
1594 return true;
1595 }
1596 }
1597
1598 return false;
1599}
1600
Anders Carlssonffb945f2011-05-14 23:26:09 +00001601bool FunctionDecl::hasTrivialBody() const
1602{
1603 Stmt *S = getBody();
1604 if (!S) {
1605 // Since we don't have a body for this function, we don't know if it's
1606 // trivial or not.
1607 return false;
1608 }
1609
1610 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1611 return true;
1612 return false;
1613}
1614
Sean Hunt10620eb2011-05-06 20:44:56 +00001615bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1616 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Sean Huntcd10dec2011-05-23 23:14:04 +00001617 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Sean Hunt10620eb2011-05-06 20:44:56 +00001618 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1619 return true;
1620 }
1621 }
1622
1623 return false;
1624}
1625
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001626Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidisc37929c2009-07-14 03:20:21 +00001627 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1628 if (I->Body) {
1629 Definition = *I;
1630 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet8387e2a2011-04-22 22:18:13 +00001631 } else if (I->IsLateTemplateParsed) {
1632 Definition = *I;
1633 return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +00001634 }
1635 }
1636
1637 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001638}
1639
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001640void FunctionDecl::setBody(Stmt *B) {
1641 Body = B;
Douglas Gregorb5f35ba2010-12-06 17:49:01 +00001642 if (B)
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001643 EndRangeLoc = B->getLocEnd();
1644}
1645
Douglas Gregor21386642010-09-28 21:55:22 +00001646void FunctionDecl::setPure(bool P) {
1647 IsPure = P;
1648 if (P)
1649 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1650 Parent->markedVirtualFunctionPure();
1651}
1652
Douglas Gregor48a83b52009-09-12 00:17:51 +00001653bool FunctionDecl::isMain() const {
John McCall23c608d2011-05-15 17:49:20 +00001654 const TranslationUnitDecl *tunit =
1655 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1656 return tunit &&
Sean Hunt55878032011-05-15 20:59:31 +00001657 !tunit->getASTContext().getLangOptions().Freestanding &&
John McCall23c608d2011-05-15 17:49:20 +00001658 getIdentifier() &&
1659 getIdentifier()->isStr("main");
1660}
1661
1662bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1663 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1664 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1665 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1666 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1667 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1668
1669 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1670 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1671
1672 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1673 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1674
1675 ASTContext &Context =
1676 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1677 ->getASTContext();
1678
1679 // The result type and first argument type are constant across all
1680 // these operators. The second argument must be exactly void*.
1681 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregor04495c82009-02-24 01:23:02 +00001682}
1683
Douglas Gregor48a83b52009-09-12 00:17:51 +00001684bool FunctionDecl::isExternC() const {
1685 ASTContext &Context = getASTContext();
Douglas Gregor63935192009-03-02 00:19:53 +00001686 // In C, any non-static, non-overloadable function has external
1687 // linkage.
1688 if (!Context.getLangOptions().CPlusPlus)
John McCalld931b082010-08-26 03:08:43 +00001689 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>();
Douglas Gregor63935192009-03-02 00:19:53 +00001690
Chandler Carruth10aad442011-02-25 00:05:02 +00001691 const DeclContext *DC = getDeclContext();
1692 if (DC->isRecord())
1693 return false;
1694
1695 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
Douglas Gregor63935192009-03-02 00:19:53 +00001696 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1697 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
John McCalld931b082010-08-26 03:08:43 +00001698 return getStorageClass() != SC_Static &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001699 !getAttr<OverloadableAttr>();
Douglas Gregor63935192009-03-02 00:19:53 +00001700
1701 break;
1702 }
1703 }
1704
Douglas Gregor0bab54c2010-10-21 16:57:46 +00001705 return isMain();
Douglas Gregor63935192009-03-02 00:19:53 +00001706}
1707
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001708bool FunctionDecl::isGlobal() const {
1709 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1710 return Method->isStatic();
1711
John McCalld931b082010-08-26 03:08:43 +00001712 if (getStorageClass() == SC_Static)
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001713 return false;
1714
Mike Stump1eb44332009-09-09 15:08:12 +00001715 for (const DeclContext *DC = getDeclContext();
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001716 DC->isNamespace();
1717 DC = DC->getParent()) {
1718 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1719 if (!Namespace->getDeclName())
1720 return false;
1721 break;
1722 }
1723 }
1724
1725 return true;
1726}
1727
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001728void
1729FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1730 redeclarable_base::setPreviousDeclaration(PrevDecl);
1731
1732 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1733 FunctionTemplateDecl *PrevFunTmpl
1734 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1735 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1736 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1737 }
Douglas Gregor8f150942010-12-09 16:59:22 +00001738
Axel Naumannd9d137e2011-11-08 18:21:06 +00001739 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregor8f150942010-12-09 16:59:22 +00001740 IsInline = true;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001741}
1742
1743const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1744 return getFirstDeclaration();
1745}
1746
1747FunctionDecl *FunctionDecl::getCanonicalDecl() {
1748 return getFirstDeclaration();
1749}
1750
Douglas Gregor381d34e2010-12-06 18:36:25 +00001751void FunctionDecl::setStorageClass(StorageClass SC) {
1752 assert(isLegalForFunction(SC));
1753 if (getStorageClass() != SC)
1754 ClearLinkageCache();
1755
1756 SClass = SC;
1757}
1758
Douglas Gregor3e41d602009-02-13 23:20:09 +00001759/// \brief Returns a value indicating whether this function
1760/// corresponds to a builtin function.
1761///
1762/// The function corresponds to a built-in function if it is
1763/// declared at translation scope or within an extern "C" block and
1764/// its name matches with the name of a builtin. The returned value
1765/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump1eb44332009-09-09 15:08:12 +00001766/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregor3e41d602009-02-13 23:20:09 +00001767/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001768unsigned FunctionDecl::getBuiltinID() const {
1769 ASTContext &Context = getASTContext();
Douglas Gregor3c385e52009-02-14 18:57:46 +00001770 if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1771 return 0;
1772
1773 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1774 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1775 return BuiltinID;
1776
1777 // This function has the name of a known C library
1778 // function. Determine whether it actually refers to the C library
1779 // function or whether it just has the same name.
1780
Douglas Gregor9add3172009-02-17 03:23:10 +00001781 // If this is a static function, it's not a builtin.
John McCalld931b082010-08-26 03:08:43 +00001782 if (getStorageClass() == SC_Static)
Douglas Gregor9add3172009-02-17 03:23:10 +00001783 return 0;
1784
Douglas Gregor3c385e52009-02-14 18:57:46 +00001785 // If this function is at translation-unit scope and we're not in
1786 // C++, it refers to the C library function.
1787 if (!Context.getLangOptions().CPlusPlus &&
1788 getDeclContext()->isTranslationUnit())
1789 return BuiltinID;
1790
1791 // If the function is in an extern "C" linkage specification and is
1792 // not marked "overloadable", it's the real function.
1793 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001794 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregor3c385e52009-02-14 18:57:46 +00001795 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001796 !getAttr<OverloadableAttr>())
Douglas Gregor3c385e52009-02-14 18:57:46 +00001797 return BuiltinID;
1798
1799 // Not a builtin
Douglas Gregor3e41d602009-02-13 23:20:09 +00001800 return 0;
1801}
1802
1803
Chris Lattner1ad9b282009-04-25 06:03:53 +00001804/// getNumParams - Return the number of parameters this function must have
Bob Wilson8dbfbf42011-01-10 18:23:55 +00001805/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner1ad9b282009-04-25 06:03:53 +00001806/// after it has been created.
1807unsigned FunctionDecl::getNumParams() const {
John McCall183700f2009-09-21 23:43:11 +00001808 const FunctionType *FT = getType()->getAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001809 if (isa<FunctionNoProtoType>(FT))
Chris Lattnerd3b90652008-03-15 05:43:15 +00001810 return 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00001811 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Reid Spencer5f016e22007-07-11 17:01:13 +00001813}
1814
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00001815void FunctionDecl::setParams(ASTContext &C,
David Blaikie4278c652011-09-21 18:16:56 +00001816 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie4278c652011-09-21 18:16:56 +00001818 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Reid Spencer5f016e22007-07-11 17:01:13 +00001820 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00001821 if (!NewParamInfo.empty()) {
1822 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1823 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00001824 }
1825}
1826
Chris Lattner8123a952008-04-10 02:22:51 +00001827/// getMinRequiredArguments - Returns the minimum number of arguments
1828/// needed to call this function. This may be fewer than the number of
1829/// function parameters, if some of the parameters have default
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00001830/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner8123a952008-04-10 02:22:51 +00001831unsigned FunctionDecl::getMinRequiredArguments() const {
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00001832 if (!getASTContext().getLangOptions().CPlusPlus)
1833 return getNumParams();
1834
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00001835 unsigned NumRequiredArgs = getNumParams();
1836
1837 // If the last parameter is a parameter pack, we don't need an argument for
1838 // it.
1839 if (NumRequiredArgs > 0 &&
1840 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1841 --NumRequiredArgs;
1842
1843 // If this parameter has a default argument, we don't need an argument for
1844 // it.
1845 while (NumRequiredArgs > 0 &&
1846 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner8123a952008-04-10 02:22:51 +00001847 --NumRequiredArgs;
1848
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00001849 // We might have parameter packs before the end. These can't be deduced,
1850 // but they can still handle multiple arguments.
1851 unsigned ArgIdx = NumRequiredArgs;
1852 while (ArgIdx > 0) {
1853 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1854 NumRequiredArgs = ArgIdx;
1855
1856 --ArgIdx;
1857 }
1858
Chris Lattner8123a952008-04-10 02:22:51 +00001859 return NumRequiredArgs;
1860}
1861
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001862bool FunctionDecl::isInlined() const {
Douglas Gregor8f150942010-12-09 16:59:22 +00001863 if (IsInline)
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001864 return true;
Anders Carlsson48eda2c2009-12-04 22:35:50 +00001865
1866 if (isa<CXXMethodDecl>(this)) {
1867 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1868 return true;
1869 }
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001870
1871 switch (getTemplateSpecializationKind()) {
1872 case TSK_Undeclared:
1873 case TSK_ExplicitSpecialization:
1874 return false;
1875
1876 case TSK_ImplicitInstantiation:
1877 case TSK_ExplicitInstantiationDeclaration:
1878 case TSK_ExplicitInstantiationDefinition:
1879 // Handle below.
1880 break;
1881 }
1882
1883 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001884 bool HasPattern = false;
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001885 if (PatternDecl)
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001886 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001887
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001888 if (HasPattern && PatternDecl)
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001889 return PatternDecl->isInlined();
1890
1891 return false;
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001892}
1893
Nick Lewyckydce67a72011-07-18 05:26:13 +00001894/// \brief For a function declaration in C or C++, determine whether this
1895/// declaration causes the definition to be externally visible.
1896///
1897/// Determines whether this is the first non-inline redeclaration of an inline
1898/// function in a language where "inline" does not normally require an
1899/// externally visible definition.
1900bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1901 assert(!doesThisDeclarationHaveABody() &&
1902 "Must have a declaration without a body.");
1903
1904 ASTContext &Context = getASTContext();
1905
1906 // In C99 mode, a function may have an inline definition (causing it to
1907 // be deferred) then redeclared later. As a special case, "extern inline"
1908 // is not required to produce an external symbol.
1909 if (Context.getLangOptions().GNUInline || !Context.getLangOptions().C99 ||
1910 Context.getLangOptions().CPlusPlus)
1911 return false;
1912 if (getLinkage() != ExternalLinkage || isInlineSpecified())
1913 return false;
Nick Lewyckyf57ef052011-07-18 07:11:55 +00001914 const FunctionDecl *Definition = 0;
1915 if (hasBody(Definition))
1916 return Definition->isInlined() &&
1917 Definition->isInlineDefinitionExternallyVisible();
Nick Lewyckydce67a72011-07-18 05:26:13 +00001918 return false;
1919}
1920
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001921/// \brief For an inline function definition in C or C++, determine whether the
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001922/// definition will be externally visible.
1923///
1924/// Inline function definitions are always available for inlining optimizations.
1925/// However, depending on the language dialect, declaration specifiers, and
1926/// attributes, the definition of an inline function may or may not be
1927/// "externally" visible to other translation units in the program.
1928///
1929/// In C99, inline definitions are not externally visible by default. However,
Mike Stump1e5fd7f2010-01-06 02:05:39 +00001930/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001931/// inline definition becomes externally visible (C99 6.7.4p6).
1932///
1933/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1934/// definition, we use the GNU semantics for inline, which are nearly the
1935/// opposite of C99 semantics. In particular, "inline" by itself will create
1936/// an externally visible symbol, but "extern inline" will not create an
1937/// externally visible symbol.
1938bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Sean Hunt10620eb2011-05-06 20:44:56 +00001939 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001940 assert(isInlined() && "Function must be inline");
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00001941 ASTContext &Context = getASTContext();
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001942
Rafael Espindolafb3f4aa2011-06-02 16:13:27 +00001943 if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
Douglas Gregor8f150942010-12-09 16:59:22 +00001944 // If it's not the case that both 'inline' and 'extern' are
1945 // specified on the definition, then this inline definition is
1946 // externally visible.
1947 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
1948 return true;
1949
1950 // If any declaration is 'inline' but not 'extern', then this definition
1951 // is externally visible.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001952 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1953 Redecl != RedeclEnd;
1954 ++Redecl) {
Douglas Gregor8f150942010-12-09 16:59:22 +00001955 if (Redecl->isInlineSpecified() &&
1956 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001957 return true;
Douglas Gregor8f150942010-12-09 16:59:22 +00001958 }
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001959
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001960 return false;
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001961 }
1962
1963 // C99 6.7.4p6:
1964 // [...] If all of the file scope declarations for a function in a
1965 // translation unit include the inline function specifier without extern,
1966 // then the definition in that translation unit is an inline definition.
1967 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1968 Redecl != RedeclEnd;
1969 ++Redecl) {
1970 // Only consider file-scope declarations in this test.
1971 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1972 continue;
Eli Friedman8a1d6a52011-10-11 22:09:24 +00001973
1974 // Only consider explicit declarations; the presence of a builtin for a
1975 // libcall shouldn't affect whether a definition is externally visible.
1976 if (Redecl->isImplicit())
1977 continue;
1978
John McCalld931b082010-08-26 03:08:43 +00001979 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Douglas Gregor1fc09a92009-09-13 07:46:26 +00001980 return true; // Not an inline definition
1981 }
1982
1983 // C99 6.7.4p6:
1984 // An inline definition does not provide an external definition for the
1985 // function, and does not forbid an external definition in another
1986 // translation unit.
Douglas Gregor9f9bf252009-04-28 06:37:30 +00001987 return false;
1988}
1989
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001990/// getOverloadedOperator - Which C++ overloaded operator this
1991/// function represents, if any.
1992OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001993 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1994 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001995 else
1996 return OO_None;
1997}
1998
Sean Hunta6c058d2010-01-13 09:01:02 +00001999/// getLiteralIdentifier - The literal suffix identifier this function
2000/// represents, if any.
2001const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2002 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2003 return getDeclName().getCXXLiteralIdentifier();
2004 else
2005 return 0;
2006}
2007
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002008FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2009 if (TemplateOrSpecialization.isNull())
2010 return TK_NonTemplate;
2011 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2012 return TK_FunctionTemplate;
2013 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2014 return TK_MemberSpecialization;
2015 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2016 return TK_FunctionTemplateSpecialization;
2017 if (TemplateOrSpecialization.is
2018 <DependentFunctionTemplateSpecializationInfo*>())
2019 return TK_DependentFunctionTemplateSpecialization;
2020
David Blaikieb219cfc2011-09-23 05:06:16 +00002021 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002022}
2023
Douglas Gregor2db32322009-10-07 23:56:10 +00002024FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002025 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregor2db32322009-10-07 23:56:10 +00002026 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2027
2028 return 0;
2029}
2030
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002031MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2032 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2033}
2034
Douglas Gregor2db32322009-10-07 23:56:10 +00002035void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002036FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2037 FunctionDecl *FD,
Douglas Gregor2db32322009-10-07 23:56:10 +00002038 TemplateSpecializationKind TSK) {
2039 assert(TemplateOrSpecialization.isNull() &&
2040 "Member function is already a specialization");
2041 MemberSpecializationInfo *Info
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002042 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregor2db32322009-10-07 23:56:10 +00002043 TemplateOrSpecialization = Info;
2044}
2045
Douglas Gregor3b846b62009-10-27 20:53:28 +00002046bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002047 // If the function is invalid, it can't be implicitly instantiated.
2048 if (isInvalidDecl())
Douglas Gregor3b846b62009-10-27 20:53:28 +00002049 return false;
2050
2051 switch (getTemplateSpecializationKind()) {
2052 case TSK_Undeclared:
Douglas Gregor3b846b62009-10-27 20:53:28 +00002053 case TSK_ExplicitInstantiationDefinition:
2054 return false;
2055
2056 case TSK_ImplicitInstantiation:
2057 return true;
2058
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002059 // It is possible to instantiate TSK_ExplicitSpecialization kind
2060 // if the FunctionDecl has a class scope specialization pattern.
2061 case TSK_ExplicitSpecialization:
2062 return getClassScopeSpecializationPattern() != 0;
2063
Douglas Gregor3b846b62009-10-27 20:53:28 +00002064 case TSK_ExplicitInstantiationDeclaration:
2065 // Handled below.
2066 break;
2067 }
2068
2069 // Find the actual template from which we will instantiate.
2070 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002071 bool HasPattern = false;
Douglas Gregor3b846b62009-10-27 20:53:28 +00002072 if (PatternDecl)
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002073 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregor3b846b62009-10-27 20:53:28 +00002074
2075 // C++0x [temp.explicit]p9:
2076 // Except for inline functions, other explicit instantiation declarations
2077 // have the effect of suppressing the implicit instantiation of the entity
2078 // to which they refer.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002079 if (!HasPattern || !PatternDecl)
Douglas Gregor3b846b62009-10-27 20:53:28 +00002080 return true;
2081
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002082 return PatternDecl->isInlined();
Ted Kremenek75df4ee2011-12-01 00:59:17 +00002083}
2084
2085bool FunctionDecl::isTemplateInstantiation() const {
2086 switch (getTemplateSpecializationKind()) {
2087 case TSK_Undeclared:
2088 case TSK_ExplicitSpecialization:
2089 return false;
2090 case TSK_ImplicitInstantiation:
2091 case TSK_ExplicitInstantiationDeclaration:
2092 case TSK_ExplicitInstantiationDefinition:
2093 return true;
2094 }
2095 llvm_unreachable("All TSK values handled.");
2096}
Douglas Gregor3b846b62009-10-27 20:53:28 +00002097
2098FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002099 // Handle class scope explicit specialization special case.
2100 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2101 return getClassScopeSpecializationPattern();
2102
Douglas Gregor3b846b62009-10-27 20:53:28 +00002103 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2104 while (Primary->getInstantiatedFromMemberTemplate()) {
2105 // If we have hit a point where the user provided a specialization of
2106 // this template, we're done looking.
2107 if (Primary->isMemberSpecialization())
2108 break;
2109
2110 Primary = Primary->getInstantiatedFromMemberTemplate();
2111 }
2112
2113 return Primary->getTemplatedDecl();
2114 }
2115
2116 return getInstantiatedFromMemberFunction();
2117}
2118
Douglas Gregor16e8be22009-06-29 17:30:29 +00002119FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002120 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00002121 = TemplateOrSpecialization
2122 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002123 return Info->Template.getPointer();
Douglas Gregor16e8be22009-06-29 17:30:29 +00002124 }
2125 return 0;
2126}
2127
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002128FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2129 return getASTContext().getClassScopeSpecializationPattern(this);
2130}
2131
Douglas Gregor16e8be22009-06-29 17:30:29 +00002132const TemplateArgumentList *
2133FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002134 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002135 = TemplateOrSpecialization
2136 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor16e8be22009-06-29 17:30:29 +00002137 return Info->TemplateArguments;
2138 }
2139 return 0;
2140}
2141
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00002142const ASTTemplateArgumentListInfo *
Abramo Bagnarae03db982010-05-20 15:32:11 +00002143FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2144 if (FunctionTemplateSpecializationInfo *Info
2145 = TemplateOrSpecialization
2146 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2147 return Info->TemplateArgumentsAsWritten;
2148 }
2149 return 0;
2150}
2151
Mike Stump1eb44332009-09-09 15:08:12 +00002152void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002153FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2154 FunctionTemplateDecl *Template,
Douglas Gregor127102b2009-06-29 20:59:39 +00002155 const TemplateArgumentList *TemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002156 void *InsertPos,
Abramo Bagnarae03db982010-05-20 15:32:11 +00002157 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis7b081c82010-07-05 10:37:55 +00002158 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2159 SourceLocation PointOfInstantiation) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002160 assert(TSK != TSK_Undeclared &&
2161 "Must specify the type of function template specialization");
Mike Stump1eb44332009-09-09 15:08:12 +00002162 FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00002163 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor1637be72009-06-26 00:10:03 +00002164 if (!Info)
Argyrios Kyrtzidisa626a3d2010-09-09 11:28:23 +00002165 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2166 TemplateArgs,
2167 TemplateArgsAsWritten,
2168 PointOfInstantiation);
Douglas Gregor1637be72009-06-26 00:10:03 +00002169 TemplateOrSpecialization = Info;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Douglas Gregor127102b2009-06-29 20:59:39 +00002171 // Insert this function template specialization into the set of known
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002172 // function template specializations.
2173 if (InsertPos)
Sebastian Redl5bbcdbf2011-04-14 14:07:59 +00002174 Template->addSpecialization(Info, InsertPos);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002175 else {
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00002176 // Try to insert the new node. If there is an existing node, leave it, the
2177 // set will contain the canonical decls while
2178 // FunctionTemplateDecl::findSpecialization will return
2179 // the most recent redeclarations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002180 FunctionTemplateSpecializationInfo *Existing
2181 = Template->getSpecializations().GetOrInsertNode(Info);
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00002182 (void)Existing;
2183 assert((!Existing || Existing->Function->isCanonicalDecl()) &&
2184 "Set is supposed to only contain canonical decls");
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002185 }
Douglas Gregor1637be72009-06-26 00:10:03 +00002186}
2187
John McCallaf2094e2010-04-08 09:05:18 +00002188void
2189FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2190 const UnresolvedSetImpl &Templates,
2191 const TemplateArgumentListInfo &TemplateArgs) {
2192 assert(TemplateOrSpecialization.isNull());
2193 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2194 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall21c01602010-04-13 22:18:28 +00002195 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallaf2094e2010-04-08 09:05:18 +00002196 void *Buffer = Context.Allocate(Size);
2197 DependentFunctionTemplateSpecializationInfo *Info =
2198 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2199 TemplateArgs);
2200 TemplateOrSpecialization = Info;
2201}
2202
2203DependentFunctionTemplateSpecializationInfo::
2204DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2205 const TemplateArgumentListInfo &TArgs)
2206 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2207
2208 d.NumTemplates = Ts.size();
2209 d.NumArgs = TArgs.size();
2210
2211 FunctionTemplateDecl **TsArray =
2212 const_cast<FunctionTemplateDecl**>(getTemplates());
2213 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2214 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2215
2216 TemplateArgumentLoc *ArgsArray =
2217 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2218 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2219 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2220}
2221
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002222TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002223 // For a function template specialization, query the specialization
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002224 // information object.
Douglas Gregor2db32322009-10-07 23:56:10 +00002225 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002226 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor2db32322009-10-07 23:56:10 +00002227 if (FTSInfo)
2228 return FTSInfo->getTemplateSpecializationKind();
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Douglas Gregor2db32322009-10-07 23:56:10 +00002230 MemberSpecializationInfo *MSInfo
2231 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2232 if (MSInfo)
2233 return MSInfo->getTemplateSpecializationKind();
2234
2235 return TSK_Undeclared;
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002236}
2237
Mike Stump1eb44332009-09-09 15:08:12 +00002238void
Douglas Gregor0a897e32009-10-15 17:21:20 +00002239FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2240 SourceLocation PointOfInstantiation) {
2241 if (FunctionTemplateSpecializationInfo *FTSInfo
2242 = TemplateOrSpecialization.dyn_cast<
2243 FunctionTemplateSpecializationInfo*>()) {
2244 FTSInfo->setTemplateSpecializationKind(TSK);
2245 if (TSK != TSK_ExplicitSpecialization &&
2246 PointOfInstantiation.isValid() &&
2247 FTSInfo->getPointOfInstantiation().isInvalid())
2248 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2249 } else if (MemberSpecializationInfo *MSInfo
2250 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2251 MSInfo->setTemplateSpecializationKind(TSK);
2252 if (TSK != TSK_ExplicitSpecialization &&
2253 PointOfInstantiation.isValid() &&
2254 MSInfo->getPointOfInstantiation().isInvalid())
2255 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2256 } else
David Blaikieb219cfc2011-09-23 05:06:16 +00002257 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor0a897e32009-10-15 17:21:20 +00002258}
2259
2260SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregor2db32322009-10-07 23:56:10 +00002261 if (FunctionTemplateSpecializationInfo *FTSInfo
2262 = TemplateOrSpecialization.dyn_cast<
2263 FunctionTemplateSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00002264 return FTSInfo->getPointOfInstantiation();
Douglas Gregor2db32322009-10-07 23:56:10 +00002265 else if (MemberSpecializationInfo *MSInfo
2266 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00002267 return MSInfo->getPointOfInstantiation();
2268
2269 return SourceLocation();
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002270}
2271
Douglas Gregor9f185072009-09-11 20:15:17 +00002272bool FunctionDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00002273 if (Decl::isOutOfLine())
Douglas Gregor9f185072009-09-11 20:15:17 +00002274 return true;
2275
2276 // If this function was instantiated from a member function of a
2277 // class template, check whether that member function was defined out-of-line.
2278 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2279 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002280 if (FD->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00002281 return Definition->isOutOfLine();
2282 }
2283
2284 // If this function was instantiated from a function template,
2285 // check whether that function template was defined out-of-line.
2286 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2287 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002288 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00002289 return Definition->isOutOfLine();
2290 }
2291
2292 return false;
2293}
2294
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002295SourceRange FunctionDecl::getSourceRange() const {
2296 return SourceRange(getOuterLocStart(), EndRangeLoc);
2297}
2298
Anna Zaksd9b859a2012-01-13 21:52:01 +00002299FunctionDecl::MemoryFunctionKind FunctionDecl::getMemoryFunctionKind() {
2300 IdentifierInfo *FnInfo = getIdentifier();
2301
2302 if (!FnInfo)
2303 return MFK_Invalid;
2304
2305 // Builtin handling.
2306 switch (getBuiltinID()) {
2307 case Builtin::BI__builtin_memset:
2308 case Builtin::BI__builtin___memset_chk:
2309 case Builtin::BImemset:
2310 return MFK_Memset;
2311
2312 case Builtin::BI__builtin_memcpy:
2313 case Builtin::BI__builtin___memcpy_chk:
2314 case Builtin::BImemcpy:
2315 return MFK_Memcpy;
2316
2317 case Builtin::BI__builtin_memmove:
2318 case Builtin::BI__builtin___memmove_chk:
2319 case Builtin::BImemmove:
2320 return MFK_Memmove;
2321
2322 case Builtin::BIstrlcpy:
2323 return MFK_Strlcpy;
2324 case Builtin::BIstrlcat:
2325 return MFK_Strlcat;
2326
2327 case Builtin::BI__builtin_memcmp:
2328 return MFK_Memcmp;
2329
2330 case Builtin::BI__builtin_strncpy:
2331 case Builtin::BI__builtin___strncpy_chk:
2332 case Builtin::BIstrncpy:
2333 return MFK_Strncpy;
2334
2335 case Builtin::BI__builtin_strncmp:
2336 return MFK_Strncmp;
2337
2338 case Builtin::BI__builtin_strncasecmp:
2339 return MFK_Strncasecmp;
2340
2341 case Builtin::BI__builtin_strncat:
2342 case Builtin::BIstrncat:
2343 return MFK_Strncat;
2344
2345 case Builtin::BI__builtin_strndup:
2346 case Builtin::BIstrndup:
2347 return MFK_Strndup;
2348
2349 default:
2350 if (getLinkage() == ExternalLinkage &&
2351 (!getASTContext().getLangOptions().CPlusPlus || isExternC())) {
2352 if (FnInfo->isStr("memset"))
2353 return MFK_Memset;
2354 else if (FnInfo->isStr("memcpy"))
2355 return MFK_Memcpy;
2356 else if (FnInfo->isStr("memmove"))
2357 return MFK_Memmove;
2358 else if (FnInfo->isStr("memcmp"))
2359 return MFK_Memcmp;
2360 else if (FnInfo->isStr("strncpy"))
2361 return MFK_Strncpy;
2362 else if (FnInfo->isStr("strncmp"))
2363 return MFK_Strncmp;
2364 else if (FnInfo->isStr("strncasecmp"))
2365 return MFK_Strncasecmp;
2366 else if (FnInfo->isStr("strncat"))
2367 return MFK_Strncat;
2368 else if (FnInfo->isStr("strndup"))
2369 return MFK_Strndup;
2370 }
2371 break;
2372 }
2373 return MFK_Invalid;
2374}
2375
Chris Lattner8a934232008-03-31 00:36:02 +00002376//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002377// FieldDecl Implementation
2378//===----------------------------------------------------------------------===//
2379
Jay Foad4ba2a172011-01-12 09:06:06 +00002380FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002381 SourceLocation StartLoc, SourceLocation IdLoc,
2382 IdentifierInfo *Id, QualType T,
Richard Smith7a614d82011-06-11 17:19:42 +00002383 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2384 bool HasInit) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002385 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith7a614d82011-06-11 17:19:42 +00002386 BW, Mutable, HasInit);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002387}
2388
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002389FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2390 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2391 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2392 0, QualType(), 0, 0, false, false);
2393}
2394
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002395bool FieldDecl::isAnonymousStructOrUnion() const {
2396 if (!isImplicit() || getDeclName())
2397 return false;
2398
2399 if (const RecordType *Record = getType()->getAs<RecordType>())
2400 return Record->getDecl()->isAnonymousStructOrUnion();
2401
2402 return false;
2403}
2404
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002405unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2406 assert(isBitField() && "not a bitfield");
2407 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2408 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2409}
2410
John McCallba4f5d52011-01-20 07:57:12 +00002411unsigned FieldDecl::getFieldIndex() const {
2412 if (CachedFieldIndex) return CachedFieldIndex - 1;
2413
Richard Smith180f4792011-11-10 06:34:14 +00002414 unsigned Index = 0;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002415 const RecordDecl *RD = getParent();
2416 const FieldDecl *LastFD = 0;
2417 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
Richard Smith180f4792011-11-10 06:34:14 +00002418
2419 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2420 I != E; ++I, ++Index) {
2421 (*I)->CachedFieldIndex = Index + 1;
John McCallba4f5d52011-01-20 07:57:12 +00002422
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002423 if (IsMsStruct) {
2424 // Zero-length bitfields following non-bitfield members are ignored.
Richard Smith180f4792011-11-10 06:34:14 +00002425 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
2426 --Index;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002427 continue;
2428 }
Richard Smith180f4792011-11-10 06:34:14 +00002429 LastFD = (*I);
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002430 }
John McCallba4f5d52011-01-20 07:57:12 +00002431 }
2432
Richard Smith180f4792011-11-10 06:34:14 +00002433 assert(CachedFieldIndex && "failed to find field in parent");
2434 return CachedFieldIndex - 1;
John McCallba4f5d52011-01-20 07:57:12 +00002435}
2436
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00002437SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnarad330e232011-08-05 08:02:55 +00002438 if (const Expr *E = InitializerOrBitWidth.getPointer())
2439 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002440 return DeclaratorDecl::getSourceRange();
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00002441}
2442
Richard Smith7a614d82011-06-11 17:19:42 +00002443void FieldDecl::setInClassInitializer(Expr *Init) {
2444 assert(!InitializerOrBitWidth.getPointer() &&
2445 "bit width or initializer already set");
2446 InitializerOrBitWidth.setPointer(Init);
2447 InitializerOrBitWidth.setInt(0);
2448}
2449
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002450//===----------------------------------------------------------------------===//
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002451// TagDecl Implementation
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002452//===----------------------------------------------------------------------===//
2453
Douglas Gregor1693e152010-07-06 18:42:40 +00002454SourceLocation TagDecl::getOuterLocStart() const {
2455 return getTemplateOrInnerLocStart(this);
2456}
2457
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00002458SourceRange TagDecl::getSourceRange() const {
2459 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregor1693e152010-07-06 18:42:40 +00002460 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00002461}
2462
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00002463TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002464 return getFirstDeclaration();
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00002465}
2466
Richard Smith162e1c12011-04-15 14:24:37 +00002467void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2468 TypedefNameDeclOrQualifier = TDD;
Douglas Gregor60e70642010-05-19 18:39:18 +00002469 if (TypeForDecl)
John McCallf4c73712011-01-19 06:33:43 +00002470 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
Douglas Gregor381d34e2010-12-06 18:36:25 +00002471 ClearLinkageCache();
Douglas Gregor60e70642010-05-19 18:39:18 +00002472}
2473
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002474void TagDecl::startDefinition() {
Sebastian Redled48a8f2010-08-02 18:27:05 +00002475 IsBeingDefined = true;
John McCall86ff3082010-02-04 22:26:26 +00002476
2477 if (isa<CXXRecordDecl>(this)) {
2478 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2479 struct CXXRecordDecl::DefinitionData *Data =
2480 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall22432882010-03-26 21:56:38 +00002481 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2482 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall86ff3082010-02-04 22:26:26 +00002483 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002484}
2485
2486void TagDecl::completeDefinition() {
John McCall5cfa0112010-02-05 01:33:36 +00002487 assert((!isa<CXXRecordDecl>(this) ||
2488 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2489 "definition completed but not started");
2490
John McCall5e1cdac2011-10-07 06:10:15 +00002491 IsCompleteDefinition = true;
Sebastian Redled48a8f2010-08-02 18:27:05 +00002492 IsBeingDefined = false;
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00002493
2494 if (ASTMutationListener *L = getASTMutationListener())
2495 L->CompletedTagDefinition(this);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002496}
2497
John McCall5e1cdac2011-10-07 06:10:15 +00002498TagDecl *TagDecl::getDefinition() const {
2499 if (isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002500 return const_cast<TagDecl *>(this);
Andrew Trick220a9c82010-10-19 21:54:32 +00002501 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2502 return CXXRD->getDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002503
2504 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002505 R != REnd; ++R)
John McCall5e1cdac2011-10-07 06:10:15 +00002506 if (R->isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002507 return *R;
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002509 return 0;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002510}
2511
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002512void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2513 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00002514 // Make sure the extended qualifier info is allocated.
2515 if (!hasExtInfo())
Richard Smith162e1c12011-04-15 14:24:37 +00002516 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCallb6217662010-03-15 10:12:16 +00002517 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002518 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00002519 } else {
John McCallb6217662010-03-15 10:12:16 +00002520 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00002521 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002522 if (getExtInfo()->NumTemplParamLists == 0) {
2523 getASTContext().Deallocate(getExtInfo());
Richard Smith162e1c12011-04-15 14:24:37 +00002524 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002525 }
2526 else
2527 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00002528 }
2529 }
2530}
2531
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002532void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2533 unsigned NumTPLists,
2534 TemplateParameterList **TPLists) {
2535 assert(NumTPLists > 0);
2536 // Make sure the extended decl info is allocated.
2537 if (!hasExtInfo())
2538 // Allocate external info struct.
Richard Smith162e1c12011-04-15 14:24:37 +00002539 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002540 // Set the template parameter lists info.
2541 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2542}
2543
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002544//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002545// EnumDecl Implementation
2546//===----------------------------------------------------------------------===//
2547
David Blaikie99ba9e32011-12-20 02:48:34 +00002548void EnumDecl::anchor() { }
2549
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002550EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2551 SourceLocation StartLoc, SourceLocation IdLoc,
2552 IdentifierInfo *Id,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00002553 EnumDecl *PrevDecl, bool IsScoped,
2554 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002555 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00002556 IsScoped, IsScopedUsingClassTag, IsFixed);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002557 C.getTypeDeclType(Enum, PrevDecl);
2558 return Enum;
2559}
2560
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002561EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2562 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2563 return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2564 false, false, false);
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00002565}
2566
Douglas Gregor838db382010-02-11 01:19:42 +00002567void EnumDecl::completeDefinition(QualType NewType,
John McCall1b5a6182010-05-06 08:49:23 +00002568 QualType NewPromotionType,
2569 unsigned NumPositiveBits,
2570 unsigned NumNegativeBits) {
John McCall5e1cdac2011-10-07 06:10:15 +00002571 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor1274ccd2010-10-08 23:50:27 +00002572 if (!IntegerType)
2573 IntegerType = NewType.getTypePtr();
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002574 PromotionType = NewPromotionType;
John McCall1b5a6182010-05-06 08:49:23 +00002575 setNumPositiveBits(NumPositiveBits);
2576 setNumNegativeBits(NumNegativeBits);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002577 TagDecl::completeDefinition();
2578}
2579
2580//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00002581// RecordDecl Implementation
2582//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00002583
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002584RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2585 SourceLocation StartLoc, SourceLocation IdLoc,
2586 IdentifierInfo *Id, RecordDecl *PrevDecl)
2587 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek63597922008-09-02 21:12:32 +00002588 HasFlexibleArrayMember = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002589 AnonymousStructOrUnion = false;
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002590 HasObjectMember = false;
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002591 LoadedFieldsFromExternalStorage = false;
Ted Kremenek63597922008-09-02 21:12:32 +00002592 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek63597922008-09-02 21:12:32 +00002593}
2594
Jay Foad4ba2a172011-01-12 09:06:06 +00002595RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002596 SourceLocation StartLoc, SourceLocation IdLoc,
2597 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2598 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2599 PrevDecl);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002600 C.getTypeDeclType(R, PrevDecl);
2601 return R;
Ted Kremenek63597922008-09-02 21:12:32 +00002602}
2603
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002604RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2605 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
2606 return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2607 SourceLocation(), 0, 0);
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00002608}
2609
Douglas Gregorc9b5b402009-03-25 15:59:44 +00002610bool RecordDecl::isInjectedClassName() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002611 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregorc9b5b402009-03-25 15:59:44 +00002612 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2613}
2614
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002615RecordDecl::field_iterator RecordDecl::field_begin() const {
2616 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2617 LoadFieldsFromExternalStorage();
2618
2619 return field_iterator(decl_iterator(FirstDecl));
2620}
2621
Douglas Gregorda2142f2011-02-19 18:51:44 +00002622/// completeDefinition - Notes that the definition of this type is now
2623/// complete.
2624void RecordDecl::completeDefinition() {
John McCall5e1cdac2011-10-07 06:10:15 +00002625 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorda2142f2011-02-19 18:51:44 +00002626 TagDecl::completeDefinition();
2627}
2628
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002629void RecordDecl::LoadFieldsFromExternalStorage() const {
2630 ExternalASTSource *Source = getASTContext().getExternalSource();
2631 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2632
2633 // Notify that we have a RecordDecl doing some initialization.
2634 ExternalASTSource::Deserializing TheFields(Source);
2635
Chris Lattner5f9e2722011-07-23 10:55:15 +00002636 SmallVector<Decl*, 64> Decls;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00002637 LoadedFieldsFromExternalStorage = true;
2638 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2639 case ELR_Success:
2640 break;
2641
2642 case ELR_AlreadyLoaded:
2643 case ELR_Failure:
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002644 return;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00002645 }
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002646
2647#ifndef NDEBUG
2648 // Check that all decls we got were FieldDecls.
2649 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2650 assert(isa<FieldDecl>(Decls[i]));
2651#endif
2652
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002653 if (Decls.empty())
2654 return;
2655
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +00002656 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2657 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002658}
2659
Steve Naroff56ee6892008-10-08 17:01:13 +00002660//===----------------------------------------------------------------------===//
2661// BlockDecl Implementation
2662//===----------------------------------------------------------------------===//
2663
David Blaikie4278c652011-09-21 18:16:56 +00002664void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffe78b8092009-03-13 16:56:44 +00002665 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump1eb44332009-09-09 15:08:12 +00002666
Steve Naroffe78b8092009-03-13 16:56:44 +00002667 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00002668 if (!NewParamInfo.empty()) {
2669 NumParams = NewParamInfo.size();
2670 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2671 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffe78b8092009-03-13 16:56:44 +00002672 }
2673}
2674
John McCall6b5a61b2011-02-07 10:33:21 +00002675void BlockDecl::setCaptures(ASTContext &Context,
2676 const Capture *begin,
2677 const Capture *end,
2678 bool capturesCXXThis) {
John McCall469a1eb2011-02-02 13:00:07 +00002679 CapturesCXXThis = capturesCXXThis;
2680
2681 if (begin == end) {
John McCall6b5a61b2011-02-07 10:33:21 +00002682 NumCaptures = 0;
2683 Captures = 0;
John McCall469a1eb2011-02-02 13:00:07 +00002684 return;
2685 }
2686
John McCall6b5a61b2011-02-07 10:33:21 +00002687 NumCaptures = end - begin;
2688
2689 // Avoid new Capture[] because we don't want to provide a default
2690 // constructor.
2691 size_t allocationSize = NumCaptures * sizeof(Capture);
2692 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2693 memcpy(buffer, begin, allocationSize);
2694 Captures = static_cast<Capture*>(buffer);
Steve Naroffe78b8092009-03-13 16:56:44 +00002695}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002696
John McCall204e1332011-06-15 22:51:16 +00002697bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2698 for (capture_const_iterator
2699 i = capture_begin(), e = capture_end(); i != e; ++i)
2700 // Only auto vars can be captured, so no redeclaration worries.
2701 if (i->getVariable() == variable)
2702 return true;
2703
2704 return false;
2705}
2706
Douglas Gregor2fcbcef2010-12-21 16:27:07 +00002707SourceRange BlockDecl::getSourceRange() const {
2708 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2709}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002710
2711//===----------------------------------------------------------------------===//
2712// Other Decl Allocation/Deallocation Method Implementations
2713//===----------------------------------------------------------------------===//
2714
David Blaikie99ba9e32011-12-20 02:48:34 +00002715void TranslationUnitDecl::anchor() { }
2716
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002717TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2718 return new (C) TranslationUnitDecl(C);
2719}
2720
David Blaikie99ba9e32011-12-20 02:48:34 +00002721void LabelDecl::anchor() { }
2722
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002723LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara67843042011-03-05 18:21:20 +00002724 SourceLocation IdentL, IdentifierInfo *II) {
2725 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2726}
2727
2728LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2729 SourceLocation IdentL, IdentifierInfo *II,
2730 SourceLocation GnuLabelL) {
2731 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2732 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerad8dcf42011-02-17 07:39:24 +00002733}
2734
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002735LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2736 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
2737 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor06c91932010-10-27 19:49:05 +00002738}
2739
David Blaikie99ba9e32011-12-20 02:48:34 +00002740void ValueDecl::anchor() { }
2741
2742void ImplicitParamDecl::anchor() { }
2743
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002744ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002745 SourceLocation IdLoc,
2746 IdentifierInfo *Id,
2747 QualType Type) {
2748 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002749}
2750
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002751ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
2752 unsigned ID) {
2753 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
2754 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
2755}
2756
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002757FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002758 SourceLocation StartLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00002759 const DeclarationNameInfo &NameInfo,
2760 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002761 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregor8f150942010-12-09 16:59:22 +00002762 bool isInlineSpecified,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00002763 bool hasWrittenPrototype,
2764 bool isConstexprSpecified) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002765 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2766 T, TInfo, SC, SCAsWritten,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00002767 isInlineSpecified,
2768 isConstexprSpecified);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002769 New->HasWrittenPrototype = hasWrittenPrototype;
2770 return New;
2771}
2772
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002773FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2774 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
2775 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
2776 DeclarationNameInfo(), QualType(), 0,
2777 SC_None, SC_None, false, false);
2778}
2779
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002780BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2781 return new (C) BlockDecl(DC, L);
2782}
2783
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002784BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2785 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
2786 return new (Mem) BlockDecl(0, SourceLocation());
2787}
2788
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002789EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2790 SourceLocation L,
2791 IdentifierInfo *Id, QualType T,
2792 Expr *E, const llvm::APSInt &V) {
2793 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2794}
2795
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002796EnumConstantDecl *
2797EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2798 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
2799 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
2800 llvm::APSInt());
2801}
2802
David Blaikie99ba9e32011-12-20 02:48:34 +00002803void IndirectFieldDecl::anchor() { }
2804
Benjamin Kramerd9811462010-11-21 14:11:41 +00002805IndirectFieldDecl *
2806IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2807 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2808 unsigned CHS) {
Francois Pichet87c2e122010-11-21 06:08:52 +00002809 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2810}
2811
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002812IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
2813 unsigned ID) {
2814 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
2815 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
2816 QualType(), 0, 0);
2817}
2818
Douglas Gregor8e7139c2010-09-01 20:41:53 +00002819SourceRange EnumConstantDecl::getSourceRange() const {
2820 SourceLocation End = getLocation();
2821 if (Init)
2822 End = Init->getLocEnd();
2823 return SourceRange(getLocation(), End);
2824}
2825
David Blaikie99ba9e32011-12-20 02:48:34 +00002826void TypeDecl::anchor() { }
2827
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002828TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara344577e2011-03-06 15:48:19 +00002829 SourceLocation StartLoc, SourceLocation IdLoc,
2830 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2831 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002832}
2833
David Blaikie99ba9e32011-12-20 02:48:34 +00002834void TypedefNameDecl::anchor() { }
2835
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002836TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2837 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
2838 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2839}
2840
Richard Smith162e1c12011-04-15 14:24:37 +00002841TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2842 SourceLocation StartLoc,
2843 SourceLocation IdLoc, IdentifierInfo *Id,
2844 TypeSourceInfo *TInfo) {
2845 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2846}
2847
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002848TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2849 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
2850 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2851}
2852
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002853SourceRange TypedefDecl::getSourceRange() const {
2854 SourceLocation RangeEnd = getLocation();
2855 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2856 if (typeIsPostfix(TInfo->getType()))
2857 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2858 }
2859 return SourceRange(getLocStart(), RangeEnd);
2860}
2861
Richard Smith162e1c12011-04-15 14:24:37 +00002862SourceRange TypeAliasDecl::getSourceRange() const {
2863 SourceLocation RangeEnd = getLocStart();
2864 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2865 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2866 return SourceRange(getLocStart(), RangeEnd);
2867}
2868
David Blaikie99ba9e32011-12-20 02:48:34 +00002869void FileScopeAsmDecl::anchor() { }
2870
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002871FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara21e006e2011-03-03 14:20:18 +00002872 StringLiteral *Str,
2873 SourceLocation AsmLoc,
2874 SourceLocation RParenLoc) {
2875 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002876}
Douglas Gregor15de72c2011-12-02 23:23:56 +00002877
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002878FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
2879 unsigned ID) {
2880 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
2881 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
2882}
2883
Douglas Gregor15de72c2011-12-02 23:23:56 +00002884//===----------------------------------------------------------------------===//
2885// ImportDecl Implementation
2886//===----------------------------------------------------------------------===//
2887
2888/// \brief Retrieve the number of module identifiers needed to name the given
2889/// module.
2890static unsigned getNumModuleIdentifiers(Module *Mod) {
2891 unsigned Result = 1;
2892 while (Mod->Parent) {
2893 Mod = Mod->Parent;
2894 ++Result;
2895 }
2896 return Result;
2897}
2898
Douglas Gregor5948ae12012-01-03 18:04:46 +00002899ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00002900 Module *Imported,
2901 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor5948ae12012-01-03 18:04:46 +00002902 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregore6649772011-12-03 00:30:27 +00002903 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00002904{
2905 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
2906 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
2907 memcpy(StoredLocs, IdentifierLocs.data(),
2908 IdentifierLocs.size() * sizeof(SourceLocation));
2909}
2910
Douglas Gregor5948ae12012-01-03 18:04:46 +00002911ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00002912 Module *Imported, SourceLocation EndLoc)
Douglas Gregor5948ae12012-01-03 18:04:46 +00002913 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregore6649772011-12-03 00:30:27 +00002914 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00002915{
2916 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
2917}
2918
2919ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00002920 SourceLocation StartLoc, Module *Imported,
Douglas Gregor15de72c2011-12-02 23:23:56 +00002921 ArrayRef<SourceLocation> IdentifierLocs) {
2922 void *Mem = C.Allocate(sizeof(ImportDecl) +
2923 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor5948ae12012-01-03 18:04:46 +00002924 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +00002925}
2926
2927ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00002928 SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00002929 Module *Imported,
2930 SourceLocation EndLoc) {
2931 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor5948ae12012-01-03 18:04:46 +00002932 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregor15de72c2011-12-02 23:23:56 +00002933 Import->setImplicit();
2934 return Import;
2935}
2936
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002937ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
2938 unsigned NumLocations) {
2939 void *Mem = AllocateDeserializedDecl(C, ID,
2940 (sizeof(ImportDecl) +
2941 NumLocations * sizeof(SourceLocation)));
Douglas Gregor15de72c2011-12-02 23:23:56 +00002942 return new (Mem) ImportDecl(EmptyShell());
2943}
2944
2945ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
2946 if (!ImportedAndComplete.getInt())
2947 return ArrayRef<SourceLocation>();
2948
2949 const SourceLocation *StoredLocs
2950 = reinterpret_cast<const SourceLocation *>(this + 1);
2951 return ArrayRef<SourceLocation>(StoredLocs,
2952 getNumModuleIdentifiers(getImportedModule()));
2953}
2954
2955SourceRange ImportDecl::getSourceRange() const {
2956 if (!ImportedAndComplete.getInt())
2957 return SourceRange(getLocation(),
2958 *reinterpret_cast<const SourceLocation *>(this + 1));
2959
2960 return SourceRange(getLocation(), getIdentifierLocs().back());
2961}