blob: 305c41c51c46ba932ba2a75de126f2baca7b1969 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Douglas Gregor889ceb72009-02-03 19:21:40 +000015#include "clang/AST/DeclCXX.h"
Steve Naroffc4173fa2009-02-22 19:35:57 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregore362cea2009-05-10 22:57:19 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000018#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Stmt.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +000024#include "clang/AST/ASTMutationListener.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000026#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000027#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000028#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000029#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000030#include "llvm/Support/ErrorHandling.h"
Ted Kremenekce20e8f2008-05-20 00:43:19 +000031
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Chris Lattner88f70d62008-03-15 05:43:15 +000036//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000037// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000038//===----------------------------------------------------------------------===//
39
Douglas Gregor1baf38f2011-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 McCall659a3372010-12-18 03:30:47 +000051
John McCall457a04e2010-10-22 21:05:15 +000052 return DefaultVisibility;
John McCall457a04e2010-10-22 21:05:15 +000053 }
Douglas Gregor1baf38f2011-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 Gregore8bbc122011-09-02 00:18:52 +000057 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-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 McCall457a04e2010-10-22 21:05:15 +000067}
68
John McCallc273f242010-10-30 11:50:40 +000069typedef NamedDecl::LinkageInfo LinkageInfo;
John McCall457a04e2010-10-22 21:05:15 +000070typedef std::pair<Linkage,Visibility> LVPair;
John McCallc273f242010-10-30 11:50:40 +000071
John McCall457a04e2010-10-22 21:05:15 +000072static LVPair merge(LVPair L, LVPair R) {
73 return LVPair(minLinkage(L.first, R.first),
74 minVisibility(L.second, R.second));
75}
76
John McCallc273f242010-10-30 11:50:40 +000077static LVPair merge(LVPair L, LinkageInfo R) {
78 return LVPair(minLinkage(L.first, R.linkage()),
79 minVisibility(L.second, R.visibility()));
80}
81
Benjamin Kramer396dcf32010-11-05 19:56:37 +000082namespace {
John McCall07072662010-11-02 01:45:15 +000083/// Flags controlling the computation of linkage and visibility.
84struct LVFlags {
85 bool ConsiderGlobalVisibility;
86 bool ConsiderVisibilityAttributes;
John McCall8bc6d5b2011-03-04 10:39:25 +000087 bool ConsiderTemplateParameterTypes;
John McCall07072662010-11-02 01:45:15 +000088
89 LVFlags() : ConsiderGlobalVisibility(true),
John McCall8bc6d5b2011-03-04 10:39:25 +000090 ConsiderVisibilityAttributes(true),
91 ConsiderTemplateParameterTypes(true) {
John McCall07072662010-11-02 01:45:15 +000092 }
93
Douglas Gregorbf62d642010-12-06 18:36:25 +000094 /// \brief Returns a set of flags that is only useful for computing the
95 /// linkage, not the visibility, of a declaration.
96 static LVFlags CreateOnlyDeclLinkage() {
97 LVFlags F;
98 F.ConsiderGlobalVisibility = false;
99 F.ConsiderVisibilityAttributes = false;
John McCall8bc6d5b2011-03-04 10:39:25 +0000100 F.ConsiderTemplateParameterTypes = false;
Douglas Gregorbf62d642010-12-06 18:36:25 +0000101 return F;
102 }
103
John McCall07072662010-11-02 01:45:15 +0000104 /// Returns a set of flags, otherwise based on these, which ignores
105 /// off all sources of visibility except template arguments.
106 LVFlags onlyTemplateVisibility() const {
107 LVFlags F = *this;
108 F.ConsiderGlobalVisibility = false;
109 F.ConsiderVisibilityAttributes = false;
John McCall8bc6d5b2011-03-04 10:39:25 +0000110 F.ConsiderTemplateParameterTypes = false;
John McCall07072662010-11-02 01:45:15 +0000111 return F;
112 }
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000113};
Benjamin Kramer396dcf32010-11-05 19:56:37 +0000114} // end anonymous namespace
John McCall07072662010-11-02 01:45:15 +0000115
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000116/// \brief Get the most restrictive linkage for the types in the given
117/// template parameter list.
John McCall457a04e2010-10-22 21:05:15 +0000118static LVPair
119getLVForTemplateParameterList(const TemplateParameterList *Params) {
120 LVPair LV(ExternalLinkage, DefaultVisibility);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000121 for (TemplateParameterList::const_iterator P = Params->begin(),
122 PEnd = Params->end();
123 P != PEnd; ++P) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000124 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
125 if (NTTP->isExpandedParameterPack()) {
126 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
127 QualType T = NTTP->getExpansionType(I);
128 if (!T->isDependentType())
129 LV = merge(LV, T->getLinkageAndVisibility());
130 }
131 continue;
132 }
133
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000134 if (!NTTP->getType()->isDependentType()) {
John McCall457a04e2010-10-22 21:05:15 +0000135 LV = merge(LV, NTTP->getType()->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000136 continue;
137 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000138 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000139
140 if (TemplateTemplateParmDecl *TTP
141 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
John McCallc273f242010-10-30 11:50:40 +0000142 LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000143 }
144 }
145
John McCall457a04e2010-10-22 21:05:15 +0000146 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000147}
148
Douglas Gregorbf62d642010-12-06 18:36:25 +0000149/// getLVForDecl - Get the linkage and visibility for the given declaration.
150static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
151
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000152/// \brief Get the most restrictive linkage for the types and
153/// declarations in the given template argument list.
John McCall457a04e2010-10-22 21:05:15 +0000154static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args,
Douglas Gregorbf62d642010-12-06 18:36:25 +0000155 unsigned NumArgs,
156 LVFlags &F) {
John McCall457a04e2010-10-22 21:05:15 +0000157 LVPair LV(ExternalLinkage, DefaultVisibility);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000158
159 for (unsigned I = 0; I != NumArgs; ++I) {
160 switch (Args[I].getKind()) {
161 case TemplateArgument::Null:
162 case TemplateArgument::Integral:
163 case TemplateArgument::Expression:
164 break;
165
166 case TemplateArgument::Type:
John McCall457a04e2010-10-22 21:05:15 +0000167 LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000168 break;
169
170 case TemplateArgument::Declaration:
John McCall457a04e2010-10-22 21:05:15 +0000171 // The decl can validly be null as the representation of nullptr
172 // arguments, valid only in C++0x.
173 if (Decl *D = Args[I].getAsDecl()) {
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000174 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
175 LV = merge(LV, getLVForDecl(ND, F));
John McCall457a04e2010-10-22 21:05:15 +0000176 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000177 break;
178
179 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000180 case TemplateArgument::TemplateExpansion:
181 if (TemplateDecl *Template
182 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000183 LV = merge(LV, getLVForDecl(Template, F));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000184 break;
185
186 case TemplateArgument::Pack:
John McCall457a04e2010-10-22 21:05:15 +0000187 LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(),
Douglas Gregorbf62d642010-12-06 18:36:25 +0000188 Args[I].pack_size(),
189 F));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000190 break;
191 }
192 }
193
John McCall457a04e2010-10-22 21:05:15 +0000194 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000195}
196
John McCallc273f242010-10-30 11:50:40 +0000197static LVPair
Douglas Gregorbf62d642010-12-06 18:36:25 +0000198getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
199 LVFlags &F) {
200 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
John McCall8823c652010-08-13 08:35:10 +0000201}
202
John McCallb8c604a2011-06-27 23:06:04 +0000203static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
204 const FunctionTemplateSpecializationInfo *spec) {
205 return !(spec->isExplicitSpecialization() &&
206 fn->hasAttr<VisibilityAttr>());
207}
208
209static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
210 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
211}
212
John McCall07072662010-11-02 01:45:15 +0000213static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000214 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000215 "Not a name having namespace scope");
216 ASTContext &Context = D->getASTContext();
217
218 // C++ [basic.link]p3:
219 // A name having namespace scope (3.3.6) has internal linkage if it
220 // is the name of
221 // - an object, reference, function or function template that is
222 // explicitly declared static; or,
223 // (This bullet corresponds to C99 6.2.2p3.)
224 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
225 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000226 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000227 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000228
229 // - an object or reference that is explicitly declared const
230 // and neither explicitly declared extern nor previously
231 // declared to have external linkage; or
232 // (there is no equivalent in C99)
233 if (Context.getLangOptions().CPlusPlus &&
Eli Friedmanf873c2f2009-11-26 03:04:01 +0000234 Var->getType().isConstant(Context) &&
John McCall8e7d6562010-08-26 03:08:43 +0000235 Var->getStorageClass() != SC_Extern &&
236 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000237 bool FoundExtern = false;
238 for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
239 PrevVar && !FoundExtern;
240 PrevVar = PrevVar->getPreviousDeclaration())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000241 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000242 FoundExtern = true;
243
244 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000245 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000246 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000247 if (Var->getStorageClass() == SC_None) {
248 const VarDecl *PrevVar = Var->getPreviousDeclaration();
249 for (; PrevVar; PrevVar = PrevVar->getPreviousDeclaration())
250 if (PrevVar->getStorageClass() == SC_PrivateExtern)
251 break;
252 if (PrevVar)
253 return PrevVar->getLinkageAndVisibility();
254 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000255 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000256 // C++ [temp]p4:
257 // A non-member function template can have internal linkage; any
258 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000259 const FunctionDecl *Function = 0;
260 if (const FunctionTemplateDecl *FunTmpl
261 = dyn_cast<FunctionTemplateDecl>(D))
262 Function = FunTmpl->getTemplatedDecl();
263 else
264 Function = cast<FunctionDecl>(D);
265
266 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000267 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000268 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000269 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
270 // - a data member of an anonymous union.
271 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000272 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000273 }
274
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000275 if (D->isInAnonymousNamespace()) {
276 const VarDecl *Var = dyn_cast<VarDecl>(D);
277 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
278 if ((!Var || !Var->isExternC()) && (!Func || !Func->isExternC()))
279 return LinkageInfo::uniqueExternal();
280 }
John McCallb7139c42010-10-28 04:18:25 +0000281
John McCall457a04e2010-10-22 21:05:15 +0000282 // Set up the defaults.
283
284 // C99 6.2.2p5:
285 // If the declaration of an identifier for an object has file
286 // scope and no storage-class specifier, its linkage is
287 // external.
John McCallc273f242010-10-30 11:50:40 +0000288 LinkageInfo LV;
289
John McCall07072662010-11-02 01:45:15 +0000290 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000291 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
292 LV.setVisibility(*Vis, true);
John McCall07072662010-11-02 01:45:15 +0000293 F.ConsiderGlobalVisibility = false;
John McCall2faf32c2010-12-10 02:59:44 +0000294 } else {
295 // If we're declared in a namespace with a visibility attribute,
296 // use that namespace's visibility, but don't call it explicit.
297 for (const DeclContext *DC = D->getDeclContext();
298 !isa<TranslationUnitDecl>(DC);
299 DC = DC->getParent()) {
300 if (!isa<NamespaceDecl>(DC)) continue;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000301 if (llvm::Optional<Visibility> Vis
302 = cast<NamespaceDecl>(DC)->getExplicitVisibility()) {
303 LV.setVisibility(*Vis, false);
John McCall2faf32c2010-12-10 02:59:44 +0000304 F.ConsiderGlobalVisibility = false;
305 break;
306 }
307 }
John McCall07072662010-11-02 01:45:15 +0000308 }
John McCallc273f242010-10-30 11:50:40 +0000309 }
John McCall457a04e2010-10-22 21:05:15 +0000310
Douglas Gregorf73b2822009-11-25 22:24:25 +0000311 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000312
Douglas Gregorf73b2822009-11-25 22:24:25 +0000313 // A name having namespace scope has external linkage if it is the
314 // name of
315 //
316 // - an object or reference, unless it has internal linkage; or
317 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000318 // GCC applies the following optimization to variables and static
319 // data members, but not to functions:
320 //
John McCall457a04e2010-10-22 21:05:15 +0000321 // Modify the variable's LV by the LV of its type unless this is
322 // C or extern "C". This follows from [basic.link]p9:
323 // A type without linkage shall not be used as the type of a
324 // variable or function with external linkage unless
325 // - the entity has C language linkage, or
326 // - the entity is declared within an unnamed namespace, or
327 // - the entity is not used or is defined in the same
328 // translation unit.
329 // and [basic.link]p10:
330 // ...the types specified by all declarations referring to a
331 // given variable or function shall be identical...
332 // C does not have an equivalent rule.
333 //
John McCall5fe84122010-10-26 04:59:26 +0000334 // Ignore this if we've got an explicit attribute; the user
335 // probably knows what they're doing.
336 //
John McCall457a04e2010-10-22 21:05:15 +0000337 // Note that we don't want to make the variable non-external
338 // because of this, but unique-external linkage suits us.
John McCall36cd5cc2010-10-30 09:18:49 +0000339 if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
John McCall457a04e2010-10-22 21:05:15 +0000340 LVPair TypeLV = Var->getType()->getLinkageAndVisibility();
341 if (TypeLV.first != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000342 return LinkageInfo::uniqueExternal();
343 if (!LV.visibilityExplicit())
344 LV.mergeVisibility(TypeLV.second);
John McCall37bb6c92010-10-29 22:22:43 +0000345 }
346
John McCall23032652010-11-02 18:38:13 +0000347 if (Var->getStorageClass() == SC_PrivateExtern)
348 LV.setVisibility(HiddenVisibility, true);
349
Douglas Gregorf73b2822009-11-25 22:24:25 +0000350 if (!Context.getLangOptions().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000351 (Var->getStorageClass() == SC_Extern ||
352 Var->getStorageClass() == SC_PrivateExtern)) {
John McCall457a04e2010-10-22 21:05:15 +0000353
Douglas Gregorf73b2822009-11-25 22:24:25 +0000354 // C99 6.2.2p4:
355 // For an identifier declared with the storage-class specifier
356 // extern in a scope in which a prior declaration of that
357 // identifier is visible, if the prior declaration specifies
358 // internal or external linkage, the linkage of the identifier
359 // at the later declaration is the same as the linkage
360 // specified at the prior declaration. If no prior declaration
361 // is visible, or if the prior declaration specifies no
362 // linkage, then the identifier has external linkage.
363 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000364 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
John McCallc273f242010-10-30 11:50:40 +0000365 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
366 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000367 }
368 }
369
Douglas Gregorf73b2822009-11-25 22:24:25 +0000370 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000371 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000372 // In theory, we can modify the function's LV by the LV of its
373 // type unless it has C linkage (see comment above about variables
374 // for justification). In practice, GCC doesn't do this, so it's
375 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000376
John McCall23032652010-11-02 18:38:13 +0000377 if (Function->getStorageClass() == SC_PrivateExtern)
378 LV.setVisibility(HiddenVisibility, true);
379
Douglas Gregorf73b2822009-11-25 22:24:25 +0000380 // C99 6.2.2p5:
381 // If the declaration of an identifier for a function has no
382 // storage-class specifier, its linkage is determined exactly
383 // as if it were declared with the storage-class specifier
384 // extern.
385 if (!Context.getLangOptions().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000386 (Function->getStorageClass() == SC_Extern ||
387 Function->getStorageClass() == SC_PrivateExtern ||
388 Function->getStorageClass() == SC_None)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000389 // C99 6.2.2p4:
390 // For an identifier declared with the storage-class specifier
391 // extern in a scope in which a prior declaration of that
392 // identifier is visible, if the prior declaration specifies
393 // internal or external linkage, the linkage of the identifier
394 // at the later declaration is the same as the linkage
395 // specified at the prior declaration. If no prior declaration
396 // is visible, or if the prior declaration specifies no
397 // linkage, then the identifier has external linkage.
398 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000399 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
John McCallc273f242010-10-30 11:50:40 +0000400 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
401 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000402 }
403 }
404
John McCallf768aa72011-02-10 06:50:24 +0000405 // In C++, then if the type of the function uses a type with
406 // unique-external linkage, it's not legally usable from outside
407 // this translation unit. However, we should use the C linkage
408 // rules instead for extern "C" declarations.
409 if (Context.getLangOptions().CPlusPlus && !Function->isExternC() &&
410 Function->getType()->getLinkage() == UniqueExternalLinkage)
411 return LinkageInfo::uniqueExternal();
412
John McCallb8c604a2011-06-27 23:06:04 +0000413 // Consider LV from the template and the template arguments unless
414 // this is an explicit specialization with a visibility attribute.
415 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000416 = Function->getTemplateSpecializationInfo()) {
John McCallb8c604a2011-06-27 23:06:04 +0000417 if (shouldConsiderTemplateLV(Function, specInfo)) {
418 LV.merge(getLVForDecl(specInfo->getTemplate(),
419 F.onlyTemplateVisibility()));
420 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
421 LV.merge(getLVForTemplateArgumentList(templateArgs, F));
422 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000423 }
424
Douglas Gregorf73b2822009-11-25 22:24:25 +0000425 // - a named class (Clause 9), or an unnamed class defined in a
426 // typedef declaration in which the class has the typedef name
427 // for linkage purposes (7.1.3); or
428 // - a named enumeration (7.2), or an unnamed enumeration
429 // defined in a typedef declaration in which the enumeration
430 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000431 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
432 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000433 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000434 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000435
John McCall457a04e2010-10-22 21:05:15 +0000436 // If this is a class template specialization, consider the
437 // linkage of the template and template arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000438 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000439 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCallb8c604a2011-06-27 23:06:04 +0000440 if (shouldConsiderTemplateLV(spec)) {
441 // From the template.
442 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
443 F.onlyTemplateVisibility()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000444
John McCallb8c604a2011-06-27 23:06:04 +0000445 // The arguments at which the template was instantiated.
446 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
447 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
448 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000449 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000450
John McCall5fe84122010-10-26 04:59:26 +0000451 // Consider -fvisibility unless the type has C linkage.
John McCall07072662010-11-02 01:45:15 +0000452 if (F.ConsiderGlobalVisibility)
453 F.ConsiderGlobalVisibility =
John McCall5fe84122010-10-26 04:59:26 +0000454 (Context.getLangOptions().CPlusPlus &&
455 !Tag->getDeclContext()->isExternCContext());
John McCall457a04e2010-10-22 21:05:15 +0000456
Douglas Gregorf73b2822009-11-25 22:24:25 +0000457 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000458 } else if (isa<EnumConstantDecl>(D)) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000459 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
John McCallc273f242010-10-30 11:50:40 +0000460 if (!isExternalLinkage(EnumLV.linkage()))
461 return LinkageInfo::none();
462 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000463
464 // - a template, unless it is a function template that has
465 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000466 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
467 if (F.ConsiderTemplateParameterTypes)
468 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000469
Douglas Gregorf73b2822009-11-25 22:24:25 +0000470 // - a namespace (7.3), unless it is declared within an unnamed
471 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000472 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
473 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000474
John McCall457a04e2010-10-22 21:05:15 +0000475 // By extension, we assign external linkage to Objective-C
476 // interfaces.
477 } else if (isa<ObjCInterfaceDecl>(D)) {
478 // fallout
479
480 // Everything not covered here has no linkage.
481 } else {
John McCallc273f242010-10-30 11:50:40 +0000482 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000483 }
484
485 // If we ended up with non-external linkage, visibility should
486 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000487 if (LV.linkage() != ExternalLinkage)
488 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000489
490 // If we didn't end up with hidden visibility, consider attributes
491 // and -fvisibility.
John McCall07072662010-11-02 01:45:15 +0000492 if (F.ConsiderGlobalVisibility)
John McCallc273f242010-10-30 11:50:40 +0000493 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
John McCall457a04e2010-10-22 21:05:15 +0000494
495 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000496}
497
John McCall07072662010-11-02 01:45:15 +0000498static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
John McCall457a04e2010-10-22 21:05:15 +0000499 // Only certain class members have linkage. Note that fields don't
500 // really have linkage, but it's convenient to say they do for the
501 // purposes of calculating linkage of pointer-to-data-member
502 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000503 if (!(isa<CXXMethodDecl>(D) ||
504 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000505 isa<FieldDecl>(D) ||
John McCall8823c652010-08-13 08:35:10 +0000506 (isa<TagDecl>(D) &&
Richard Smithdda56e42011-04-15 14:24:37 +0000507 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
John McCallc273f242010-10-30 11:50:40 +0000508 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000509
John McCall07072662010-11-02 01:45:15 +0000510 LinkageInfo LV;
511
512 // The flags we're going to use to compute the class's visibility.
513 LVFlags ClassF = F;
514
515 // If we have an explicit visibility attribute, merge that in.
516 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000517 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
518 LV.mergeVisibility(*Vis, true);
John McCall07072662010-11-02 01:45:15 +0000519
520 // Ignore global visibility later, but not this attribute.
521 F.ConsiderGlobalVisibility = false;
522
523 // Ignore both global visibility and attributes when computing our
524 // parent's visibility.
525 ClassF = F.onlyTemplateVisibility();
526 }
527 }
John McCallc273f242010-10-30 11:50:40 +0000528
529 // Class members only have linkage if their class has external
John McCall07072662010-11-02 01:45:15 +0000530 // linkage.
531 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
532 if (!isExternalLinkage(LV.linkage()))
John McCallc273f242010-10-30 11:50:40 +0000533 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000534
535 // If the class already has unique-external linkage, we can't improve.
John McCall07072662010-11-02 01:45:15 +0000536 if (LV.linkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000537 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000538
John McCall8823c652010-08-13 08:35:10 +0000539 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000540 // If the type of the function uses a type with unique-external
541 // linkage, it's not legally usable from outside this translation unit.
542 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
543 return LinkageInfo::uniqueExternal();
544
John McCall37bb6c92010-10-29 22:22:43 +0000545 TemplateSpecializationKind TSK = TSK_Undeclared;
546
John McCall457a04e2010-10-22 21:05:15 +0000547 // If this is a method template specialization, use the linkage for
548 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000549 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000550 = MD->getTemplateSpecializationInfo()) {
John McCallb8c604a2011-06-27 23:06:04 +0000551 if (shouldConsiderTemplateLV(MD, spec)) {
552 LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F));
553 if (F.ConsiderTemplateParameterTypes)
554 LV.merge(getLVForTemplateParameterList(
555 spec->getTemplate()->getTemplateParameters()));
556 }
John McCall37bb6c92010-10-29 22:22:43 +0000557
John McCallb8c604a2011-06-27 23:06:04 +0000558 TSK = spec->getTemplateSpecializationKind();
John McCall37bb6c92010-10-29 22:22:43 +0000559 } else if (MemberSpecializationInfo *MSI =
560 MD->getMemberSpecializationInfo()) {
561 TSK = MSI->getTemplateSpecializationKind();
John McCall8823c652010-08-13 08:35:10 +0000562 }
563
John McCall37bb6c92010-10-29 22:22:43 +0000564 // If we're paying attention to global visibility, apply
565 // -finline-visibility-hidden if this is an inline method.
566 //
John McCallc273f242010-10-30 11:50:40 +0000567 // Note that ConsiderGlobalVisibility doesn't yet have information
568 // about whether containing classes have visibility attributes,
569 // and that's intentional.
570 if (TSK != TSK_ExplicitInstantiationDeclaration &&
John McCall07072662010-11-02 01:45:15 +0000571 F.ConsiderGlobalVisibility &&
John McCalle6e622e2010-11-01 01:29:57 +0000572 MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
573 // InlineVisibilityHidden only applies to definitions, and
574 // isInlined() only gives meaningful answers on definitions
575 // anyway.
576 const FunctionDecl *Def = 0;
577 if (MD->hasBody(Def) && Def->isInlined())
578 LV.setVisibility(HiddenVisibility);
579 }
John McCall457a04e2010-10-22 21:05:15 +0000580
John McCall37bb6c92010-10-29 22:22:43 +0000581 // Note that in contrast to basically every other situation, we
582 // *do* apply -fvisibility to method declarations.
583
584 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000585 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000586 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCallb8c604a2011-06-27 23:06:04 +0000587 if (shouldConsiderTemplateLV(spec)) {
588 // Merge template argument/parameter information for member
589 // class template specializations.
590 LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
John McCall8bc6d5b2011-03-04 10:39:25 +0000591 if (F.ConsiderTemplateParameterTypes)
592 LV.merge(getLVForTemplateParameterList(
John McCallb8c604a2011-06-27 23:06:04 +0000593 spec->getSpecializedTemplate()->getTemplateParameters()));
594 }
John McCall37bb6c92010-10-29 22:22:43 +0000595 }
596
John McCall37bb6c92010-10-29 22:22:43 +0000597 // Static data members.
598 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000599 // Modify the variable's linkage by its type, but ignore the
600 // type's visibility unless it's a definition.
601 LVPair TypeLV = VD->getType()->getLinkageAndVisibility();
602 if (TypeLV.first != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000603 LV.mergeLinkage(UniqueExternalLinkage);
604 if (!LV.visibilityExplicit())
605 LV.mergeVisibility(TypeLV.second);
John McCall37bb6c92010-10-29 22:22:43 +0000606 }
607
John McCall07072662010-11-02 01:45:15 +0000608 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
John McCall37bb6c92010-10-29 22:22:43 +0000609
610 // Apply -fvisibility if desired.
John McCall07072662010-11-02 01:45:15 +0000611 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
John McCallc273f242010-10-30 11:50:40 +0000612 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
John McCall8823c652010-08-13 08:35:10 +0000613 }
614
John McCall457a04e2010-10-22 21:05:15 +0000615 return LV;
John McCall8823c652010-08-13 08:35:10 +0000616}
617
John McCalld396b972011-02-08 19:01:05 +0000618static void clearLinkageForClass(const CXXRecordDecl *record) {
619 for (CXXRecordDecl::decl_iterator
620 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
621 Decl *child = *i;
622 if (isa<NamedDecl>(child))
623 cast<NamedDecl>(child)->ClearLinkageCache();
624 }
625}
626
627void NamedDecl::ClearLinkageCache() {
628 // Note that we can't skip clearing the linkage of children just
629 // because the parent doesn't have cached linkage: we don't cache
630 // when computing linkage for parent contexts.
631
632 HasCachedLinkage = 0;
633
634 // If we're changing the linkage of a class, we need to reset the
635 // linkage of child declarations, too.
636 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
637 clearLinkageForClass(record);
638
John McCall83779672011-02-19 02:53:41 +0000639 if (ClassTemplateDecl *temp =
640 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
John McCalld396b972011-02-08 19:01:05 +0000641 // Clear linkage for the template pattern.
642 CXXRecordDecl *record = temp->getTemplatedDecl();
643 record->HasCachedLinkage = 0;
644 clearLinkageForClass(record);
645
John McCall83779672011-02-19 02:53:41 +0000646 // We need to clear linkage for specializations, too.
647 for (ClassTemplateDecl::spec_iterator
648 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
649 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000650 }
John McCall83779672011-02-19 02:53:41 +0000651
652 // Clear cached linkage for function template decls, too.
653 if (FunctionTemplateDecl *temp =
John McCall8f9a4292011-03-22 06:58:49 +0000654 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
655 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000656 for (FunctionTemplateDecl::spec_iterator
657 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
658 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000659 }
John McCall83779672011-02-19 02:53:41 +0000660
John McCalld396b972011-02-08 19:01:05 +0000661}
662
Douglas Gregorbf62d642010-12-06 18:36:25 +0000663Linkage NamedDecl::getLinkage() const {
664 if (HasCachedLinkage) {
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000665 assert(Linkage(CachedLinkage) ==
666 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000667 return Linkage(CachedLinkage);
668 }
669
670 CachedLinkage = getLVForDecl(this,
671 LVFlags::CreateOnlyDeclLinkage()).linkage();
672 HasCachedLinkage = 1;
673 return Linkage(CachedLinkage);
674}
675
John McCallc273f242010-10-30 11:50:40 +0000676LinkageInfo NamedDecl::getLinkageAndVisibility() const {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000677 LinkageInfo LI = getLVForDecl(this, LVFlags());
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000678 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000679 HasCachedLinkage = 1;
680 CachedLinkage = LI.linkage();
681 return LI;
John McCall033caa52010-10-29 00:29:13 +0000682}
Ted Kremenek926d8602010-04-20 23:15:35 +0000683
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000684llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
685 // Use the most recent declaration of a variable.
686 if (const VarDecl *var = dyn_cast<VarDecl>(this))
687 return getVisibilityOf(var->getMostRecentDeclaration());
688
689 // Use the most recent declaration of a function, and also handle
690 // function template specializations.
691 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
692 if (llvm::Optional<Visibility> V
693 = getVisibilityOf(fn->getMostRecentDeclaration()))
694 return V;
695
696 // If the function is a specialization of a template with an
697 // explicit visibility attribute, use that.
698 if (FunctionTemplateSpecializationInfo *templateInfo
699 = fn->getTemplateSpecializationInfo())
700 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
701
702 return llvm::Optional<Visibility>();
703 }
704
705 // Otherwise, just check the declaration itself first.
706 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
707 return V;
708
709 // If there wasn't explicit visibility there, and this is a
710 // specialization of a class template, check for visibility
711 // on the pattern.
712 if (const ClassTemplateSpecializationDecl *spec
713 = dyn_cast<ClassTemplateSpecializationDecl>(this))
714 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
715
716 return llvm::Optional<Visibility>();
717}
718
John McCall07072662010-11-02 01:45:15 +0000719static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000720 // Objective-C: treat all Objective-C declarations as having external
721 // linkage.
John McCall033caa52010-10-29 00:29:13 +0000722 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000723 default:
724 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +0000725 case Decl::ParmVar:
726 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000727 case Decl::TemplateTemplateParm: // count these as external
728 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +0000729 case Decl::ObjCAtDefsField:
730 case Decl::ObjCCategory:
731 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +0000732 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +0000733 case Decl::ObjCForwardProtocol:
734 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +0000735 case Decl::ObjCMethod:
736 case Decl::ObjCProperty:
737 case Decl::ObjCPropertyImpl:
738 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +0000739 return LinkageInfo::external();
Ted Kremenek926d8602010-04-20 23:15:35 +0000740 }
741
Douglas Gregorf73b2822009-11-25 22:24:25 +0000742 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +0000743 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall07072662010-11-02 01:45:15 +0000744 return getLVForNamespaceScopeDecl(D, Flags);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000745
746 // C++ [basic.link]p5:
747 // In addition, a member function, static data member, a named
748 // class or enumeration of class scope, or an unnamed class or
749 // enumeration defined in a class-scope typedef declaration such
750 // that the class or enumeration has the typedef name for linkage
751 // purposes (7.1.3), has external linkage if the name of the class
752 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +0000753 if (D->getDeclContext()->isRecord())
John McCall07072662010-11-02 01:45:15 +0000754 return getLVForClassMember(D, Flags);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000755
756 // C++ [basic.link]p6:
757 // The name of a function declared in block scope and the name of
758 // an object declared by a block scope extern declaration have
759 // linkage. If there is a visible declaration of an entity with
760 // linkage having the same name and type, ignoring entities
761 // declared outside the innermost enclosing namespace scope, the
762 // block scope declaration declares that same entity and receives
763 // the linkage of the previous declaration. If there is more than
764 // one such matching entity, the program is ill-formed. Otherwise,
765 // if no matching entity is found, the block scope entity receives
766 // external linkage.
John McCall033caa52010-10-29 00:29:13 +0000767 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
768 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Chandler Carruth4322a282011-02-25 00:05:02 +0000769 if (Function->isInAnonymousNamespace() && !Function->isExternC())
John McCallc273f242010-10-30 11:50:40 +0000770 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000771
John McCallc273f242010-10-30 11:50:40 +0000772 LinkageInfo LV;
Douglas Gregorbf62d642010-12-06 18:36:25 +0000773 if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000774 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
775 LV.setVisibility(*Vis);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000776 }
777
John McCall457a04e2010-10-22 21:05:15 +0000778 if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000779 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallc273f242010-10-30 11:50:40 +0000780 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
781 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000782 }
783
784 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000785 }
786
John McCall033caa52010-10-29 00:29:13 +0000787 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
John McCall8e7d6562010-08-26 03:08:43 +0000788 if (Var->getStorageClass() == SC_Extern ||
789 Var->getStorageClass() == SC_PrivateExtern) {
Chandler Carruth4322a282011-02-25 00:05:02 +0000790 if (Var->isInAnonymousNamespace() && !Var->isExternC())
John McCallc273f242010-10-30 11:50:40 +0000791 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000792
John McCallc273f242010-10-30 11:50:40 +0000793 LinkageInfo LV;
John McCall457a04e2010-10-22 21:05:15 +0000794 if (Var->getStorageClass() == SC_PrivateExtern)
John McCallc273f242010-10-30 11:50:40 +0000795 LV.setVisibility(HiddenVisibility);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000796 else if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000797 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
798 LV.setVisibility(*Vis);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000799 }
800
John McCall457a04e2010-10-22 21:05:15 +0000801 if (const VarDecl *Prev = Var->getPreviousDeclaration()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000802 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallc273f242010-10-30 11:50:40 +0000803 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
804 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000805 }
806
807 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000808 }
809 }
810
811 // C++ [basic.link]p6:
812 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +0000813 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000814}
Douglas Gregorf73b2822009-11-25 22:24:25 +0000815
Douglas Gregor2ada0482009-02-04 17:27:36 +0000816std::string NamedDecl::getQualifiedNameAsString() const {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000817 return getQualifiedNameAsString(getASTContext().getLangOptions());
818}
819
820std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000821 const DeclContext *Ctx = getDeclContext();
822
823 if (Ctx->isFunctionOrMethod())
824 return getNameAsString();
825
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000826 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000827 ContextsTy Contexts;
828
829 // Collect contexts.
830 while (Ctx && isa<NamedDecl>(Ctx)) {
831 Contexts.push_back(Ctx);
832 Ctx = Ctx->getParent();
833 };
834
835 std::string QualName;
836 llvm::raw_string_ostream OS(QualName);
837
838 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
839 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000840 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000841 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregor85673582009-05-18 17:01:57 +0000842 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
843 std::string TemplateArgsStr
844 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +0000845 TemplateArgs.data(),
846 TemplateArgs.size(),
Anders Carlsson2fb08242009-09-08 18:24:21 +0000847 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000848 OS << Spec->getName() << TemplateArgsStr;
849 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +0000850 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000851 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +0000852 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000853 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000854 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
855 if (!RD->getIdentifier())
856 OS << "<anonymous " << RD->getKindName() << '>';
857 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000858 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000859 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +0000860 const FunctionProtoType *FT = 0;
861 if (FD->hasWrittenPrototype())
862 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
863
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000864 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +0000865 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +0000866 unsigned NumParams = FD->getNumParams();
867 for (unsigned i = 0; i < NumParams; ++i) {
868 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000869 OS << ", ";
Sam Weinigb999f682009-12-28 03:19:38 +0000870 std::string Param;
871 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000872 OS << Param;
Sam Weinigb999f682009-12-28 03:19:38 +0000873 }
874
875 if (FT->isVariadic()) {
876 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000877 OS << ", ";
878 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +0000879 }
880 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000881 OS << ')';
882 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000883 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000884 }
885 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000886 }
887
John McCalla2a3f7d2010-03-16 21:48:18 +0000888 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000889 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +0000890 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000891 OS << "<anonymous>";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000892
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000893 return OS.str();
Douglas Gregor2ada0482009-02-04 17:27:36 +0000894}
895
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000896bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000897 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
898
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
900 // We want to keep it, unless it nominates same namespace.
901 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +0000902 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
903 ->getOriginalNamespace() ==
904 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
905 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000906 }
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
909 // For function declarations, we keep track of redeclarations.
910 return FD->getPreviousDeclaration() == OldD;
911
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000912 // For function templates, the underlying function declarations are linked.
913 if (const FunctionTemplateDecl *FunctionTemplate
914 = dyn_cast<FunctionTemplateDecl>(this))
915 if (const FunctionTemplateDecl *OldFunctionTemplate
916 = dyn_cast<FunctionTemplateDecl>(OldD))
917 return FunctionTemplate->getTemplatedDecl()
918 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000919
Steve Naroffc4173fa2009-02-22 19:35:57 +0000920 // For method declarations, we keep track of redeclarations.
921 if (isa<ObjCMethodDecl>(this))
922 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000923
John McCall9f3059a2009-10-09 21:13:30 +0000924 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
925 return true;
926
John McCall3f746822009-11-17 05:59:44 +0000927 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
928 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
929 cast<UsingShadowDecl>(OldD)->getTargetDecl();
930
Douglas Gregora9d87bc2011-02-25 00:36:19 +0000931 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
932 ASTContext &Context = getASTContext();
933 return Context.getCanonicalNestedNameSpecifier(
934 cast<UsingDecl>(this)->getQualifier()) ==
935 Context.getCanonicalNestedNameSpecifier(
936 cast<UsingDecl>(OldD)->getQualifier());
937 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +0000938
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000939 // For non-function declarations, if the declarations are of the
940 // same kind then this must be a redeclaration, or semantic analysis
941 // would not have given us the new declaration.
942 return this->getKind() == OldD->getKind();
943}
944
Douglas Gregoreddf4332009-02-24 20:03:32 +0000945bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000946 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000947}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000948
Anders Carlsson6915bf62009-06-26 06:29:23 +0000949NamedDecl *NamedDecl::getUnderlyingDecl() {
950 NamedDecl *ND = this;
951 while (true) {
John McCall3f746822009-11-17 05:59:44 +0000952 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
Anders Carlsson6915bf62009-06-26 06:29:23 +0000953 ND = UD->getTargetDecl();
954 else if (ObjCCompatibleAliasDecl *AD
955 = dyn_cast<ObjCCompatibleAliasDecl>(ND))
956 return AD->getClassInterface();
957 else
958 return ND;
959 }
960}
961
John McCalla8ae2222010-04-06 21:38:20 +0000962bool NamedDecl::isCXXInstanceMember() const {
963 assert(isCXXClassMember() &&
964 "checking whether non-member is instance member");
965
966 const NamedDecl *D = this;
967 if (isa<UsingShadowDecl>(D))
968 D = cast<UsingShadowDecl>(D)->getTargetDecl();
969
Francois Pichet783dd6e2010-11-21 06:08:52 +0000970 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +0000971 return true;
972 if (isa<CXXMethodDecl>(D))
973 return cast<CXXMethodDecl>(D)->isInstance();
974 if (isa<FunctionTemplateDecl>(D))
975 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
976 ->getTemplatedDecl())->isInstance();
977 return false;
978}
979
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000980//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000981// DeclaratorDecl Implementation
982//===----------------------------------------------------------------------===//
983
Douglas Gregorec9c6ae2010-07-06 18:42:40 +0000984template <typename DeclT>
985static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
986 if (decl->getNumTemplateParameterLists() > 0)
987 return decl->getTemplateParameterList(0)->getTemplateLoc();
988 else
989 return decl->getInnerLocStart();
990}
991
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000992SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +0000993 TypeSourceInfo *TSI = getTypeSourceInfo();
994 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000995 return SourceLocation();
996}
997
Douglas Gregor14454802011-02-25 02:25:35 +0000998void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
999 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001000 // Make sure the extended decl info is allocated.
1001 if (!hasExtInfo()) {
1002 // Save (non-extended) type source info pointer.
1003 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1004 // Allocate external info struct.
1005 DeclInfo = new (getASTContext()) ExtInfo;
1006 // Restore savedTInfo into (extended) decl info.
1007 getExtInfo()->TInfo = savedTInfo;
1008 }
1009 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001010 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001011 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001012 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001013 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001014 if (getExtInfo()->NumTemplParamLists == 0) {
1015 // Save type source info pointer.
1016 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1017 // Deallocate the extended decl info.
1018 getASTContext().Deallocate(getExtInfo());
1019 // Restore savedTInfo into (non-extended) decl info.
1020 DeclInfo = savedTInfo;
1021 }
1022 else
1023 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001024 }
1025 }
1026}
1027
Abramo Bagnara60804e12011-03-18 15:16:37 +00001028void
1029DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1030 unsigned NumTPLists,
1031 TemplateParameterList **TPLists) {
1032 assert(NumTPLists > 0);
1033 // Make sure the extended decl info is allocated.
1034 if (!hasExtInfo()) {
1035 // Save (non-extended) type source info pointer.
1036 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1037 // Allocate external info struct.
1038 DeclInfo = new (getASTContext()) ExtInfo;
1039 // Restore savedTInfo into (extended) decl info.
1040 getExtInfo()->TInfo = savedTInfo;
1041 }
1042 // Set the template parameter lists info.
1043 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1044}
1045
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001046SourceLocation DeclaratorDecl::getOuterLocStart() const {
1047 return getTemplateOrInnerLocStart(this);
1048}
1049
Abramo Bagnaraea947882011-03-08 16:41:52 +00001050namespace {
1051
1052// Helper function: returns true if QT is or contains a type
1053// having a postfix component.
1054bool typeIsPostfix(clang::QualType QT) {
1055 while (true) {
1056 const Type* T = QT.getTypePtr();
1057 switch (T->getTypeClass()) {
1058 default:
1059 return false;
1060 case Type::Pointer:
1061 QT = cast<PointerType>(T)->getPointeeType();
1062 break;
1063 case Type::BlockPointer:
1064 QT = cast<BlockPointerType>(T)->getPointeeType();
1065 break;
1066 case Type::MemberPointer:
1067 QT = cast<MemberPointerType>(T)->getPointeeType();
1068 break;
1069 case Type::LValueReference:
1070 case Type::RValueReference:
1071 QT = cast<ReferenceType>(T)->getPointeeType();
1072 break;
1073 case Type::PackExpansion:
1074 QT = cast<PackExpansionType>(T)->getPattern();
1075 break;
1076 case Type::Paren:
1077 case Type::ConstantArray:
1078 case Type::DependentSizedArray:
1079 case Type::IncompleteArray:
1080 case Type::VariableArray:
1081 case Type::FunctionProto:
1082 case Type::FunctionNoProto:
1083 return true;
1084 }
1085 }
1086}
1087
1088} // namespace
1089
1090SourceRange DeclaratorDecl::getSourceRange() const {
1091 SourceLocation RangeEnd = getLocation();
1092 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1093 if (typeIsPostfix(TInfo->getType()))
1094 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1095 }
1096 return SourceRange(getOuterLocStart(), RangeEnd);
1097}
1098
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001099void
Douglas Gregor20527e22010-06-15 17:44:38 +00001100QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1101 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001102 TemplateParameterList **TPLists) {
1103 assert((NumTPLists == 0 || TPLists != 0) &&
1104 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001105
1106 // Free previous template parameters (if any).
1107 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001108 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001109 TemplParamLists = 0;
1110 NumTemplParamLists = 0;
1111 }
1112 // Set info on matched template parameter lists (if any).
1113 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001114 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001115 NumTemplParamLists = NumTPLists;
1116 for (unsigned i = NumTPLists; i-- > 0; )
1117 TemplParamLists[i] = TPLists[i];
1118 }
1119}
1120
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001121//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001122// VarDecl Implementation
1123//===----------------------------------------------------------------------===//
1124
Sebastian Redl833ef452010-01-26 22:01:41 +00001125const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1126 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001127 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001128 case SC_Auto: return "auto";
1129 case SC_Extern: return "extern";
1130 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1131 case SC_PrivateExtern: return "__private_extern__";
1132 case SC_Register: return "register";
1133 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001134 }
1135
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001136 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001137 return 0;
1138}
1139
Abramo Bagnaradff19302011-03-08 08:55:46 +00001140VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1141 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001142 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001143 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001144 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001145}
1146
Douglas Gregorbf62d642010-12-06 18:36:25 +00001147void VarDecl::setStorageClass(StorageClass SC) {
1148 assert(isLegalForVariable(SC));
1149 if (getStorageClass() != SC)
1150 ClearLinkageCache();
1151
John McCallbeaa11c2011-05-01 02:13:58 +00001152 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001153}
1154
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001155SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001156 if (getInit())
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001157 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00001158 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001159}
1160
Sebastian Redl833ef452010-01-26 22:01:41 +00001161bool VarDecl::isExternC() const {
1162 ASTContext &Context = getASTContext();
1163 if (!Context.getLangOptions().CPlusPlus)
1164 return (getDeclContext()->isTranslationUnit() &&
John McCall8e7d6562010-08-26 03:08:43 +00001165 getStorageClass() != SC_Static) ||
Sebastian Redl833ef452010-01-26 22:01:41 +00001166 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
1167
Chandler Carruth4322a282011-02-25 00:05:02 +00001168 const DeclContext *DC = getDeclContext();
1169 if (DC->isFunctionOrMethod())
1170 return false;
1171
1172 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001173 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1174 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
John McCall8e7d6562010-08-26 03:08:43 +00001175 return getStorageClass() != SC_Static;
Sebastian Redl833ef452010-01-26 22:01:41 +00001176
1177 break;
1178 }
1179
Sebastian Redl833ef452010-01-26 22:01:41 +00001180 }
1181
1182 return false;
1183}
1184
1185VarDecl *VarDecl::getCanonicalDecl() {
1186 return getFirstDeclaration();
1187}
1188
Sebastian Redl35351a92010-01-31 22:27:38 +00001189VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
1190 // C++ [basic.def]p2:
1191 // A declaration is a definition unless [...] it contains the 'extern'
1192 // specifier or a linkage-specification and neither an initializer [...],
1193 // it declares a static data member in a class declaration [...].
1194 // C++ [temp.expl.spec]p15:
1195 // An explicit specialization of a static data member of a template is a
1196 // definition if the declaration includes an initializer; otherwise, it is
1197 // a declaration.
1198 if (isStaticDataMember()) {
1199 if (isOutOfLine() && (hasInit() ||
1200 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1201 return Definition;
1202 else
1203 return DeclarationOnly;
1204 }
1205 // C99 6.7p5:
1206 // A definition of an identifier is a declaration for that identifier that
1207 // [...] causes storage to be reserved for that object.
1208 // Note: that applies for all non-file-scope objects.
1209 // C99 6.9.2p1:
1210 // If the declaration of an identifier for an object has file scope and an
1211 // initializer, the declaration is an external definition for the identifier
1212 if (hasInit())
1213 return Definition;
1214 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1215 if (hasExternalStorage())
1216 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001217
John McCall8e7d6562010-08-26 03:08:43 +00001218 if (getStorageClassAsWritten() == SC_Extern ||
1219 getStorageClassAsWritten() == SC_PrivateExtern) {
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001220 for (const VarDecl *PrevVar = getPreviousDeclaration();
1221 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
1222 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1223 return DeclarationOnly;
1224 }
1225 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001226 // C99 6.9.2p2:
1227 // A declaration of an object that has file scope without an initializer,
1228 // and without a storage class specifier or the scs 'static', constitutes
1229 // a tentative definition.
1230 // No such thing in C++.
1231 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
1232 return TentativeDefinition;
1233
1234 // What's left is (in C, block-scope) declarations without initializers or
1235 // external storage. These are definitions.
1236 return Definition;
1237}
1238
Sebastian Redl35351a92010-01-31 22:27:38 +00001239VarDecl *VarDecl::getActingDefinition() {
1240 DefinitionKind Kind = isThisDeclarationADefinition();
1241 if (Kind != TentativeDefinition)
1242 return 0;
1243
Chris Lattner48eb14d2010-06-14 18:31:46 +00001244 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001245 VarDecl *First = getFirstDeclaration();
1246 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1247 I != E; ++I) {
1248 Kind = (*I)->isThisDeclarationADefinition();
1249 if (Kind == Definition)
1250 return 0;
1251 else if (Kind == TentativeDefinition)
1252 LastTentative = *I;
1253 }
1254 return LastTentative;
1255}
1256
1257bool VarDecl::isTentativeDefinitionNow() const {
1258 DefinitionKind Kind = isThisDeclarationADefinition();
1259 if (Kind != TentativeDefinition)
1260 return false;
1261
1262 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1263 if ((*I)->isThisDeclarationADefinition() == Definition)
1264 return false;
1265 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001266 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001267}
1268
Sebastian Redl5ca79842010-02-01 20:16:42 +00001269VarDecl *VarDecl::getDefinition() {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001270 VarDecl *First = getFirstDeclaration();
1271 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1272 I != E; ++I) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001273 if ((*I)->isThisDeclarationADefinition() == Definition)
1274 return *I;
1275 }
1276 return 0;
1277}
1278
John McCall37bb6c92010-10-29 22:22:43 +00001279VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1280 DefinitionKind Kind = DeclarationOnly;
1281
1282 const VarDecl *First = getFirstDeclaration();
1283 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1284 I != E; ++I)
1285 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1286
1287 return Kind;
1288}
1289
Sebastian Redl5ca79842010-02-01 20:16:42 +00001290const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001291 redecl_iterator I = redecls_begin(), E = redecls_end();
1292 while (I != E && !I->getInit())
1293 ++I;
1294
1295 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001296 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001297 return I->getInit();
1298 }
1299 return 0;
1300}
1301
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001302bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001303 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001304 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001305
1306 if (!isStaticDataMember())
1307 return false;
1308
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001309 // If this static data member was instantiated from a static data member of
1310 // a class template, check whether that static data member was defined
1311 // out-of-line.
1312 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1313 return VD->isOutOfLine();
1314
1315 return false;
1316}
1317
Douglas Gregor1d957a32009-10-27 18:42:08 +00001318VarDecl *VarDecl::getOutOfLineDefinition() {
1319 if (!isStaticDataMember())
1320 return 0;
1321
1322 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1323 RD != RDEnd; ++RD) {
1324 if (RD->getLexicalDeclContext()->isFileContext())
1325 return *RD;
1326 }
1327
1328 return 0;
1329}
1330
Douglas Gregord5058122010-02-11 01:19:42 +00001331void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001332 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1333 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001334 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001335 }
1336
1337 Init = I;
1338}
1339
Richard Smithd0b4dd62011-12-19 06:19:21 +00001340/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1341/// form, which contains extra information on the evaluated value of the
1342/// initializer.
1343EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1344 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1345 if (!Eval) {
1346 Stmt *S = Init.get<Stmt *>();
1347 Eval = new (getASTContext()) EvaluatedStmt;
1348 Eval->Value = S;
1349 Init = Eval;
1350 }
1351 return Eval;
1352}
1353
1354bool VarDecl::evaluateValue(
1355 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1356 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1357
1358 // We only produce notes indicating why an initializer is non-constant the
1359 // first time it is evaluated. FIXME: The notes won't always be emitted the
1360 // first time we try evaluation, so might not be produced at all.
1361 if (Eval->WasEvaluated)
1362 return !Eval->Evaluated.isUninit();
1363
1364 const Expr *Init = cast<Expr>(Eval->Value);
1365 assert(!Init->isValueDependent());
1366
1367 if (Eval->IsEvaluating) {
1368 // FIXME: Produce a diagnostic for self-initialization.
1369 Eval->CheckedICE = true;
1370 Eval->IsICE = false;
1371 return false;
1372 }
1373
1374 Eval->IsEvaluating = true;
1375
1376 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1377 this, Notes);
1378
1379 // Ensure the result is an uninitialized APValue if evaluation fails.
1380 if (!Result)
1381 Eval->Evaluated = APValue();
1382
1383 Eval->IsEvaluating = false;
1384 Eval->WasEvaluated = true;
1385
1386 // In C++11, we have determined whether the initializer was a constant
1387 // expression as a side-effect.
1388 if (getASTContext().getLangOptions().CPlusPlus0x && !Eval->CheckedICE) {
1389 Eval->CheckedICE = true;
1390 Eval->IsICE = Notes.empty();
1391 }
1392
1393 return Result;
1394}
1395
1396bool VarDecl::checkInitIsICE() const {
1397 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1398 if (Eval->CheckedICE)
1399 // We have already checked whether this subexpression is an
1400 // integral constant expression.
1401 return Eval->IsICE;
1402
1403 const Expr *Init = cast<Expr>(Eval->Value);
1404 assert(!Init->isValueDependent());
1405
1406 // In C++11, evaluate the initializer to check whether it's a constant
1407 // expression.
1408 if (getASTContext().getLangOptions().CPlusPlus0x) {
1409 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1410 evaluateValue(Notes);
1411 return Eval->IsICE;
1412 }
1413
1414 // It's an ICE whether or not the definition we found is
1415 // out-of-line. See DR 721 and the discussion in Clang PR
1416 // 6206 for details.
1417
1418 if (Eval->CheckingICE)
1419 return false;
1420 Eval->CheckingICE = true;
1421
1422 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1423 Eval->CheckingICE = false;
1424 Eval->CheckedICE = true;
1425 return Eval->IsICE;
1426}
1427
Douglas Gregorfe314812011-06-21 17:03:29 +00001428bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001429 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001430
1431 const Expr *E = getInit();
1432 if (!E)
1433 return false;
1434
1435 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1436 E = Cleanups->getSubExpr();
1437
1438 return isa<MaterializeTemporaryExpr>(E);
1439}
1440
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001441VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001442 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001443 return cast<VarDecl>(MSI->getInstantiatedFrom());
1444
1445 return 0;
1446}
1447
Douglas Gregor3c74d412009-10-14 20:14:33 +00001448TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001449 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001450 return MSI->getTemplateSpecializationKind();
1451
1452 return TSK_Undeclared;
1453}
1454
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001455MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001456 return getASTContext().getInstantiatedFromStaticDataMember(this);
1457}
1458
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001459void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1460 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001461 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001462 assert(MSI && "Not an instantiated static data member?");
1463 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001464 if (TSK != TSK_ExplicitSpecialization &&
1465 PointOfInstantiation.isValid() &&
1466 MSI->getPointOfInstantiation().isInvalid())
1467 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001468}
1469
Sebastian Redl833ef452010-01-26 22:01:41 +00001470//===----------------------------------------------------------------------===//
1471// ParmVarDecl Implementation
1472//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001473
Sebastian Redl833ef452010-01-26 22:01:41 +00001474ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001475 SourceLocation StartLoc,
1476 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001477 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001478 StorageClass S, StorageClass SCAsWritten,
1479 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001480 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001481 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001482}
1483
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001484SourceRange ParmVarDecl::getSourceRange() const {
1485 if (!hasInheritedDefaultArg()) {
1486 SourceRange ArgRange = getDefaultArgRange();
1487 if (ArgRange.isValid())
1488 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1489 }
1490
1491 return DeclaratorDecl::getSourceRange();
1492}
1493
Sebastian Redl833ef452010-01-26 22:01:41 +00001494Expr *ParmVarDecl::getDefaultArg() {
1495 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1496 assert(!hasUninstantiatedDefaultArg() &&
1497 "Default argument is not yet instantiated!");
1498
1499 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001500 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001501 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001502
Sebastian Redl833ef452010-01-26 22:01:41 +00001503 return Arg;
1504}
1505
Sebastian Redl833ef452010-01-26 22:01:41 +00001506SourceRange ParmVarDecl::getDefaultArgRange() const {
1507 if (const Expr *E = getInit())
1508 return E->getSourceRange();
1509
1510 if (hasUninstantiatedDefaultArg())
1511 return getUninstantiatedDefaultArg()->getSourceRange();
1512
1513 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001514}
1515
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001516bool ParmVarDecl::isParameterPack() const {
1517 return isa<PackExpansionType>(getType());
1518}
1519
Ted Kremenek540017e2011-10-06 05:00:56 +00001520void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1521 getASTContext().setParameterIndex(this, parameterIndex);
1522 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1523}
1524
1525unsigned ParmVarDecl::getParameterIndexLarge() const {
1526 return getASTContext().getParameterIndex(this);
1527}
1528
Nuno Lopes394ec982008-12-17 23:39:55 +00001529//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001530// FunctionDecl Implementation
1531//===----------------------------------------------------------------------===//
1532
Douglas Gregorb11aad82011-02-19 18:51:44 +00001533void FunctionDecl::getNameForDiagnostic(std::string &S,
1534 const PrintingPolicy &Policy,
1535 bool Qualified) const {
1536 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1537 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1538 if (TemplateArgs)
1539 S += TemplateSpecializationType::PrintTemplateArgumentList(
1540 TemplateArgs->data(),
1541 TemplateArgs->size(),
1542 Policy);
1543
1544}
1545
Ted Kremenek186a0742010-04-29 16:49:01 +00001546bool FunctionDecl::isVariadic() const {
1547 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1548 return FT->isVariadic();
1549 return false;
1550}
1551
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001552bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1553 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001554 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001555 Definition = *I;
1556 return true;
1557 }
1558 }
1559
1560 return false;
1561}
1562
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001563bool FunctionDecl::hasTrivialBody() const
1564{
1565 Stmt *S = getBody();
1566 if (!S) {
1567 // Since we don't have a body for this function, we don't know if it's
1568 // trivial or not.
1569 return false;
1570 }
1571
1572 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1573 return true;
1574 return false;
1575}
1576
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001577bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1578 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001579 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001580 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1581 return true;
1582 }
1583 }
1584
1585 return false;
1586}
1587
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001588Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00001589 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1590 if (I->Body) {
1591 Definition = *I;
1592 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00001593 } else if (I->IsLateTemplateParsed) {
1594 Definition = *I;
1595 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00001596 }
1597 }
1598
1599 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001600}
1601
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001602void FunctionDecl::setBody(Stmt *B) {
1603 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00001604 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001605 EndRangeLoc = B->getLocEnd();
1606}
1607
Douglas Gregor7d9120c2010-09-28 21:55:22 +00001608void FunctionDecl::setPure(bool P) {
1609 IsPure = P;
1610 if (P)
1611 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1612 Parent->markedVirtualFunctionPure();
1613}
1614
Douglas Gregor16618f22009-09-12 00:17:51 +00001615bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00001616 const TranslationUnitDecl *tunit =
1617 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1618 return tunit &&
Alexis Huntf9933e82011-05-15 20:59:31 +00001619 !tunit->getASTContext().getLangOptions().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00001620 getIdentifier() &&
1621 getIdentifier()->isStr("main");
1622}
1623
1624bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1625 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1626 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1627 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1628 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1629 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1630
1631 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1632 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1633
1634 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1635 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1636
1637 ASTContext &Context =
1638 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1639 ->getASTContext();
1640
1641 // The result type and first argument type are constant across all
1642 // these operators. The second argument must be exactly void*.
1643 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001644}
1645
Douglas Gregor16618f22009-09-12 00:17:51 +00001646bool FunctionDecl::isExternC() const {
1647 ASTContext &Context = getASTContext();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001648 // In C, any non-static, non-overloadable function has external
1649 // linkage.
1650 if (!Context.getLangOptions().CPlusPlus)
John McCall8e7d6562010-08-26 03:08:43 +00001651 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001652
Chandler Carruth4322a282011-02-25 00:05:02 +00001653 const DeclContext *DC = getDeclContext();
1654 if (DC->isRecord())
1655 return false;
1656
1657 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001658 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) {
1659 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
John McCall8e7d6562010-08-26 03:08:43 +00001660 return getStorageClass() != SC_Static &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001661 !getAttr<OverloadableAttr>();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001662
1663 break;
1664 }
1665 }
1666
Douglas Gregorbff62032010-10-21 16:57:46 +00001667 return isMain();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001668}
1669
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001670bool FunctionDecl::isGlobal() const {
1671 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1672 return Method->isStatic();
1673
John McCall8e7d6562010-08-26 03:08:43 +00001674 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001675 return false;
1676
Mike Stump11289f42009-09-09 15:08:12 +00001677 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001678 DC->isNamespace();
1679 DC = DC->getParent()) {
1680 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1681 if (!Namespace->getDeclName())
1682 return false;
1683 break;
1684 }
1685 }
1686
1687 return true;
1688}
1689
Sebastian Redl833ef452010-01-26 22:01:41 +00001690void
1691FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1692 redeclarable_base::setPreviousDeclaration(PrevDecl);
1693
1694 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1695 FunctionTemplateDecl *PrevFunTmpl
1696 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1697 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1698 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1699 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00001700
Axel Naumannfbc7b982011-11-08 18:21:06 +00001701 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00001702 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00001703}
1704
1705const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1706 return getFirstDeclaration();
1707}
1708
1709FunctionDecl *FunctionDecl::getCanonicalDecl() {
1710 return getFirstDeclaration();
1711}
1712
Douglas Gregorbf62d642010-12-06 18:36:25 +00001713void FunctionDecl::setStorageClass(StorageClass SC) {
1714 assert(isLegalForFunction(SC));
1715 if (getStorageClass() != SC)
1716 ClearLinkageCache();
1717
1718 SClass = SC;
1719}
1720
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001721/// \brief Returns a value indicating whether this function
1722/// corresponds to a builtin function.
1723///
1724/// The function corresponds to a built-in function if it is
1725/// declared at translation scope or within an extern "C" block and
1726/// its name matches with the name of a builtin. The returned value
1727/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00001728/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001729/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001730unsigned FunctionDecl::getBuiltinID() const {
1731 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00001732 if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1733 return 0;
1734
1735 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1736 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1737 return BuiltinID;
1738
1739 // This function has the name of a known C library
1740 // function. Determine whether it actually refers to the C library
1741 // function or whether it just has the same name.
1742
Douglas Gregora908e7f2009-02-17 03:23:10 +00001743 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00001744 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00001745 return 0;
1746
Douglas Gregore711f702009-02-14 18:57:46 +00001747 // If this function is at translation-unit scope and we're not in
1748 // C++, it refers to the C library function.
1749 if (!Context.getLangOptions().CPlusPlus &&
1750 getDeclContext()->isTranslationUnit())
1751 return BuiltinID;
1752
1753 // If the function is in an extern "C" linkage specification and is
1754 // not marked "overloadable", it's the real function.
1755 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001756 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00001757 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001758 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00001759 return BuiltinID;
1760
1761 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001762 return 0;
1763}
1764
1765
Chris Lattner47c0d002009-04-25 06:03:53 +00001766/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00001767/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00001768/// after it has been created.
1769unsigned FunctionDecl::getNumParams() const {
John McCall9dd450b2009-09-21 23:43:11 +00001770 const FunctionType *FT = getType()->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001771 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00001772 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001773 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00001774
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001775}
1776
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00001777void FunctionDecl::setParams(ASTContext &C,
David Blaikie9c70e042011-09-21 18:16:56 +00001778 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001779 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00001780 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00001781
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001782 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00001783 if (!NewParamInfo.empty()) {
1784 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1785 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001786 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001787}
Chris Lattner41943152007-01-25 04:52:46 +00001788
Chris Lattner58258242008-04-10 02:22:51 +00001789/// getMinRequiredArguments - Returns the minimum number of arguments
1790/// needed to call this function. This may be fewer than the number of
1791/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00001792/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00001793unsigned FunctionDecl::getMinRequiredArguments() const {
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001794 if (!getASTContext().getLangOptions().CPlusPlus)
1795 return getNumParams();
1796
Douglas Gregor7825bf32011-01-06 22:09:01 +00001797 unsigned NumRequiredArgs = getNumParams();
1798
1799 // If the last parameter is a parameter pack, we don't need an argument for
1800 // it.
1801 if (NumRequiredArgs > 0 &&
1802 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1803 --NumRequiredArgs;
1804
1805 // If this parameter has a default argument, we don't need an argument for
1806 // it.
1807 while (NumRequiredArgs > 0 &&
1808 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00001809 --NumRequiredArgs;
1810
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001811 // We might have parameter packs before the end. These can't be deduced,
1812 // but they can still handle multiple arguments.
1813 unsigned ArgIdx = NumRequiredArgs;
1814 while (ArgIdx > 0) {
1815 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1816 NumRequiredArgs = ArgIdx;
1817
1818 --ArgIdx;
1819 }
1820
Chris Lattner58258242008-04-10 02:22:51 +00001821 return NumRequiredArgs;
1822}
1823
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001824bool FunctionDecl::isInlined() const {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001825 if (IsInline)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001826 return true;
Anders Carlssoncfb65d72009-12-04 22:35:50 +00001827
1828 if (isa<CXXMethodDecl>(this)) {
1829 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1830 return true;
1831 }
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001832
1833 switch (getTemplateSpecializationKind()) {
1834 case TSK_Undeclared:
1835 case TSK_ExplicitSpecialization:
1836 return false;
1837
1838 case TSK_ImplicitInstantiation:
1839 case TSK_ExplicitInstantiationDeclaration:
1840 case TSK_ExplicitInstantiationDefinition:
1841 // Handle below.
1842 break;
1843 }
1844
1845 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001846 bool HasPattern = false;
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001847 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001848 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001849
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001850 if (HasPattern && PatternDecl)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001851 return PatternDecl->isInlined();
1852
1853 return false;
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001854}
1855
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001856/// \brief For a function declaration in C or C++, determine whether this
1857/// declaration causes the definition to be externally visible.
1858///
1859/// Determines whether this is the first non-inline redeclaration of an inline
1860/// function in a language where "inline" does not normally require an
1861/// externally visible definition.
1862bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1863 assert(!doesThisDeclarationHaveABody() &&
1864 "Must have a declaration without a body.");
1865
1866 ASTContext &Context = getASTContext();
1867
1868 // In C99 mode, a function may have an inline definition (causing it to
1869 // be deferred) then redeclared later. As a special case, "extern inline"
1870 // is not required to produce an external symbol.
1871 if (Context.getLangOptions().GNUInline || !Context.getLangOptions().C99 ||
1872 Context.getLangOptions().CPlusPlus)
1873 return false;
1874 if (getLinkage() != ExternalLinkage || isInlineSpecified())
1875 return false;
Nick Lewyckyba4cc012011-07-18 07:11:55 +00001876 const FunctionDecl *Definition = 0;
1877 if (hasBody(Definition))
1878 return Definition->isInlined() &&
1879 Definition->isInlineDefinitionExternallyVisible();
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001880 return false;
1881}
1882
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001883/// \brief For an inline function definition in C or C++, determine whether the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001884/// definition will be externally visible.
1885///
1886/// Inline function definitions are always available for inlining optimizations.
1887/// However, depending on the language dialect, declaration specifiers, and
1888/// attributes, the definition of an inline function may or may not be
1889/// "externally" visible to other translation units in the program.
1890///
1891/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00001892/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001893/// inline definition becomes externally visible (C99 6.7.4p6).
1894///
1895/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1896/// definition, we use the GNU semantics for inline, which are nearly the
1897/// opposite of C99 semantics. In particular, "inline" by itself will create
1898/// an externally visible symbol, but "extern inline" will not create an
1899/// externally visible symbol.
1900bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001901 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001902 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001903 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00001904
Rafael Espindolafb2af642011-06-02 16:13:27 +00001905 if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001906 // If it's not the case that both 'inline' and 'extern' are
1907 // specified on the definition, then this inline definition is
1908 // externally visible.
1909 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
1910 return true;
1911
1912 // If any declaration is 'inline' but not 'extern', then this definition
1913 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00001914 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1915 Redecl != RedeclEnd;
1916 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001917 if (Redecl->isInlineSpecified() &&
1918 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00001919 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00001920 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00001921
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001922 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00001923 }
1924
1925 // C99 6.7.4p6:
1926 // [...] If all of the file scope declarations for a function in a
1927 // translation unit include the inline function specifier without extern,
1928 // then the definition in that translation unit is an inline definition.
1929 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1930 Redecl != RedeclEnd;
1931 ++Redecl) {
1932 // Only consider file-scope declarations in this test.
1933 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1934 continue;
Eli Friedman94ab9302011-10-11 22:09:24 +00001935
1936 // Only consider explicit declarations; the presence of a builtin for a
1937 // libcall shouldn't affect whether a definition is externally visible.
1938 if (Redecl->isImplicit())
1939 continue;
1940
John McCall8e7d6562010-08-26 03:08:43 +00001941 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00001942 return true; // Not an inline definition
1943 }
1944
1945 // C99 6.7.4p6:
1946 // An inline definition does not provide an external definition for the
1947 // function, and does not forbid an external definition in another
1948 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001949 return false;
1950}
1951
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001952/// getOverloadedOperator - Which C++ overloaded operator this
1953/// function represents, if any.
1954OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00001955 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1956 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001957 else
1958 return OO_None;
1959}
1960
Alexis Huntc88db062010-01-13 09:01:02 +00001961/// getLiteralIdentifier - The literal suffix identifier this function
1962/// represents, if any.
1963const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1964 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1965 return getDeclName().getCXXLiteralIdentifier();
1966 else
1967 return 0;
1968}
1969
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00001970FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
1971 if (TemplateOrSpecialization.isNull())
1972 return TK_NonTemplate;
1973 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
1974 return TK_FunctionTemplate;
1975 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
1976 return TK_MemberSpecialization;
1977 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
1978 return TK_FunctionTemplateSpecialization;
1979 if (TemplateOrSpecialization.is
1980 <DependentFunctionTemplateSpecializationInfo*>())
1981 return TK_DependentFunctionTemplateSpecialization;
1982
David Blaikie83d382b2011-09-23 05:06:16 +00001983 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00001984}
1985
Douglas Gregord801b062009-10-07 23:56:10 +00001986FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001987 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00001988 return cast<FunctionDecl>(Info->getInstantiatedFrom());
1989
1990 return 0;
1991}
1992
Douglas Gregor06db9f52009-10-12 20:18:28 +00001993MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
1994 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
1995}
1996
Douglas Gregord801b062009-10-07 23:56:10 +00001997void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00001998FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
1999 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002000 TemplateSpecializationKind TSK) {
2001 assert(TemplateOrSpecialization.isNull() &&
2002 "Member function is already a specialization");
2003 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002004 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002005 TemplateOrSpecialization = Info;
2006}
2007
Douglas Gregorafca3b42009-10-27 20:53:28 +00002008bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002009 // If the function is invalid, it can't be implicitly instantiated.
2010 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002011 return false;
2012
2013 switch (getTemplateSpecializationKind()) {
2014 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002015 case TSK_ExplicitInstantiationDefinition:
2016 return false;
2017
2018 case TSK_ImplicitInstantiation:
2019 return true;
2020
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002021 // It is possible to instantiate TSK_ExplicitSpecialization kind
2022 // if the FunctionDecl has a class scope specialization pattern.
2023 case TSK_ExplicitSpecialization:
2024 return getClassScopeSpecializationPattern() != 0;
2025
Douglas Gregorafca3b42009-10-27 20:53:28 +00002026 case TSK_ExplicitInstantiationDeclaration:
2027 // Handled below.
2028 break;
2029 }
2030
2031 // Find the actual template from which we will instantiate.
2032 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002033 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002034 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002035 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002036
2037 // C++0x [temp.explicit]p9:
2038 // Except for inline functions, other explicit instantiation declarations
2039 // have the effect of suppressing the implicit instantiation of the entity
2040 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002041 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002042 return true;
2043
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002044 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002045}
2046
2047bool FunctionDecl::isTemplateInstantiation() const {
2048 switch (getTemplateSpecializationKind()) {
2049 case TSK_Undeclared:
2050 case TSK_ExplicitSpecialization:
2051 return false;
2052 case TSK_ImplicitInstantiation:
2053 case TSK_ExplicitInstantiationDeclaration:
2054 case TSK_ExplicitInstantiationDefinition:
2055 return true;
2056 }
2057 llvm_unreachable("All TSK values handled.");
2058}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002059
2060FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002061 // Handle class scope explicit specialization special case.
2062 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2063 return getClassScopeSpecializationPattern();
2064
Douglas Gregorafca3b42009-10-27 20:53:28 +00002065 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2066 while (Primary->getInstantiatedFromMemberTemplate()) {
2067 // If we have hit a point where the user provided a specialization of
2068 // this template, we're done looking.
2069 if (Primary->isMemberSpecialization())
2070 break;
2071
2072 Primary = Primary->getInstantiatedFromMemberTemplate();
2073 }
2074
2075 return Primary->getTemplatedDecl();
2076 }
2077
2078 return getInstantiatedFromMemberFunction();
2079}
2080
Douglas Gregor70d83e22009-06-29 17:30:29 +00002081FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002082 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002083 = TemplateOrSpecialization
2084 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002085 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002086 }
2087 return 0;
2088}
2089
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002090FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2091 return getASTContext().getClassScopeSpecializationPattern(this);
2092}
2093
Douglas Gregor70d83e22009-06-29 17:30:29 +00002094const TemplateArgumentList *
2095FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002096 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002097 = TemplateOrSpecialization
2098 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002099 return Info->TemplateArguments;
2100 }
2101 return 0;
2102}
2103
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002104const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002105FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2106 if (FunctionTemplateSpecializationInfo *Info
2107 = TemplateOrSpecialization
2108 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2109 return Info->TemplateArgumentsAsWritten;
2110 }
2111 return 0;
2112}
2113
Mike Stump11289f42009-09-09 15:08:12 +00002114void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002115FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2116 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002117 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002118 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002119 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002120 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2121 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002122 assert(TSK != TSK_Undeclared &&
2123 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002124 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002125 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002126 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002127 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2128 TemplateArgs,
2129 TemplateArgsAsWritten,
2130 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002131 TemplateOrSpecialization = Info;
Mike Stump11289f42009-09-09 15:08:12 +00002132
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002133 // Insert this function template specialization into the set of known
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002134 // function template specializations.
2135 if (InsertPos)
Sebastian Redl9ab988f2011-04-14 14:07:59 +00002136 Template->addSpecialization(Info, InsertPos);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002137 else {
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002138 // Try to insert the new node. If there is an existing node, leave it, the
2139 // set will contain the canonical decls while
2140 // FunctionTemplateDecl::findSpecialization will return
2141 // the most recent redeclarations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002142 FunctionTemplateSpecializationInfo *Existing
2143 = Template->getSpecializations().GetOrInsertNode(Info);
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002144 (void)Existing;
2145 assert((!Existing || Existing->Function->isCanonicalDecl()) &&
2146 "Set is supposed to only contain canonical decls");
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002147 }
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002148}
2149
John McCallb9c78482010-04-08 09:05:18 +00002150void
2151FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2152 const UnresolvedSetImpl &Templates,
2153 const TemplateArgumentListInfo &TemplateArgs) {
2154 assert(TemplateOrSpecialization.isNull());
2155 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2156 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002157 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002158 void *Buffer = Context.Allocate(Size);
2159 DependentFunctionTemplateSpecializationInfo *Info =
2160 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2161 TemplateArgs);
2162 TemplateOrSpecialization = Info;
2163}
2164
2165DependentFunctionTemplateSpecializationInfo::
2166DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2167 const TemplateArgumentListInfo &TArgs)
2168 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2169
2170 d.NumTemplates = Ts.size();
2171 d.NumArgs = TArgs.size();
2172
2173 FunctionTemplateDecl **TsArray =
2174 const_cast<FunctionTemplateDecl**>(getTemplates());
2175 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2176 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2177
2178 TemplateArgumentLoc *ArgsArray =
2179 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2180 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2181 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2182}
2183
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002184TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002185 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002186 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002187 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002188 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002189 if (FTSInfo)
2190 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002191
Douglas Gregord801b062009-10-07 23:56:10 +00002192 MemberSpecializationInfo *MSInfo
2193 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2194 if (MSInfo)
2195 return MSInfo->getTemplateSpecializationKind();
2196
2197 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002198}
2199
Mike Stump11289f42009-09-09 15:08:12 +00002200void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002201FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2202 SourceLocation PointOfInstantiation) {
2203 if (FunctionTemplateSpecializationInfo *FTSInfo
2204 = TemplateOrSpecialization.dyn_cast<
2205 FunctionTemplateSpecializationInfo*>()) {
2206 FTSInfo->setTemplateSpecializationKind(TSK);
2207 if (TSK != TSK_ExplicitSpecialization &&
2208 PointOfInstantiation.isValid() &&
2209 FTSInfo->getPointOfInstantiation().isInvalid())
2210 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2211 } else if (MemberSpecializationInfo *MSInfo
2212 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2213 MSInfo->setTemplateSpecializationKind(TSK);
2214 if (TSK != TSK_ExplicitSpecialization &&
2215 PointOfInstantiation.isValid() &&
2216 MSInfo->getPointOfInstantiation().isInvalid())
2217 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2218 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002219 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002220}
2221
2222SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002223 if (FunctionTemplateSpecializationInfo *FTSInfo
2224 = TemplateOrSpecialization.dyn_cast<
2225 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002226 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002227 else if (MemberSpecializationInfo *MSInfo
2228 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002229 return MSInfo->getPointOfInstantiation();
2230
2231 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002232}
2233
Douglas Gregor6411b922009-09-11 20:15:17 +00002234bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002235 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002236 return true;
2237
2238 // If this function was instantiated from a member function of a
2239 // class template, check whether that member function was defined out-of-line.
2240 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2241 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002242 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002243 return Definition->isOutOfLine();
2244 }
2245
2246 // If this function was instantiated from a function template,
2247 // check whether that function template was defined out-of-line.
2248 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2249 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002250 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002251 return Definition->isOutOfLine();
2252 }
2253
2254 return false;
2255}
2256
Abramo Bagnaraea947882011-03-08 16:41:52 +00002257SourceRange FunctionDecl::getSourceRange() const {
2258 return SourceRange(getOuterLocStart(), EndRangeLoc);
2259}
2260
Chris Lattner59a25942008-03-31 00:36:02 +00002261//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002262// FieldDecl Implementation
2263//===----------------------------------------------------------------------===//
2264
Jay Foad39c79802011-01-12 09:06:06 +00002265FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002266 SourceLocation StartLoc, SourceLocation IdLoc,
2267 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002268 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2269 bool HasInit) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002270 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002271 BW, Mutable, HasInit);
Sebastian Redl833ef452010-01-26 22:01:41 +00002272}
2273
2274bool FieldDecl::isAnonymousStructOrUnion() const {
2275 if (!isImplicit() || getDeclName())
2276 return false;
2277
2278 if (const RecordType *Record = getType()->getAs<RecordType>())
2279 return Record->getDecl()->isAnonymousStructOrUnion();
2280
2281 return false;
2282}
2283
Richard Smithcaf33902011-10-10 18:28:20 +00002284unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2285 assert(isBitField() && "not a bitfield");
2286 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2287 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2288}
2289
John McCall4e819612011-01-20 07:57:12 +00002290unsigned FieldDecl::getFieldIndex() const {
2291 if (CachedFieldIndex) return CachedFieldIndex - 1;
2292
Richard Smithd62306a2011-11-10 06:34:14 +00002293 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002294 const RecordDecl *RD = getParent();
2295 const FieldDecl *LastFD = 0;
2296 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
Richard Smithd62306a2011-11-10 06:34:14 +00002297
2298 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2299 I != E; ++I, ++Index) {
2300 (*I)->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002301
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002302 if (IsMsStruct) {
2303 // Zero-length bitfields following non-bitfield members are ignored.
Richard Smithd62306a2011-11-10 06:34:14 +00002304 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
2305 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002306 continue;
2307 }
Richard Smithd62306a2011-11-10 06:34:14 +00002308 LastFD = (*I);
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002309 }
John McCall4e819612011-01-20 07:57:12 +00002310 }
2311
Richard Smithd62306a2011-11-10 06:34:14 +00002312 assert(CachedFieldIndex && "failed to find field in parent");
2313 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002314}
2315
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002316SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002317 if (const Expr *E = InitializerOrBitWidth.getPointer())
2318 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002319 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002320}
2321
Richard Smith938f40b2011-06-11 17:19:42 +00002322void FieldDecl::setInClassInitializer(Expr *Init) {
2323 assert(!InitializerOrBitWidth.getPointer() &&
2324 "bit width or initializer already set");
2325 InitializerOrBitWidth.setPointer(Init);
2326 InitializerOrBitWidth.setInt(0);
2327}
2328
Sebastian Redl833ef452010-01-26 22:01:41 +00002329//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002330// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002331//===----------------------------------------------------------------------===//
2332
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002333SourceLocation TagDecl::getOuterLocStart() const {
2334 return getTemplateOrInnerLocStart(this);
2335}
2336
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002337SourceRange TagDecl::getSourceRange() const {
2338 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002339 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002340}
2341
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002342TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002343 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002344}
2345
Richard Smithdda56e42011-04-15 14:24:37 +00002346void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2347 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002348 if (TypeForDecl)
John McCall424cec92011-01-19 06:33:43 +00002349 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002350 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002351}
2352
Douglas Gregordee1be82009-01-17 00:42:38 +00002353void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002354 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002355
2356 if (isa<CXXRecordDecl>(this)) {
2357 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2358 struct CXXRecordDecl::DefinitionData *Data =
2359 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002360 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2361 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002362 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002363}
2364
2365void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002366 assert((!isa<CXXRecordDecl>(this) ||
2367 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2368 "definition completed but not started");
2369
John McCallf937c022011-10-07 06:10:15 +00002370 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002371 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002372
2373 if (ASTMutationListener *L = getASTMutationListener())
2374 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002375}
2376
John McCallf937c022011-10-07 06:10:15 +00002377TagDecl *TagDecl::getDefinition() const {
2378 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002379 return const_cast<TagDecl *>(this);
Andrew Trickba266ee2010-10-19 21:54:32 +00002380 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2381 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002382
2383 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002384 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002385 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002386 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002387
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002388 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002389}
2390
Douglas Gregor14454802011-02-25 02:25:35 +00002391void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2392 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002393 // Make sure the extended qualifier info is allocated.
2394 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002395 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002396 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002397 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002398 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002399 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002400 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002401 if (getExtInfo()->NumTemplParamLists == 0) {
2402 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002403 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002404 }
2405 else
2406 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002407 }
2408 }
2409}
2410
Abramo Bagnara60804e12011-03-18 15:16:37 +00002411void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2412 unsigned NumTPLists,
2413 TemplateParameterList **TPLists) {
2414 assert(NumTPLists > 0);
2415 // Make sure the extended decl info is allocated.
2416 if (!hasExtInfo())
2417 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002418 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002419 // Set the template parameter lists info.
2420 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2421}
2422
Ted Kremenek21475702008-09-05 17:16:31 +00002423//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002424// EnumDecl Implementation
2425//===----------------------------------------------------------------------===//
2426
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002427EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2428 SourceLocation StartLoc, SourceLocation IdLoc,
2429 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002430 EnumDecl *PrevDecl, bool IsScoped,
2431 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002432 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002433 IsScoped, IsScopedUsingClassTag, IsFixed);
Sebastian Redl833ef452010-01-26 22:01:41 +00002434 C.getTypeDeclType(Enum, PrevDecl);
2435 return Enum;
2436}
2437
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002438EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002439 return new (C) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002440 false, false, false);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002441}
2442
Douglas Gregord5058122010-02-11 01:19:42 +00002443void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002444 QualType NewPromotionType,
2445 unsigned NumPositiveBits,
2446 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002447 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002448 if (!IntegerType)
2449 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002450 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002451 setNumPositiveBits(NumPositiveBits);
2452 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002453 TagDecl::completeDefinition();
2454}
2455
2456//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002457// RecordDecl Implementation
2458//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00002459
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002460RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2461 SourceLocation StartLoc, SourceLocation IdLoc,
2462 IdentifierInfo *Id, RecordDecl *PrevDecl)
2463 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00002464 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002465 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002466 HasObjectMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002467 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00002468 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00002469}
2470
Jay Foad39c79802011-01-12 09:06:06 +00002471RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002472 SourceLocation StartLoc, SourceLocation IdLoc,
2473 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2474 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2475 PrevDecl);
Ted Kremenek21475702008-09-05 17:16:31 +00002476 C.getTypeDeclType(R, PrevDecl);
2477 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00002478}
2479
Jay Foad39c79802011-01-12 09:06:06 +00002480RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002481 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2482 SourceLocation(), 0, 0);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002483}
2484
Douglas Gregordfcad112009-03-25 15:59:44 +00002485bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00002486 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00002487 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2488}
2489
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002490RecordDecl::field_iterator RecordDecl::field_begin() const {
2491 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2492 LoadFieldsFromExternalStorage();
2493
2494 return field_iterator(decl_iterator(FirstDecl));
2495}
2496
Douglas Gregorb11aad82011-02-19 18:51:44 +00002497/// completeDefinition - Notes that the definition of this type is now
2498/// complete.
2499void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00002500 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00002501 TagDecl::completeDefinition();
2502}
2503
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002504void RecordDecl::LoadFieldsFromExternalStorage() const {
2505 ExternalASTSource *Source = getASTContext().getExternalSource();
2506 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2507
2508 // Notify that we have a RecordDecl doing some initialization.
2509 ExternalASTSource::Deserializing TheFields(Source);
2510
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002511 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002512 LoadedFieldsFromExternalStorage = true;
2513 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2514 case ELR_Success:
2515 break;
2516
2517 case ELR_AlreadyLoaded:
2518 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002519 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002520 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002521
2522#ifndef NDEBUG
2523 // Check that all decls we got were FieldDecls.
2524 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2525 assert(isa<FieldDecl>(Decls[i]));
2526#endif
2527
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002528 if (Decls.empty())
2529 return;
2530
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00002531 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2532 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002533}
2534
Steve Naroff415d3d52008-10-08 17:01:13 +00002535//===----------------------------------------------------------------------===//
2536// BlockDecl Implementation
2537//===----------------------------------------------------------------------===//
2538
David Blaikie9c70e042011-09-21 18:16:56 +00002539void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00002540 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00002541
Steve Naroffc4b30e52009-03-13 16:56:44 +00002542 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002543 if (!NewParamInfo.empty()) {
2544 NumParams = NewParamInfo.size();
2545 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2546 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002547 }
2548}
2549
John McCall351762c2011-02-07 10:33:21 +00002550void BlockDecl::setCaptures(ASTContext &Context,
2551 const Capture *begin,
2552 const Capture *end,
2553 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00002554 CapturesCXXThis = capturesCXXThis;
2555
2556 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00002557 NumCaptures = 0;
2558 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00002559 return;
2560 }
2561
John McCall351762c2011-02-07 10:33:21 +00002562 NumCaptures = end - begin;
2563
2564 // Avoid new Capture[] because we don't want to provide a default
2565 // constructor.
2566 size_t allocationSize = NumCaptures * sizeof(Capture);
2567 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2568 memcpy(buffer, begin, allocationSize);
2569 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002570}
Sebastian Redl833ef452010-01-26 22:01:41 +00002571
John McCallce45f882011-06-15 22:51:16 +00002572bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2573 for (capture_const_iterator
2574 i = capture_begin(), e = capture_end(); i != e; ++i)
2575 // Only auto vars can be captured, so no redeclaration worries.
2576 if (i->getVariable() == variable)
2577 return true;
2578
2579 return false;
2580}
2581
Douglas Gregor70226da2010-12-21 16:27:07 +00002582SourceRange BlockDecl::getSourceRange() const {
2583 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2584}
Sebastian Redl833ef452010-01-26 22:01:41 +00002585
2586//===----------------------------------------------------------------------===//
2587// Other Decl Allocation/Deallocation Method Implementations
2588//===----------------------------------------------------------------------===//
2589
2590TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2591 return new (C) TranslationUnitDecl(C);
2592}
2593
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002594LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002595 SourceLocation IdentL, IdentifierInfo *II) {
2596 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2597}
2598
2599LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2600 SourceLocation IdentL, IdentifierInfo *II,
2601 SourceLocation GnuLabelL) {
2602 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2603 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002604}
2605
2606
Sebastian Redl833ef452010-01-26 22:01:41 +00002607NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00002608 SourceLocation StartLoc,
2609 SourceLocation IdLoc, IdentifierInfo *Id) {
2610 return new (C) NamespaceDecl(DC, StartLoc, IdLoc, Id);
Sebastian Redl833ef452010-01-26 22:01:41 +00002611}
2612
Douglas Gregor417e87c2010-10-27 19:49:05 +00002613NamespaceDecl *NamespaceDecl::getNextNamespace() {
2614 return dyn_cast_or_null<NamespaceDecl>(
2615 NextNamespace.get(getASTContext().getExternalSource()));
2616}
2617
Sebastian Redl833ef452010-01-26 22:01:41 +00002618ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002619 SourceLocation IdLoc,
2620 IdentifierInfo *Id,
2621 QualType Type) {
2622 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00002623}
2624
2625FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002626 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002627 const DeclarationNameInfo &NameInfo,
2628 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002629 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00002630 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00002631 bool hasWrittenPrototype,
2632 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002633 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2634 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00002635 isInlineSpecified,
2636 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00002637 New->HasWrittenPrototype = hasWrittenPrototype;
2638 return New;
2639}
2640
2641BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2642 return new (C) BlockDecl(DC, L);
2643}
2644
2645EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2646 SourceLocation L,
2647 IdentifierInfo *Id, QualType T,
2648 Expr *E, const llvm::APSInt &V) {
2649 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2650}
2651
Benjamin Kramer39593702010-11-21 14:11:41 +00002652IndirectFieldDecl *
2653IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2654 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2655 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00002656 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2657}
2658
Douglas Gregorbe996932010-09-01 20:41:53 +00002659SourceRange EnumConstantDecl::getSourceRange() const {
2660 SourceLocation End = getLocation();
2661 if (Init)
2662 End = Init->getLocEnd();
2663 return SourceRange(getLocation(), End);
2664}
2665
Sebastian Redl833ef452010-01-26 22:01:41 +00002666TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00002667 SourceLocation StartLoc, SourceLocation IdLoc,
2668 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2669 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00002670}
2671
Richard Smithdda56e42011-04-15 14:24:37 +00002672TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2673 SourceLocation StartLoc,
2674 SourceLocation IdLoc, IdentifierInfo *Id,
2675 TypeSourceInfo *TInfo) {
2676 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2677}
2678
Abramo Bagnaraea947882011-03-08 16:41:52 +00002679SourceRange TypedefDecl::getSourceRange() const {
2680 SourceLocation RangeEnd = getLocation();
2681 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2682 if (typeIsPostfix(TInfo->getType()))
2683 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2684 }
2685 return SourceRange(getLocStart(), RangeEnd);
2686}
2687
Richard Smithdda56e42011-04-15 14:24:37 +00002688SourceRange TypeAliasDecl::getSourceRange() const {
2689 SourceLocation RangeEnd = getLocStart();
2690 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2691 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2692 return SourceRange(getLocStart(), RangeEnd);
2693}
2694
Sebastian Redl833ef452010-01-26 22:01:41 +00002695FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00002696 StringLiteral *Str,
2697 SourceLocation AsmLoc,
2698 SourceLocation RParenLoc) {
2699 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00002700}
Douglas Gregorba345522011-12-02 23:23:56 +00002701
2702//===----------------------------------------------------------------------===//
2703// ImportDecl Implementation
2704//===----------------------------------------------------------------------===//
2705
2706/// \brief Retrieve the number of module identifiers needed to name the given
2707/// module.
2708static unsigned getNumModuleIdentifiers(Module *Mod) {
2709 unsigned Result = 1;
2710 while (Mod->Parent) {
2711 Mod = Mod->Parent;
2712 ++Result;
2713 }
2714 return Result;
2715}
2716
2717ImportDecl::ImportDecl(DeclContext *DC, SourceLocation ImportLoc,
2718 Module *Imported,
2719 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002720 : Decl(Import, DC, ImportLoc), ImportedAndComplete(Imported, true),
2721 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002722{
2723 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
2724 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
2725 memcpy(StoredLocs, IdentifierLocs.data(),
2726 IdentifierLocs.size() * sizeof(SourceLocation));
2727}
2728
2729ImportDecl::ImportDecl(DeclContext *DC, SourceLocation ImportLoc,
2730 Module *Imported, SourceLocation EndLoc)
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002731 : Decl(Import, DC, ImportLoc), ImportedAndComplete(Imported, false),
2732 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002733{
2734 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
2735}
2736
2737ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
2738 SourceLocation ImportLoc, Module *Imported,
2739 ArrayRef<SourceLocation> IdentifierLocs) {
2740 void *Mem = C.Allocate(sizeof(ImportDecl) +
2741 IdentifierLocs.size() * sizeof(SourceLocation));
2742 return new (Mem) ImportDecl(DC, ImportLoc, Imported, IdentifierLocs);
2743}
2744
2745ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
2746 SourceLocation ImportLoc,
2747 Module *Imported,
2748 SourceLocation EndLoc) {
2749 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregorbcfc7d02011-12-02 23:42:12 +00002750 ImportDecl *Import = new (Mem) ImportDecl(DC, ImportLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00002751 Import->setImplicit();
2752 return Import;
2753}
2754
2755ImportDecl *ImportDecl::CreateEmpty(ASTContext &C, unsigned NumLocations) {
2756 void *Mem = C.Allocate(sizeof(ImportDecl) +
2757 NumLocations * sizeof(SourceLocation));
2758 return new (Mem) ImportDecl(EmptyShell());
2759}
2760
2761ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
2762 if (!ImportedAndComplete.getInt())
2763 return ArrayRef<SourceLocation>();
2764
2765 const SourceLocation *StoredLocs
2766 = reinterpret_cast<const SourceLocation *>(this + 1);
2767 return ArrayRef<SourceLocation>(StoredLocs,
2768 getNumModuleIdentifiers(getImportedModule()));
2769}
2770
2771SourceRange ImportDecl::getSourceRange() const {
2772 if (!ImportedAndComplete.getInt())
2773 return SourceRange(getLocation(),
2774 *reinterpret_cast<const SourceLocation *>(this + 1));
2775
2776 return SourceRange(getLocation(), getIdentifierLocs().back());
2777}