blob: 312426134fc18064f4bd3680f958af9eeb93d737 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidise184bae2008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattner6c2b6eb2008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
Nuno Lopes99f06ba2008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson337cba42009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregord249e1d1f2009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000024#include "clang/AST/Stmt.h"
25#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000027#include "clang/Basic/IdentifierTable.h"
Douglas Gregor15de72c2011-12-02 23:23:56 +000028#include "clang/Basic/Module.h"
Abramo Bagnara465d41b2010-05-11 21:36:43 +000029#include "clang/Basic/Specifiers.h"
Douglas Gregor4421d2b2011-03-26 12:10:19 +000030#include "clang/Basic/TargetInfo.h"
John McCallf1bbbb42009-09-04 01:14:41 +000031#include "llvm/Support/ErrorHandling.h"
David Blaikie4278c652011-09-21 18:16:56 +000032#include <algorithm>
33
Reid Spencer5f016e22007-07-11 17:01:13 +000034using namespace clang;
35
Chris Lattnerd3b90652008-03-15 05:43:15 +000036//===----------------------------------------------------------------------===//
Douglas Gregor4afa39d2009-01-20 01:17:11 +000037// NamedDecl Implementation
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000038//===----------------------------------------------------------------------===//
39
John McCall5a758de2013-02-16 00:17:33 +000040// Visibility rules aren't rigorously externally specified, but here
41// are the basic principles behind what we implement:
42//
43// 1. An explicit visibility attribute is generally a direct expression
44// of the user's intent and should be honored. Only the innermost
45// visibility attribute applies. If no visibility attribute applies,
46// global visibility settings are considered.
47//
48// 2. There is one caveat to the above: on or in a template pattern,
49// an explicit visibility attribute is just a default rule, and
50// visibility can be decreased by the visibility of template
51// arguments. But this, too, has an exception: an attribute on an
52// explicit specialization or instantiation causes all the visibility
53// restrictions of the template arguments to be ignored.
54//
55// 3. A variable that does not otherwise have explicit visibility can
56// be restricted by the visibility of its type.
57//
58// 4. A visibility restriction is explicit if it comes from an
59// attribute (or something like it), not a global visibility setting.
60// When emitting a reference to an external symbol, visibility
61// restrictions are ignored unless they are explicit.
John McCalld4c3d662013-02-20 01:54:26 +000062//
63// 5. When computing the visibility of a non-type, including a
64// non-type member of a class, only non-type visibility restrictions
65// are considered: the 'visibility' attribute, global value-visibility
66// settings, and a few special cases like __private_extern.
67//
68// 6. When computing the visibility of a type, including a type member
69// of a class, only type visibility restrictions are considered:
70// the 'type_visibility' attribute and global type-visibility settings.
71// However, a 'visibility' attribute counts as a 'type_visibility'
72// attribute on any declaration that only has the former.
73//
74// The visibility of a "secondary" entity, like a template argument,
75// is computed using the kind of that entity, not the kind of the
76// primary entity for which we are computing visibility. For example,
77// the visibility of a specialization of either of these templates:
78// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
79// template <class T, bool (&compare)(T, X)> class matcher;
80// is restricted according to the type visibility of the argument 'T',
81// the type visibility of 'bool(&)(T,X)', and the value visibility of
82// the argument function 'compare'. That 'has_match' is a value
83// and 'matcher' is a type only matters when looking for attributes
84// and settings from the immediate context.
John McCall5a758de2013-02-16 00:17:33 +000085
86/// Kinds of LV computation. The linkage side of the computation is
87/// always the same, but different things can change how visibility is
88/// computed.
89enum LVComputationKind {
John McCall5a758de2013-02-16 00:17:33 +000090 /// Do a normal LV computation for, ultimately, a type.
John McCalld4c3d662013-02-20 01:54:26 +000091 LVForType = NamedDecl::VisibilityForType,
John McCall5a758de2013-02-16 00:17:33 +000092
John McCalld4c3d662013-02-20 01:54:26 +000093 /// Do a normal LV computation for, ultimately, a non-type declaration.
94 LVForValue = NamedDecl::VisibilityForValue,
95
96 /// Do a normal LV computation for, ultimately, a type that already
97 /// has some sort of explicit visibility.
98 LVForExplicitType,
99
100 /// Do a normal LV computation for, ultimately, a non-type declaration
101 /// that already has some sort of explicit visibility.
102 LVForExplicitValue
John McCall5a758de2013-02-16 00:17:33 +0000103};
104
John McCalld4c3d662013-02-20 01:54:26 +0000105/// Does this computation kind permit us to consider additional
106/// visibility settings from attributes and the like?
107static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
108 return ((unsigned(computation) & 2) != 0);
109}
110
111/// Given an LVComputationKind, return one of the same type/value sort
112/// that records that it already has explicit visibility.
113static LVComputationKind
114withExplicitVisibilityAlready(LVComputationKind oldKind) {
115 LVComputationKind newKind =
116 static_cast<LVComputationKind>(unsigned(oldKind) | 2);
117 assert(oldKind != LVForType || newKind == LVForExplicitType);
118 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
119 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
120 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
121 return newKind;
122}
123
David Blaikiedc84cd52013-02-20 22:23:23 +0000124static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
125 LVComputationKind kind) {
John McCalld4c3d662013-02-20 01:54:26 +0000126 assert(!hasExplicitVisibilityAlready(kind) &&
127 "asking for explicit visibility when we shouldn't be");
128 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
129}
130
John McCall5a758de2013-02-16 00:17:33 +0000131typedef NamedDecl::LinkageInfo LinkageInfo;
132
133/// Is the given declaration a "type" or a "value" for the purposes of
134/// visibility computation?
135static bool usesTypeVisibility(const NamedDecl *D) {
John McCalla880b192013-02-19 01:57:35 +0000136 return isa<TypeDecl>(D) ||
137 isa<ClassTemplateDecl>(D) ||
138 isa<ObjCInterfaceDecl>(D);
John McCall5a758de2013-02-16 00:17:33 +0000139}
140
John McCalld4c3d662013-02-20 01:54:26 +0000141/// Given a visibility attribute, return the explicit visibility
142/// associated with it.
143template <class T>
144static Visibility getVisibilityFromAttr(const T *attr) {
145 switch (attr->getVisibility()) {
146 case T::Default:
147 return DefaultVisibility;
148 case T::Hidden:
149 return HiddenVisibility;
150 case T::Protected:
151 return ProtectedVisibility;
152 }
153 llvm_unreachable("bad visibility kind");
154}
155
John McCall5a758de2013-02-16 00:17:33 +0000156/// Return the explicit visibility of the given declaration.
David Blaikiedc84cd52013-02-20 22:23:23 +0000157static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld4c3d662013-02-20 01:54:26 +0000158 NamedDecl::ExplicitVisibilityKind kind) {
159 // If we're ultimately computing the visibility of a type, look for
160 // a 'type_visibility' attribute before looking for 'visibility'.
161 if (kind == NamedDecl::VisibilityForType) {
162 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
163 return getVisibilityFromAttr(A);
164 }
165 }
166
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000167 // If this declaration has an explicit visibility attribute, use it.
168 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld4c3d662013-02-20 01:54:26 +0000169 return getVisibilityFromAttr(A);
John McCall1fb0caa2010-10-22 21:05:15 +0000170 }
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000171
172 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
173 // implies visibility(default).
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000174 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000175 for (specific_attr_iterator<AvailabilityAttr>
176 A = D->specific_attr_begin<AvailabilityAttr>(),
177 AEnd = D->specific_attr_end<AvailabilityAttr>();
178 A != AEnd; ++A)
179 if ((*A)->getPlatform()->getName().equals("macosx"))
180 return DefaultVisibility;
181 }
182
David Blaikie66874fb2013-02-21 01:47:18 +0000183 return None;
John McCall1fb0caa2010-10-22 21:05:15 +0000184}
185
Rafael Espindola093ecc92012-01-14 00:30:36 +0000186static LinkageInfo getLVForType(QualType T) {
187 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
188 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
189}
190
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000191/// \brief Get the most restrictive linkage for the types in the given
John McCall5a758de2013-02-16 00:17:33 +0000192/// template parameter list. For visibility purposes, template
193/// parameters are part of the signature of a template.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000194static LinkageInfo
John McCall5a758de2013-02-16 00:17:33 +0000195getLVForTemplateParameterList(const TemplateParameterList *params) {
196 LinkageInfo LV;
197 for (TemplateParameterList::const_iterator P = params->begin(),
198 PEnd = params->end();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000199 P != PEnd; ++P) {
John McCall5a758de2013-02-16 00:17:33 +0000200
201 // Template type parameters are the most common and never
202 // contribute to visibility, pack or not.
203 if (isa<TemplateTypeParmDecl>(*P))
204 continue;
205
206 // Non-type template parameters can be restricted by the value type, e.g.
207 // template <enum X> class A { ... };
208 // We have to be careful here, though, because we can be dealing with
209 // dependent types.
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000210 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCall5a758de2013-02-16 00:17:33 +0000211 // Handle the non-pack case first.
212 if (!NTTP->isExpandedParameterPack()) {
213 if (!NTTP->getType()->isDependentType()) {
214 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000215 }
216 continue;
217 }
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000218
John McCall5a758de2013-02-16 00:17:33 +0000219 // Look at all the types in an expanded pack.
220 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
221 QualType type = NTTP->getExpansionType(i);
222 if (!type->isDependentType())
223 LV.merge(getLVForType(type));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000224 }
John McCall5a758de2013-02-16 00:17:33 +0000225 continue;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000226 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000227
John McCall5a758de2013-02-16 00:17:33 +0000228 // Template template parameters can be restricted by their
229 // template parameters, recursively.
230 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
231
232 // Handle the non-pack case first.
233 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000234 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
John McCall5a758de2013-02-16 00:17:33 +0000235 continue;
236 }
237
238 // Look at all expansions in an expanded pack.
239 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
240 i != n; ++i) {
241 LV.merge(getLVForTemplateParameterList(
242 TTP->getExpansionTemplateParameters(i)));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000243 }
244 }
245
John McCall1fb0caa2010-10-22 21:05:15 +0000246 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000247}
248
Rafael Espindola838dc592013-01-12 06:42:30 +0000249/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCall5a758de2013-02-16 00:17:33 +0000250static LinkageInfo getLVForDecl(const NamedDecl *D,
251 LVComputationKind computation);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000252
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000253/// \brief Get the most restrictive linkage for the types and
254/// declarations in the given template argument list.
John McCall5a758de2013-02-16 00:17:33 +0000255///
256/// Note that we don't take an LVComputationKind because we always
257/// want to honor the visibility of template arguments in the same way.
258static LinkageInfo
259getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
260 LinkageInfo LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000261
John McCall5a758de2013-02-16 00:17:33 +0000262 for (unsigned i = 0, e = args.size(); i != e; ++i) {
263 const TemplateArgument &arg = args[i];
264 switch (arg.getKind()) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000265 case TemplateArgument::Null:
266 case TemplateArgument::Integral:
267 case TemplateArgument::Expression:
John McCall5a758de2013-02-16 00:17:33 +0000268 continue;
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000269
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000270 case TemplateArgument::Type:
John McCall5a758de2013-02-16 00:17:33 +0000271 LV.merge(getLVForType(arg.getAsType()));
272 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000273
274 case TemplateArgument::Declaration:
John McCall5a758de2013-02-16 00:17:33 +0000275 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
276 assert(!usesTypeVisibility(ND));
277 LV.merge(getLVForDecl(ND, LVForValue));
278 }
279 continue;
Eli Friedmand7a6b162012-09-26 02:36:12 +0000280
281 case TemplateArgument::NullPtr:
John McCall5a758de2013-02-16 00:17:33 +0000282 LV.merge(getLVForType(arg.getNullPtrType()));
283 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000284
285 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +0000286 case TemplateArgument::TemplateExpansion:
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000287 if (TemplateDecl *Template
John McCall5a758de2013-02-16 00:17:33 +0000288 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
289 LV.merge(getLVForDecl(Template, LVForValue));
290 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000291
292 case TemplateArgument::Pack:
John McCall5a758de2013-02-16 00:17:33 +0000293 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
294 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000295 }
John McCall5a758de2013-02-16 00:17:33 +0000296 llvm_unreachable("bad template argument kind");
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000297 }
298
John McCall1fb0caa2010-10-22 21:05:15 +0000299 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000300}
301
Rafael Espindola093ecc92012-01-14 00:30:36 +0000302static LinkageInfo
John McCall5a758de2013-02-16 00:17:33 +0000303getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
304 return getLVForTemplateArgumentList(TArgs.asArray());
John McCall3cdfc4d2010-08-13 08:35:10 +0000305}
306
John McCall5a758de2013-02-16 00:17:33 +0000307/// Merge in template-related linkage and visibility for the given
308/// function template specialization.
309///
310/// We don't need a computation kind here because we can assume
311/// LVForValue.
312static void mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
313 const FunctionTemplateSpecializationInfo *specInfo) {
314 bool hasExplicitVisibility = fn->hasAttr<VisibilityAttr>();
315 FunctionTemplateDecl *temp = specInfo->getTemplate();
316
317 // Include visibility from the template parameters and arguments
318 // only if this is not an explicit instantiation or specialization
319 // with direct explicit visibility. (Implicit instantiations won't
320 // have a direct attribute.)
321 bool considerVisibility = !hasExplicitVisibility;
322
323 // Merge information from the template parameters.
324 LinkageInfo tempLV =
325 getLVForTemplateParameterList(temp->getTemplateParameters());
326 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
327
328 // Merge information from the template arguments.
329 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
330 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
331 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCall6ce51ee2011-06-27 23:06:04 +0000332}
333
John McCalld4c3d662013-02-20 01:54:26 +0000334/// Should we consider visibility associated with the template
335/// arguments and parameters of the given class template specialization?
336static bool shouldConsiderTemplateVisibility(
337 const ClassTemplateSpecializationDecl *spec,
338 LVComputationKind computation) {
John McCall5a758de2013-02-16 00:17:33 +0000339 // Include visibility from the template parameters and arguments
340 // only if this is not an explicit instantiation or specialization
341 // with direct explicit visibility (and note that implicit
342 // instantiations won't have a direct attribute).
343 //
344 // Furthermore, we want to ignore template parameters and arguments
John McCalld4c3d662013-02-20 01:54:26 +0000345 // for an explicit specialization when computing the visibility of a
346 // member thereof with explicit visibility.
John McCall5a758de2013-02-16 00:17:33 +0000347 //
348 // This is a bit complex; let's unpack it.
349 //
350 // An explicit class specialization is an independent, top-level
351 // declaration. As such, if it or any of its members has an
352 // explicit visibility attribute, that must directly express the
353 // user's intent, and we should honor it. The same logic applies to
354 // an explicit instantiation of a member of such a thing.
John McCalld4c3d662013-02-20 01:54:26 +0000355
356 // Fast path: if this is not an explicit instantiation or
357 // specialization, we always want to consider template-related
358 // visibility restrictions.
359 if (!spec->isExplicitInstantiationOrSpecialization())
360 return true;
361
362 // This is the 'member thereof' check.
363 if (spec->isExplicitSpecialization() &&
364 hasExplicitVisibilityAlready(computation))
365 return false;
366
367 // Otherwise, look to see if we have an attribute.
368 switch (computation) {
369 case LVForType:
370 case LVForExplicitType:
371 if (spec->hasAttr<TypeVisibilityAttr>())
372 return false;
373 // fallthrough
374 case LVForValue:
375 case LVForExplicitValue:
376 if (spec->hasAttr<VisibilityAttr>())
377 return false;
378 return true;
379 }
380 llvm_unreachable("bad visibility computation kind");
381}
382
383/// Merge in template-related linkage and visibility for the given
384/// class template specialization.
385static void mergeTemplateLV(LinkageInfo &LV,
386 const ClassTemplateSpecializationDecl *spec,
387 LVComputationKind computation) {
388 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCall5a758de2013-02-16 00:17:33 +0000389
390 // Merge information from the template parameters, but ignore
391 // visibility if we're only considering template arguments.
392
John McCalld4c3d662013-02-20 01:54:26 +0000393 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCall5a758de2013-02-16 00:17:33 +0000394 LinkageInfo tempLV =
395 getLVForTemplateParameterList(temp->getTemplateParameters());
396 LV.mergeMaybeWithVisibility(tempLV,
John McCalld4c3d662013-02-20 01:54:26 +0000397 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCall5a758de2013-02-16 00:17:33 +0000398
399 // Merge information from the template arguments. We ignore
400 // template-argument visibility if we've got an explicit
401 // instantiation with a visibility attribute.
402 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
403 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
404 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCall6ce51ee2011-06-27 23:06:04 +0000405}
406
Rafael Espindolab04b7312012-07-13 14:25:36 +0000407static bool useInlineVisibilityHidden(const NamedDecl *D) {
408 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola0bab9da2012-07-13 23:26:43 +0000409 const LangOptions &Opts = D->getASTContext().getLangOpts();
410 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolab04b7312012-07-13 14:25:36 +0000411 return false;
412
413 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
414 if (!FD)
415 return false;
416
417 TemplateSpecializationKind TSK = TSK_Undeclared;
418 if (FunctionTemplateSpecializationInfo *spec
419 = FD->getTemplateSpecializationInfo()) {
420 TSK = spec->getTemplateSpecializationKind();
421 } else if (MemberSpecializationInfo *MSI =
422 FD->getMemberSpecializationInfo()) {
423 TSK = MSI->getTemplateSpecializationKind();
424 }
425
426 const FunctionDecl *Def = 0;
427 // InlineVisibilityHidden only applies to definitions, and
428 // isInlined() only gives meaningful answers on definitions
429 // anyway.
430 return TSK != TSK_ExplicitInstantiationDeclaration &&
431 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindola0142f0c2012-10-11 16:32:25 +0000432 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolab04b7312012-07-13 14:25:36 +0000433}
434
Benjamin Kramera574c892013-02-15 12:30:38 +0000435template <typename T> static bool isInExternCContext(T *D) {
Rafael Espindola950fee22013-02-14 01:18:37 +0000436 const T *First = D->getFirstDeclaration();
437 return First->getDeclContext()->isExternCContext();
438}
439
Rafael Espindola1266b612012-04-21 23:28:21 +0000440static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCall5a758de2013-02-16 00:17:33 +0000441 LVComputationKind computation) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000442 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregord85b5b92009-11-25 22:24:25 +0000443 "Not a name having namespace scope");
444 ASTContext &Context = D->getASTContext();
445
446 // C++ [basic.link]p3:
447 // A name having namespace scope (3.3.6) has internal linkage if it
448 // is the name of
449 // - an object, reference, function or function template that is
450 // explicitly declared static; or,
451 // (This bullet corresponds to C99 6.2.2p3.)
452 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
453 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000454 if (Var->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000455 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000456
Richard Smith820e9a72012-10-19 06:37:48 +0000457 // - a non-volatile object or reference that is explicitly declared const
458 // or constexpr and neither explicitly declared extern nor previously
459 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikie4e4d0842012-03-11 07:00:24 +0000460 if (Context.getLangOpts().CPlusPlus &&
Richard Smith820e9a72012-10-19 06:37:48 +0000461 Var->getType().isConstQualified() &&
462 !Var->getType().isVolatileQualified() &&
John McCalld931b082010-08-26 03:08:43 +0000463 Var->getStorageClass() != SC_Extern &&
464 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregord85b5b92009-11-25 22:24:25 +0000465 bool FoundExtern = false;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000466 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000467 PrevVar && !FoundExtern;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000468 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000469 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregord85b5b92009-11-25 22:24:25 +0000470 FoundExtern = true;
471
472 if (!FoundExtern)
John McCallaf146032010-10-30 11:50:40 +0000473 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000474 }
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000475 if (Var->getStorageClass() == SC_None) {
Douglas Gregoref96ee02012-01-14 16:38:05 +0000476 const VarDecl *PrevVar = Var->getPreviousDecl();
477 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000478 if (PrevVar->getStorageClass() == SC_PrivateExtern)
479 break;
Eli Friedman8c7a1852012-10-26 23:05:34 +0000480 if (PrevVar)
481 return PrevVar->getLinkageAndVisibility();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000482 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000483 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000484 // C++ [temp]p4:
485 // A non-member function template can have internal linkage; any
486 // other template name shall have external linkage.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000487 const FunctionDecl *Function = 0;
488 if (const FunctionTemplateDecl *FunTmpl
489 = dyn_cast<FunctionTemplateDecl>(D))
490 Function = FunTmpl->getTemplatedDecl();
491 else
492 Function = cast<FunctionDecl>(D);
493
494 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000495 if (Function->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000496 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000497 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
498 // - a data member of an anonymous union.
499 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallaf146032010-10-30 11:50:40 +0000500 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000501 }
502
Chandler Carruth094b6432011-02-24 19:03:39 +0000503 if (D->isInAnonymousNamespace()) {
504 const VarDecl *Var = dyn_cast<VarDecl>(D);
505 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindola950fee22013-02-14 01:18:37 +0000506 if ((!Var || !isInExternCContext(Var)) &&
507 (!Func || !isInExternCContext(Func)))
Chandler Carruth094b6432011-02-24 19:03:39 +0000508 return LinkageInfo::uniqueExternal();
509 }
John McCalle7bc9722010-10-28 04:18:25 +0000510
John McCall1fb0caa2010-10-22 21:05:15 +0000511 // Set up the defaults.
512
513 // C99 6.2.2p5:
514 // If the declaration of an identifier for an object has file
515 // scope and no storage-class specifier, its linkage is
516 // external.
John McCallaf146032010-10-30 11:50:40 +0000517 LinkageInfo LV;
518
John McCalld4c3d662013-02-20 01:54:26 +0000519 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000520 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola5727cf52012-04-19 02:22:07 +0000521 LV.mergeVisibility(*Vis, true);
Rafael Espindolae9836a22012-04-16 18:46:26 +0000522 } else {
523 // If we're declared in a namespace with a visibility attribute,
John McCall5a758de2013-02-16 00:17:33 +0000524 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindolae9836a22012-04-16 18:46:26 +0000525 for (const DeclContext *DC = D->getDeclContext();
526 !isa<TranslationUnitDecl>(DC);
527 DC = DC->getParent()) {
528 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
529 if (!ND) continue;
David Blaikiedc84cd52013-02-20 22:23:23 +0000530 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola5727cf52012-04-19 02:22:07 +0000531 LV.mergeVisibility(*Vis, true);
Rafael Espindolae9836a22012-04-16 18:46:26 +0000532 break;
533 }
534 }
535 }
Rafael Espindolae9836a22012-04-16 18:46:26 +0000536
John McCall5a758de2013-02-16 00:17:33 +0000537 // Add in global settings if the above didn't give us direct visibility.
538 if (!LV.visibilityExplicit()) {
John McCalla880b192013-02-19 01:57:35 +0000539 // Use global type/value visibility as appropriate.
540 Visibility globalVisibility;
541 if (computation == LVForValue) {
542 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
543 } else {
544 assert(computation == LVForType);
545 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
546 }
547 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCall5a758de2013-02-16 00:17:33 +0000548
549 // If we're paying attention to global visibility, apply
550 // -finline-visibility-hidden if this is an inline method.
551 if (useInlineVisibilityHidden(D))
552 LV.mergeVisibility(HiddenVisibility, true);
553 }
Rafael Espindolab04b7312012-07-13 14:25:36 +0000554 }
Rafael Espindolaff257982012-04-19 02:55:01 +0000555
Douglas Gregord85b5b92009-11-25 22:24:25 +0000556 // C++ [basic.link]p4:
John McCall1fb0caa2010-10-22 21:05:15 +0000557
Douglas Gregord85b5b92009-11-25 22:24:25 +0000558 // A name having namespace scope has external linkage if it is the
559 // name of
560 //
561 // - an object or reference, unless it has internal linkage; or
562 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall110e8e52010-10-29 22:22:43 +0000563 // GCC applies the following optimization to variables and static
564 // data members, but not to functions:
565 //
John McCall1fb0caa2010-10-22 21:05:15 +0000566 // Modify the variable's LV by the LV of its type unless this is
567 // C or extern "C". This follows from [basic.link]p9:
568 // A type without linkage shall not be used as the type of a
569 // variable or function with external linkage unless
570 // - the entity has C language linkage, or
571 // - the entity is declared within an unnamed namespace, or
572 // - the entity is not used or is defined in the same
573 // translation unit.
574 // and [basic.link]p10:
575 // ...the types specified by all declarations referring to a
576 // given variable or function shall be identical...
577 // C does not have an equivalent rule.
578 //
John McCallac65c622010-10-26 04:59:26 +0000579 // Ignore this if we've got an explicit attribute; the user
580 // probably knows what they're doing.
581 //
John McCall1fb0caa2010-10-22 21:05:15 +0000582 // Note that we don't want to make the variable non-external
583 // because of this, but unique-external linkage suits us.
David Blaikie4e4d0842012-03-11 07:00:24 +0000584 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman750dc2b2012-01-15 01:23:58 +0000585 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000586 LinkageInfo TypeLV = getLVForType(Var->getType());
587 if (TypeLV.linkage() != ExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000588 return LinkageInfo::uniqueExternal();
John McCall5a758de2013-02-16 00:17:33 +0000589 if (!LV.visibilityExplicit())
590 LV.mergeVisibility(TypeLV);
John McCall110e8e52010-10-29 22:22:43 +0000591 }
592
John McCall35cebc32010-11-02 18:38:13 +0000593 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola5727cf52012-04-19 02:22:07 +0000594 LV.mergeVisibility(HiddenVisibility, true);
John McCall35cebc32010-11-02 18:38:13 +0000595
Rafael Espindola538fb982012-11-12 04:10:23 +0000596 // Note that Sema::MergeVarDecl already takes care of implementing
597 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
598 // to do it here.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000599
Douglas Gregord85b5b92009-11-25 22:24:25 +0000600 // - a function, unless it has internal linkage; or
John McCall1fb0caa2010-10-22 21:05:15 +0000601 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall67fa6d52010-10-28 07:07:52 +0000602 // In theory, we can modify the function's LV by the LV of its
603 // type unless it has C linkage (see comment above about variables
604 // for justification). In practice, GCC doesn't do this, so it's
605 // just too painful to make work.
John McCall1fb0caa2010-10-22 21:05:15 +0000606
John McCall35cebc32010-11-02 18:38:13 +0000607 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola5727cf52012-04-19 02:22:07 +0000608 LV.mergeVisibility(HiddenVisibility, true);
John McCall35cebc32010-11-02 18:38:13 +0000609
Rafael Espindola51758612012-11-21 02:47:19 +0000610 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
611 // merging storage classes and visibility attributes, so we don't have to
612 // look at previous decls in here.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000613
John McCallaf8ca372011-02-10 06:50:24 +0000614 // In C++, then if the type of the function uses a type with
615 // unique-external linkage, it's not legally usable from outside
616 // this translation unit. However, we should use the C linkage
617 // rules instead for extern "C" declarations.
David Blaikie4e4d0842012-03-11 07:00:24 +0000618 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman750dc2b2012-01-15 01:23:58 +0000619 !Function->getDeclContext()->isExternCContext() &&
John McCallaf8ca372011-02-10 06:50:24 +0000620 Function->getType()->getLinkage() == UniqueExternalLinkage)
621 return LinkageInfo::uniqueExternal();
622
John McCall6ce51ee2011-06-27 23:06:04 +0000623 // Consider LV from the template and the template arguments unless
624 // this is an explicit specialization with a visibility attribute.
625 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000626 = Function->getTemplateSpecializationInfo()) {
John McCall5a758de2013-02-16 00:17:33 +0000627 mergeTemplateLV(LV, Function, specInfo);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000628 }
629
Douglas Gregord85b5b92009-11-25 22:24:25 +0000630 // - a named class (Clause 9), or an unnamed class defined in a
631 // typedef declaration in which the class has the typedef name
632 // for linkage purposes (7.1.3); or
633 // - a named enumeration (7.2), or an unnamed enumeration
634 // defined in a typedef declaration in which the enumeration
635 // has the typedef name for linkage purposes (7.1.3); or
John McCall1fb0caa2010-10-22 21:05:15 +0000636 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
637 // Unnamed tags have no linkage.
Richard Smith162e1c12011-04-15 14:24:37 +0000638 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallaf146032010-10-30 11:50:40 +0000639 return LinkageInfo::none();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000640
John McCall1fb0caa2010-10-22 21:05:15 +0000641 // If this is a class template specialization, consider the
642 // linkage of the template and template arguments.
John McCall6ce51ee2011-06-27 23:06:04 +0000643 if (const ClassTemplateSpecializationDecl *spec
John McCall1fb0caa2010-10-22 21:05:15 +0000644 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCall5a758de2013-02-16 00:17:33 +0000645 mergeTemplateLV(LV, spec, computation);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000646 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000647
648 // - an enumerator belonging to an enumeration with external linkage;
John McCall1fb0caa2010-10-22 21:05:15 +0000649 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola1266b612012-04-21 23:28:21 +0000650 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCall5a758de2013-02-16 00:17:33 +0000651 computation);
John McCallaf146032010-10-30 11:50:40 +0000652 if (!isExternalLinkage(EnumLV.linkage()))
653 return LinkageInfo::none();
654 LV.merge(EnumLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000655
656 // - a template, unless it is a function template that has
657 // internal linkage (Clause 14);
John McCall1a0918a2011-03-04 10:39:25 +0000658 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld4c3d662013-02-20 01:54:26 +0000659 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCall5a758de2013-02-16 00:17:33 +0000660 LinkageInfo tempLV =
661 getLVForTemplateParameterList(temp->getTemplateParameters());
662 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
663
Douglas Gregord85b5b92009-11-25 22:24:25 +0000664 // - a namespace (7.3), unless it is declared within an unnamed
665 // namespace.
John McCall1fb0caa2010-10-22 21:05:15 +0000666 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
667 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000668
John McCall1fb0caa2010-10-22 21:05:15 +0000669 // By extension, we assign external linkage to Objective-C
670 // interfaces.
671 } else if (isa<ObjCInterfaceDecl>(D)) {
672 // fallout
673
674 // Everything not covered here has no linkage.
675 } else {
John McCallaf146032010-10-30 11:50:40 +0000676 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000677 }
678
679 // If we ended up with non-external linkage, visibility should
680 // always be default.
John McCallaf146032010-10-30 11:50:40 +0000681 if (LV.linkage() != ExternalLinkage)
682 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall1fb0caa2010-10-22 21:05:15 +0000683
John McCall1fb0caa2010-10-22 21:05:15 +0000684 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000685}
686
John McCall5a758de2013-02-16 00:17:33 +0000687static LinkageInfo getLVForClassMember(const NamedDecl *D,
688 LVComputationKind computation) {
John McCall1fb0caa2010-10-22 21:05:15 +0000689 // Only certain class members have linkage. Note that fields don't
690 // really have linkage, but it's convenient to say they do for the
691 // purposes of calculating linkage of pointer-to-data-member
692 // template arguments.
John McCall3cdfc4d2010-08-13 08:35:10 +0000693 if (!(isa<CXXMethodDecl>(D) ||
694 isa<VarDecl>(D) ||
John McCall1fb0caa2010-10-22 21:05:15 +0000695 isa<FieldDecl>(D) ||
David Blaikie66cff722012-11-14 01:52:05 +0000696 isa<TagDecl>(D)))
John McCallaf146032010-10-30 11:50:40 +0000697 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000698
John McCall36987482010-11-02 01:45:15 +0000699 LinkageInfo LV;
700
John McCall36987482010-11-02 01:45:15 +0000701 // If we have an explicit visibility attribute, merge that in.
John McCalld4c3d662013-02-20 01:54:26 +0000702 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000703 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000704 LV.mergeVisibility(*Vis, true);
Rafael Espindolab04b7312012-07-13 14:25:36 +0000705 // If we're paying attention to global visibility, apply
706 // -finline-visibility-hidden if this is an inline method.
707 //
708 // Note that we do this before merging information about
709 // the class visibility.
710 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D))
711 LV.mergeVisibility(HiddenVisibility, true);
John McCall36987482010-11-02 01:45:15 +0000712 }
Rafael Espindolac7e60602012-04-19 05:50:08 +0000713
714 // If this class member has an explicit visibility attribute, the only
715 // thing that can change its visibility is the template arguments, so
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000716 // only look for them when processing the class.
John McCalld4c3d662013-02-20 01:54:26 +0000717 LVComputationKind classComputation = computation;
718 if (LV.visibilityExplicit())
719 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola0f905902012-04-16 18:25:01 +0000720
Rafael Espindolac7e60602012-04-19 05:50:08 +0000721 // If this member has an visibility attribute, ClassF will exclude
722 // attributes on the class or command line options, keeping only information
723 // about the template instantiation. If the member has no visibility
724 // attributes, mergeWithMin behaves like merge, so in both cases mergeWithMin
725 // produces the desired result.
John McCall5a758de2013-02-16 00:17:33 +0000726 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()),
727 classComputation));
John McCall36987482010-11-02 01:45:15 +0000728 if (!isExternalLinkage(LV.linkage()))
John McCallaf146032010-10-30 11:50:40 +0000729 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000730
731 // If the class already has unique-external linkage, we can't improve.
John McCall36987482010-11-02 01:45:15 +0000732 if (LV.linkage() == UniqueExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000733 return LinkageInfo::uniqueExternal();
John McCall3cdfc4d2010-08-13 08:35:10 +0000734
John McCall3cdfc4d2010-08-13 08:35:10 +0000735 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallaf8ca372011-02-10 06:50:24 +0000736 // If the type of the function uses a type with unique-external
737 // linkage, it's not legally usable from outside this translation unit.
738 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
739 return LinkageInfo::uniqueExternal();
740
John McCall1fb0caa2010-10-22 21:05:15 +0000741 // If this is a method template specialization, use the linkage for
742 // the template parameters and arguments.
John McCall6ce51ee2011-06-27 23:06:04 +0000743 if (FunctionTemplateSpecializationInfo *spec
John McCall3cdfc4d2010-08-13 08:35:10 +0000744 = MD->getTemplateSpecializationInfo()) {
John McCall5a758de2013-02-16 00:17:33 +0000745 mergeTemplateLV(LV, MD, spec);
John McCall66cbcf32010-11-01 01:29:57 +0000746 }
John McCall1fb0caa2010-10-22 21:05:15 +0000747
John McCall110e8e52010-10-29 22:22:43 +0000748 // Note that in contrast to basically every other situation, we
749 // *do* apply -fvisibility to method declarations.
750
751 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000752 if (const ClassTemplateSpecializationDecl *spec
John McCall110e8e52010-10-29 22:22:43 +0000753 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCall5a758de2013-02-16 00:17:33 +0000754 mergeTemplateLV(LV, spec, computation);
John McCall110e8e52010-10-29 22:22:43 +0000755 }
756
John McCall110e8e52010-10-29 22:22:43 +0000757 // Static data members.
758 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallee301022010-10-30 09:18:49 +0000759 // Modify the variable's linkage by its type, but ignore the
760 // type's visibility unless it's a definition.
John McCall5a758de2013-02-16 00:17:33 +0000761 LinkageInfo typeLV = getLVForType(VD->getType());
762 if (typeLV.linkage() != ExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000763 LV.mergeLinkage(UniqueExternalLinkage);
John McCall5a758de2013-02-16 00:17:33 +0000764 if (!LV.visibilityExplicit())
765 LV.mergeVisibility(typeLV);
766
767 // Template members.
768 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
769 bool considerVisibility =
John McCalld4c3d662013-02-20 01:54:26 +0000770 (!LV.visibilityExplicit() &&
771 !hasExplicitVisibilityAlready(computation));
John McCall5a758de2013-02-16 00:17:33 +0000772 LinkageInfo tempLV =
773 getLVForTemplateParameterList(temp->getTemplateParameters());
774 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall110e8e52010-10-29 22:22:43 +0000775 }
776
John McCall1fb0caa2010-10-22 21:05:15 +0000777 return LV;
John McCall3cdfc4d2010-08-13 08:35:10 +0000778}
779
John McCallf76b0922011-02-08 19:01:05 +0000780static void clearLinkageForClass(const CXXRecordDecl *record) {
781 for (CXXRecordDecl::decl_iterator
782 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
783 Decl *child = *i;
784 if (isa<NamedDecl>(child))
Rafael Espindola838dc592013-01-12 06:42:30 +0000785 cast<NamedDecl>(child)->ClearLinkageCache();
John McCallf76b0922011-02-08 19:01:05 +0000786 }
787}
788
David Blaikie99ba9e32011-12-20 02:48:34 +0000789void NamedDecl::anchor() { }
790
Rafael Espindola838dc592013-01-12 06:42:30 +0000791void NamedDecl::ClearLinkageCache() {
John McCallf76b0922011-02-08 19:01:05 +0000792 // Note that we can't skip clearing the linkage of children just
793 // because the parent doesn't have cached linkage: we don't cache
794 // when computing linkage for parent contexts.
795
Rafael Espindola838dc592013-01-12 06:42:30 +0000796 HasCachedLinkage = 0;
John McCallf76b0922011-02-08 19:01:05 +0000797
798 // If we're changing the linkage of a class, we need to reset the
799 // linkage of child declarations, too.
800 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
801 clearLinkageForClass(record);
802
Dmitri Gribenkof8c12142013-02-03 16:10:26 +0000803 if (ClassTemplateDecl *temp = dyn_cast<ClassTemplateDecl>(this)) {
John McCallf76b0922011-02-08 19:01:05 +0000804 // Clear linkage for the template pattern.
805 CXXRecordDecl *record = temp->getTemplatedDecl();
Rafael Espindola838dc592013-01-12 06:42:30 +0000806 record->HasCachedLinkage = 0;
John McCallf76b0922011-02-08 19:01:05 +0000807 clearLinkageForClass(record);
808
John McCall15e310a2011-02-19 02:53:41 +0000809 // We need to clear linkage for specializations, too.
810 for (ClassTemplateDecl::spec_iterator
811 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola838dc592013-01-12 06:42:30 +0000812 i->ClearLinkageCache();
John McCallf76b0922011-02-08 19:01:05 +0000813 }
John McCall15e310a2011-02-19 02:53:41 +0000814
815 // Clear cached linkage for function template decls, too.
Dmitri Gribenkof8c12142013-02-03 16:10:26 +0000816 if (FunctionTemplateDecl *temp = dyn_cast<FunctionTemplateDecl>(this)) {
Rafael Espindola838dc592013-01-12 06:42:30 +0000817 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall15e310a2011-02-19 02:53:41 +0000818 for (FunctionTemplateDecl::spec_iterator
819 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola838dc592013-01-12 06:42:30 +0000820 i->ClearLinkageCache();
John McCall78951942011-03-22 06:58:49 +0000821 }
John McCall15e310a2011-02-19 02:53:41 +0000822
John McCallf76b0922011-02-08 19:01:05 +0000823}
824
Douglas Gregor381d34e2010-12-06 18:36:25 +0000825Linkage NamedDecl::getLinkage() const {
Richard Smithad0e27b2013-02-12 05:48:23 +0000826 if (HasCachedLinkage)
Rafael Espindola838dc592013-01-12 06:42:30 +0000827 return Linkage(CachedLinkage);
Rafael Espindola838dc592013-01-12 06:42:30 +0000828
John McCalld4c3d662013-02-20 01:54:26 +0000829 // We don't care about visibility here, so ask for the cheapest
830 // possible visibility analysis.
831 CachedLinkage = getLVForDecl(this, LVForExplicitValue).linkage();
Rafael Espindola838dc592013-01-12 06:42:30 +0000832 HasCachedLinkage = 1;
833
834#ifndef NDEBUG
835 verifyLinkage();
836#endif
837
838 return Linkage(CachedLinkage);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000839}
840
John McCallaf146032010-10-30 11:50:40 +0000841LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCall5a758de2013-02-16 00:17:33 +0000842 LVComputationKind computation =
843 (usesTypeVisibility(this) ? LVForType : LVForValue);
844 LinkageInfo LI = getLVForDecl(this, computation);
Rafael Espindola838dc592013-01-12 06:42:30 +0000845 if (HasCachedLinkage) {
846 assert(Linkage(CachedLinkage) == LI.linkage());
847 return LI;
Rafael Espindola140aadf2012-12-25 07:31:49 +0000848 }
Rafael Espindola838dc592013-01-12 06:42:30 +0000849 HasCachedLinkage = 1;
850 CachedLinkage = LI.linkage();
Rafael Espindola6acc4bc2013-01-05 01:28:37 +0000851
852#ifndef NDEBUG
Rafael Espindola838dc592013-01-12 06:42:30 +0000853 verifyLinkage();
854#endif
855
856 return LI;
857}
858
859void NamedDecl::verifyLinkage() const {
Rafael Espindola6acc4bc2013-01-05 01:28:37 +0000860 // In C (because of gnu inline) and in c++ with microsoft extensions an
861 // static can follow an extern, so we can have two decls with different
862 // linkages.
863 const LangOptions &Opts = getASTContext().getLangOpts();
864 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
Rafael Espindola838dc592013-01-12 06:42:30 +0000865 return;
Rafael Espindola6acc4bc2013-01-05 01:28:37 +0000866
867 // We have just computed the linkage for this decl. By induction we know
868 // that all other computed linkages match, check that the one we just computed
869 // also does.
870 NamedDecl *D = NULL;
871 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
872 NamedDecl *T = cast<NamedDecl>(*I);
873 if (T == this)
874 continue;
Rafael Espindola838dc592013-01-12 06:42:30 +0000875 if (T->HasCachedLinkage != 0) {
Rafael Espindola6acc4bc2013-01-05 01:28:37 +0000876 D = T;
877 break;
878 }
879 }
880 assert(!D || D->CachedLinkage == CachedLinkage);
John McCall0df95872010-10-29 00:29:13 +0000881}
Ted Kremenekbecc3082010-04-20 23:15:35 +0000882
David Blaikiedc84cd52013-02-20 22:23:23 +0000883Optional<Visibility>
John McCalld4c3d662013-02-20 01:54:26 +0000884NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000885 // Use the most recent declaration of a variable.
Rafael Espindola797105a2012-05-16 02:10:38 +0000886 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000887 if (Optional<Visibility> V = getVisibilityOf(Var, kind))
Rafael Espindola797105a2012-05-16 02:10:38 +0000888 return V;
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000889
Rafael Espindola797105a2012-05-16 02:10:38 +0000890 if (Var->isStaticDataMember()) {
891 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
892 if (InstantiatedFrom)
John McCalld4c3d662013-02-20 01:54:26 +0000893 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola797105a2012-05-16 02:10:38 +0000894 }
895
David Blaikie66874fb2013-02-21 01:47:18 +0000896 return None;
Rafael Espindola797105a2012-05-16 02:10:38 +0000897 }
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000898 // Use the most recent declaration of a function, and also handle
899 // function template specializations.
900 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000901 if (Optional<Visibility> V = getVisibilityOf(fn, kind))
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000902 return V;
903
904 // If the function is a specialization of a template with an
905 // explicit visibility attribute, use that.
906 if (FunctionTemplateSpecializationInfo *templateInfo
907 = fn->getTemplateSpecializationInfo())
John McCalld4c3d662013-02-20 01:54:26 +0000908 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
909 kind);
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000910
Rafael Espindola860097c2012-02-23 04:17:32 +0000911 // If the function is a member of a specialization of a class template
912 // and the corresponding decl has explicit visibility, use that.
913 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
914 if (InstantiatedFrom)
John McCalld4c3d662013-02-20 01:54:26 +0000915 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola860097c2012-02-23 04:17:32 +0000916
David Blaikie66874fb2013-02-21 01:47:18 +0000917 return None;
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000918 }
919
920 // Otherwise, just check the declaration itself first.
David Blaikiedc84cd52013-02-20 22:23:23 +0000921 if (Optional<Visibility> V = getVisibilityOf(this, kind))
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000922 return V;
923
Rafael Espindola98499012012-07-31 19:02:02 +0000924 // The visibility of a template is stored in the templated decl.
925 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
John McCalld4c3d662013-02-20 01:54:26 +0000926 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindola98499012012-07-31 19:02:02 +0000927
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000928 // If there wasn't explicit visibility there, and this is a
929 // specialization of a class template, check for visibility
930 // on the pattern.
931 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindolad3d02dd2012-07-13 01:19:08 +0000932 = dyn_cast<ClassTemplateSpecializationDecl>(this))
John McCalld4c3d662013-02-20 01:54:26 +0000933 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
934 kind);
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000935
Rafael Espindola860097c2012-02-23 04:17:32 +0000936 // If this is a member class of a specialization of a class template
937 // and the corresponding decl has explicit visibility, use that.
938 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
939 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
940 if (InstantiatedFrom)
John McCalld4c3d662013-02-20 01:54:26 +0000941 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola860097c2012-02-23 04:17:32 +0000942 }
943
David Blaikie66874fb2013-02-21 01:47:18 +0000944 return None;
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000945}
946
John McCall5a758de2013-02-16 00:17:33 +0000947static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
948 LVComputationKind computation) {
949 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
950 if (Function->isInAnonymousNamespace() &&
951 !Function->getDeclContext()->isExternCContext())
952 return LinkageInfo::uniqueExternal();
953
954 // This is a "void f();" which got merged with a file static.
955 if (Function->getStorageClass() == SC_Static)
956 return LinkageInfo::internal();
957
958 LinkageInfo LV;
John McCalld4c3d662013-02-20 01:54:26 +0000959 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000960 if (Optional<Visibility> Vis =
961 getExplicitVisibility(Function, computation))
John McCall5a758de2013-02-16 00:17:33 +0000962 LV.mergeVisibility(*Vis, true);
963 }
964
965 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
966 // merging storage classes and visibility attributes, so we don't have to
967 // look at previous decls in here.
968
969 return LV;
970 }
971
972 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
973 if (Var->getStorageClassAsWritten() == SC_Extern ||
974 Var->getStorageClassAsWritten() == SC_PrivateExtern) {
975 if (Var->isInAnonymousNamespace() &&
976 !Var->getDeclContext()->isExternCContext())
977 return LinkageInfo::uniqueExternal();
978
979 // This is an "extern int foo;" which got merged with a file static.
980 if (Var->getStorageClass() == SC_Static)
981 return LinkageInfo::internal();
982
983 LinkageInfo LV;
984 if (Var->getStorageClass() == SC_PrivateExtern)
985 LV.mergeVisibility(HiddenVisibility, true);
John McCalld4c3d662013-02-20 01:54:26 +0000986 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000987 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCall5a758de2013-02-16 00:17:33 +0000988 LV.mergeVisibility(*Vis, true);
989 }
990
991 // Note that Sema::MergeVarDecl already takes care of implementing
992 // C99 6.2.2p4 and propagating the visibility attribute, so we don't
993 // have to do it here.
994 return LV;
995 }
996 }
997
998 return LinkageInfo::none();
999}
1000
1001static LinkageInfo getLVForDecl(const NamedDecl *D,
1002 LVComputationKind computation) {
Ted Kremenekbecc3082010-04-20 23:15:35 +00001003 // Objective-C: treat all Objective-C declarations as having external
1004 // linkage.
John McCall0df95872010-10-29 00:29:13 +00001005 switch (D->getKind()) {
Ted Kremenekbecc3082010-04-20 23:15:35 +00001006 default:
1007 break;
Argyrios Kyrtzidisf8d34ed2011-12-01 01:28:21 +00001008 case Decl::ParmVar:
1009 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +00001010 case Decl::TemplateTemplateParm: // count these as external
1011 case Decl::NonTypeTemplateParm:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001012 case Decl::ObjCAtDefsField:
1013 case Decl::ObjCCategory:
1014 case Decl::ObjCCategoryImpl:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001015 case Decl::ObjCCompatibleAlias:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001016 case Decl::ObjCImplementation:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001017 case Decl::ObjCMethod:
1018 case Decl::ObjCProperty:
1019 case Decl::ObjCPropertyImpl:
1020 case Decl::ObjCProtocol:
John McCallaf146032010-10-30 11:50:40 +00001021 return LinkageInfo::external();
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001022
1023 case Decl::CXXRecord: {
1024 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1025 if (Record->isLambda()) {
1026 if (!Record->getLambdaManglingNumber()) {
1027 // This lambda has no mangling number, so it's internal.
1028 return LinkageInfo::internal();
1029 }
1030
1031 // This lambda has its linkage/visibility determined by its owner.
1032 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1033 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1034 if (isa<ParmVarDecl>(ContextDecl))
1035 DC = ContextDecl->getDeclContext()->getRedeclContext();
1036 else
John McCall5a758de2013-02-16 00:17:33 +00001037 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001038 }
1039
1040 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
John McCall5a758de2013-02-16 00:17:33 +00001041 return getLVForDecl(ND, computation);
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001042
1043 return LinkageInfo::external();
1044 }
1045
1046 break;
1047 }
Ted Kremenekbecc3082010-04-20 23:15:35 +00001048 }
1049
Douglas Gregord85b5b92009-11-25 22:24:25 +00001050 // Handle linkage for namespace-scope names.
John McCall0df95872010-10-29 00:29:13 +00001051 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5a758de2013-02-16 00:17:33 +00001052 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001053
1054 // C++ [basic.link]p5:
1055 // In addition, a member function, static data member, a named
1056 // class or enumeration of class scope, or an unnamed class or
1057 // enumeration defined in a class-scope typedef declaration such
1058 // that the class or enumeration has the typedef name for linkage
1059 // purposes (7.1.3), has external linkage if the name of the class
1060 // has external linkage.
John McCall0df95872010-10-29 00:29:13 +00001061 if (D->getDeclContext()->isRecord())
John McCall5a758de2013-02-16 00:17:33 +00001062 return getLVForClassMember(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001063
1064 // C++ [basic.link]p6:
1065 // The name of a function declared in block scope and the name of
1066 // an object declared by a block scope extern declaration have
1067 // linkage. If there is a visible declaration of an entity with
1068 // linkage having the same name and type, ignoring entities
1069 // declared outside the innermost enclosing namespace scope, the
1070 // block scope declaration declares that same entity and receives
1071 // the linkage of the previous declaration. If there is more than
1072 // one such matching entity, the program is ill-formed. Otherwise,
1073 // if no matching entity is found, the block scope entity receives
1074 // external linkage.
John McCall5a758de2013-02-16 00:17:33 +00001075 if (D->getDeclContext()->isFunctionOrMethod())
1076 return getLVForLocalDecl(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001077
1078 // C++ [basic.link]p6:
1079 // Names not covered by these rules have no linkage.
John McCallaf146032010-10-30 11:50:40 +00001080 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +00001081}
Douglas Gregord85b5b92009-11-25 22:24:25 +00001082
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001083std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregorba103062012-03-27 23:34:16 +00001084 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson3a082d82009-09-08 18:24:21 +00001085}
1086
1087std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001088 const DeclContext *Ctx = getDeclContext();
1089
1090 if (Ctx->isFunctionOrMethod())
1091 return getNameAsString();
1092
Chris Lattner5f9e2722011-07-23 10:55:15 +00001093 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001094 ContextsTy Contexts;
1095
1096 // Collect contexts.
1097 while (Ctx && isa<NamedDecl>(Ctx)) {
1098 Contexts.push_back(Ctx);
1099 Ctx = Ctx->getParent();
1100 };
1101
1102 std::string QualName;
1103 llvm::raw_string_ostream OS(QualName);
1104
1105 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1106 I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001107 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001108 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001109 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1110 std::string TemplateArgsStr
1111 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00001112 TemplateArgs.data(),
1113 TemplateArgs.size(),
Anders Carlsson3a082d82009-09-08 18:24:21 +00001114 P);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001115 OS << Spec->getName() << TemplateArgsStr;
1116 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig6be11202009-12-24 23:15:03 +00001117 if (ND->isAnonymousNamespace())
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001118 OS << "<anonymous namespace>";
Sam Weinig6be11202009-12-24 23:15:03 +00001119 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001120 OS << *ND;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001121 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1122 if (!RD->getIdentifier())
1123 OS << "<anonymous " << RD->getKindName() << '>';
1124 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001125 OS << *RD;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001126 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinig3521d012009-12-28 03:19:38 +00001127 const FunctionProtoType *FT = 0;
1128 if (FD->hasWrittenPrototype())
Eli Friedman482466b2012-08-30 22:22:09 +00001129 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinig3521d012009-12-28 03:19:38 +00001130
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001131 OS << *FD << '(';
Sam Weinig3521d012009-12-28 03:19:38 +00001132 if (FT) {
Sam Weinig3521d012009-12-28 03:19:38 +00001133 unsigned NumParams = FD->getNumParams();
1134 for (unsigned i = 0; i < NumParams; ++i) {
1135 if (i)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001136 OS << ", ";
Argyrios Kyrtzidis7ad5c992012-05-05 04:20:37 +00001137 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinig3521d012009-12-28 03:19:38 +00001138 }
1139
1140 if (FT->isVariadic()) {
1141 if (NumParams > 0)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001142 OS << ", ";
1143 OS << "...";
Sam Weinig3521d012009-12-28 03:19:38 +00001144 }
1145 }
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001146 OS << ')';
1147 } else {
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001148 OS << *cast<NamedDecl>(*I);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001149 }
1150 OS << "::";
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001151 }
1152
John McCall8472af42010-03-16 21:48:18 +00001153 if (getDeclName())
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001154 OS << *this;
John McCall8472af42010-03-16 21:48:18 +00001155 else
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001156 OS << "<anonymous>";
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001157
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001158 return OS.str();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001159}
1160
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001161bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001162 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1163
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001164 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1165 // We want to keep it, unless it nominates same namespace.
1166 if (getKind() == Decl::UsingDirective) {
Douglas Gregordb992412011-02-25 16:33:46 +00001167 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1168 ->getOriginalNamespace() ==
1169 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1170 ->getOriginalNamespace();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001171 }
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001173 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1174 // For function declarations, we keep track of redeclarations.
Douglas Gregoref96ee02012-01-14 16:38:05 +00001175 return FD->getPreviousDecl() == OldD;
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001176
Douglas Gregore53060f2009-06-25 22:08:12 +00001177 // For function templates, the underlying function declarations are linked.
1178 if (const FunctionTemplateDecl *FunctionTemplate
1179 = dyn_cast<FunctionTemplateDecl>(this))
1180 if (const FunctionTemplateDecl *OldFunctionTemplate
1181 = dyn_cast<FunctionTemplateDecl>(OldD))
1182 return FunctionTemplate->getTemplatedDecl()
1183 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Steve Naroff0de21fd2009-02-22 19:35:57 +00001185 // For method declarations, we keep track of redeclarations.
1186 if (isa<ObjCMethodDecl>(this))
1187 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001188
John McCallf36e02d2009-10-09 21:13:30 +00001189 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1190 return true;
1191
John McCall9488ea12009-11-17 05:59:44 +00001192 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1193 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1194 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1195
Douglas Gregordc355712011-02-25 00:36:19 +00001196 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1197 ASTContext &Context = getASTContext();
1198 return Context.getCanonicalNestedNameSpecifier(
1199 cast<UsingDecl>(this)->getQualifier()) ==
1200 Context.getCanonicalNestedNameSpecifier(
1201 cast<UsingDecl>(OldD)->getQualifier());
1202 }
Argyrios Kyrtzidisc80117e2010-11-04 08:48:52 +00001203
Douglas Gregor7a537402012-01-03 23:26:26 +00001204 // A typedef of an Objective-C class type can replace an Objective-C class
1205 // declaration or definition, and vice versa.
1206 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1207 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1208 return true;
1209
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001210 // For non-function declarations, if the declarations are of the
1211 // same kind then this must be a redeclaration, or semantic analysis
1212 // would not have given us the new declaration.
1213 return this->getKind() == OldD->getKind();
1214}
1215
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001216bool NamedDecl::hasLinkage() const {
Douglas Gregord85b5b92009-11-25 22:24:25 +00001217 return getLinkage() != NoLinkage;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001218}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001219
Daniel Dunbar6daffa52012-03-08 18:20:41 +00001220NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlssone136e0e2009-06-26 06:29:23 +00001221 NamedDecl *ND = this;
Benjamin Kramer56757e92012-03-08 21:00:45 +00001222 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1223 ND = UD->getTargetDecl();
1224
1225 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1226 return AD->getClassInterface();
1227
1228 return ND;
Anders Carlssone136e0e2009-06-26 06:29:23 +00001229}
1230
John McCall161755a2010-04-06 21:38:20 +00001231bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor5bc37f62012-03-08 02:08:05 +00001232 if (!isCXXClassMember())
1233 return false;
1234
John McCall161755a2010-04-06 21:38:20 +00001235 const NamedDecl *D = this;
1236 if (isa<UsingShadowDecl>(D))
1237 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1238
Francois Pichet87c2e122010-11-21 06:08:52 +00001239 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCall161755a2010-04-06 21:38:20 +00001240 return true;
1241 if (isa<CXXMethodDecl>(D))
1242 return cast<CXXMethodDecl>(D)->isInstance();
1243 if (isa<FunctionTemplateDecl>(D))
1244 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1245 ->getTemplatedDecl())->isInstance();
1246 return false;
1247}
1248
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001249//===----------------------------------------------------------------------===//
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001250// DeclaratorDecl Implementation
1251//===----------------------------------------------------------------------===//
1252
Douglas Gregor1693e152010-07-06 18:42:40 +00001253template <typename DeclT>
1254static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1255 if (decl->getNumTemplateParameterLists() > 0)
1256 return decl->getTemplateParameterList(0)->getTemplateLoc();
1257 else
1258 return decl->getInnerLocStart();
1259}
1260
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001261SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCall4e449832010-05-28 23:32:21 +00001262 TypeSourceInfo *TSI = getTypeSourceInfo();
1263 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001264 return SourceLocation();
1265}
1266
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001267void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1268 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00001269 // Make sure the extended decl info is allocated.
1270 if (!hasExtInfo()) {
1271 // Save (non-extended) type source info pointer.
1272 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1273 // Allocate external info struct.
1274 DeclInfo = new (getASTContext()) ExtInfo;
1275 // Restore savedTInfo into (extended) decl info.
1276 getExtInfo()->TInfo = savedTInfo;
1277 }
1278 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001279 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00001280 } else {
John McCallb6217662010-03-15 10:12:16 +00001281 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00001282 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001283 if (getExtInfo()->NumTemplParamLists == 0) {
1284 // Save type source info pointer.
1285 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1286 // Deallocate the extended decl info.
1287 getASTContext().Deallocate(getExtInfo());
1288 // Restore savedTInfo into (non-extended) decl info.
1289 DeclInfo = savedTInfo;
1290 }
1291 else
1292 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00001293 }
1294 }
1295}
1296
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001297void
1298DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1299 unsigned NumTPLists,
1300 TemplateParameterList **TPLists) {
1301 assert(NumTPLists > 0);
1302 // Make sure the extended decl info is allocated.
1303 if (!hasExtInfo()) {
1304 // Save (non-extended) type source info pointer.
1305 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1306 // Allocate external info struct.
1307 DeclInfo = new (getASTContext()) ExtInfo;
1308 // Restore savedTInfo into (extended) decl info.
1309 getExtInfo()->TInfo = savedTInfo;
1310 }
1311 // Set the template parameter lists info.
1312 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1313}
1314
Douglas Gregor1693e152010-07-06 18:42:40 +00001315SourceLocation DeclaratorDecl::getOuterLocStart() const {
1316 return getTemplateOrInnerLocStart(this);
1317}
1318
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001319namespace {
1320
1321// Helper function: returns true if QT is or contains a type
1322// having a postfix component.
1323bool typeIsPostfix(clang::QualType QT) {
1324 while (true) {
1325 const Type* T = QT.getTypePtr();
1326 switch (T->getTypeClass()) {
1327 default:
1328 return false;
1329 case Type::Pointer:
1330 QT = cast<PointerType>(T)->getPointeeType();
1331 break;
1332 case Type::BlockPointer:
1333 QT = cast<BlockPointerType>(T)->getPointeeType();
1334 break;
1335 case Type::MemberPointer:
1336 QT = cast<MemberPointerType>(T)->getPointeeType();
1337 break;
1338 case Type::LValueReference:
1339 case Type::RValueReference:
1340 QT = cast<ReferenceType>(T)->getPointeeType();
1341 break;
1342 case Type::PackExpansion:
1343 QT = cast<PackExpansionType>(T)->getPattern();
1344 break;
1345 case Type::Paren:
1346 case Type::ConstantArray:
1347 case Type::DependentSizedArray:
1348 case Type::IncompleteArray:
1349 case Type::VariableArray:
1350 case Type::FunctionProto:
1351 case Type::FunctionNoProto:
1352 return true;
1353 }
1354 }
1355}
1356
1357} // namespace
1358
1359SourceRange DeclaratorDecl::getSourceRange() const {
1360 SourceLocation RangeEnd = getLocation();
1361 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1362 if (typeIsPostfix(TInfo->getType()))
1363 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1364 }
1365 return SourceRange(getOuterLocStart(), RangeEnd);
1366}
1367
Abramo Bagnara9b934882010-06-12 08:15:14 +00001368void
Douglas Gregorc722ea42010-06-15 17:44:38 +00001369QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1370 unsigned NumTPLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00001371 TemplateParameterList **TPLists) {
1372 assert((NumTPLists == 0 || TPLists != 0) &&
1373 "Empty array of template parameters with positive size!");
Abramo Bagnara9b934882010-06-12 08:15:14 +00001374
1375 // Free previous template parameters (if any).
1376 if (NumTemplParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001377 Context.Deallocate(TemplParamLists);
Abramo Bagnara9b934882010-06-12 08:15:14 +00001378 TemplParamLists = 0;
1379 NumTemplParamLists = 0;
1380 }
1381 // Set info on matched template parameter lists (if any).
1382 if (NumTPLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001383 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnara9b934882010-06-12 08:15:14 +00001384 NumTemplParamLists = NumTPLists;
1385 for (unsigned i = NumTPLists; i-- > 0; )
1386 TemplParamLists[i] = TPLists[i];
1387 }
1388}
1389
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001390//===----------------------------------------------------------------------===//
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001391// VarDecl Implementation
1392//===----------------------------------------------------------------------===//
1393
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001394const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1395 switch (SC) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00001396 case SC_None: break;
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001397 case SC_Auto: return "auto";
1398 case SC_Extern: return "extern";
1399 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1400 case SC_PrivateExtern: return "__private_extern__";
1401 case SC_Register: return "register";
1402 case SC_Static: return "static";
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001403 }
1404
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001405 llvm_unreachable("Invalid storage class");
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001406}
1407
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001408VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1409 SourceLocation StartL, SourceLocation IdL,
John McCalla93c9342009-12-07 02:54:59 +00001410 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001411 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001412 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001413}
1414
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001415VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1416 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1417 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1418 QualType(), 0, SC_None, SC_None);
1419}
1420
Douglas Gregor381d34e2010-12-06 18:36:25 +00001421void VarDecl::setStorageClass(StorageClass SC) {
1422 assert(isLegalForVariable(SC));
1423 if (getStorageClass() != SC)
Rafael Espindola838dc592013-01-12 06:42:30 +00001424 ClearLinkageCache();
Douglas Gregor381d34e2010-12-06 18:36:25 +00001425
John McCallf1e4fbf2011-05-01 02:13:58 +00001426 VarDeclBits.SClass = SC;
Douglas Gregor381d34e2010-12-06 18:36:25 +00001427}
1428
Douglas Gregor1693e152010-07-06 18:42:40 +00001429SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidisd69f31c2012-10-08 23:08:41 +00001430 if (const Expr *Init = getInit()) {
1431 SourceLocation InitEnd = Init->getLocEnd();
Nico Weber3a344f92013-01-22 17:00:09 +00001432 // If Init is implicit, ignore its source range and fallback on
1433 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1434 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidisd69f31c2012-10-08 23:08:41 +00001435 return SourceRange(getOuterLocStart(), InitEnd);
1436 }
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001437 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001438}
1439
Rafael Espindola7ac928b2013-01-04 21:18:45 +00001440template<typename T>
Rafael Espindola950fee22013-02-14 01:18:37 +00001441static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindolad2fdd422013-02-14 01:47:04 +00001442 // C++ [dcl.link]p1: All function types, function names with external linkage,
1443 // and variable names with external linkage have a language linkage.
1444 if (!isExternalLinkage(D.getLinkage()))
1445 return NoLanguageLinkage;
1446
1447 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola2b721f52013-01-04 20:41:40 +00001448 // C language linkage fits the implementation nicely.
Rafael Espindola78eeba82012-12-28 14:21:58 +00001449 ASTContext &Context = D.getASTContext();
1450 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola950fee22013-02-14 01:18:37 +00001451 return CLanguageLinkage;
1452
Rafael Espindolad2fdd422013-02-14 01:47:04 +00001453 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1454 // language linkage of the names of class members and the function type of
1455 // class member functions.
Rafael Espindola78eeba82012-12-28 14:21:58 +00001456 const DeclContext *DC = D.getDeclContext();
1457 if (DC->isRecord())
Rafael Espindola950fee22013-02-14 01:18:37 +00001458 return CXXLanguageLinkage;
Rafael Espindola78eeba82012-12-28 14:21:58 +00001459
1460 // If the first decl is in an extern "C" context, any other redeclaration
1461 // will have C language linkage. If the first one is not in an extern "C"
1462 // context, we would have reported an error for any other decl being in one.
Rafael Espindola7ac928b2013-01-04 21:18:45 +00001463 const T *First = D.getFirstDeclaration();
Rafael Espindola950fee22013-02-14 01:18:37 +00001464 if (First->getDeclContext()->isExternCContext())
1465 return CLanguageLinkage;
1466 return CXXLanguageLinkage;
Rafael Espindola78eeba82012-12-28 14:21:58 +00001467}
1468
Rafael Espindola950fee22013-02-14 01:18:37 +00001469LanguageLinkage VarDecl::getLanguageLinkage() const {
1470 return getLanguageLinkageTemplate(*this);
Rafael Espindola78eeba82012-12-28 14:21:58 +00001471}
1472
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001473VarDecl *VarDecl::getCanonicalDecl() {
1474 return getFirstDeclaration();
1475}
1476
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001477VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1478 ASTContext &C) const
1479{
Sebastian Redle9d12b62010-01-31 22:27:38 +00001480 // C++ [basic.def]p2:
1481 // A declaration is a definition unless [...] it contains the 'extern'
1482 // specifier or a linkage-specification and neither an initializer [...],
1483 // it declares a static data member in a class declaration [...].
1484 // C++ [temp.expl.spec]p15:
1485 // An explicit specialization of a static data member of a template is a
1486 // definition if the declaration includes an initializer; otherwise, it is
1487 // a declaration.
1488 if (isStaticDataMember()) {
1489 if (isOutOfLine() && (hasInit() ||
1490 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1491 return Definition;
1492 else
1493 return DeclarationOnly;
1494 }
1495 // C99 6.7p5:
1496 // A definition of an identifier is a declaration for that identifier that
1497 // [...] causes storage to be reserved for that object.
1498 // Note: that applies for all non-file-scope objects.
1499 // C99 6.9.2p1:
1500 // If the declaration of an identifier for an object has file scope and an
1501 // initializer, the declaration is an external definition for the identifier
1502 if (hasInit())
1503 return Definition;
1504 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1505 if (hasExternalStorage())
1506 return DeclarationOnly;
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001507
John McCalld931b082010-08-26 03:08:43 +00001508 if (getStorageClassAsWritten() == SC_Extern ||
1509 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00001510 for (const VarDecl *PrevVar = getPreviousDecl();
1511 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Rafael Espindola372df452012-12-17 22:23:47 +00001512 if (PrevVar->getLinkage() == InternalLinkage)
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001513 return DeclarationOnly;
1514 }
1515 }
Sebastian Redle9d12b62010-01-31 22:27:38 +00001516 // C99 6.9.2p2:
1517 // A declaration of an object that has file scope without an initializer,
1518 // and without a storage class specifier or the scs 'static', constitutes
1519 // a tentative definition.
1520 // No such thing in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00001521 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redle9d12b62010-01-31 22:27:38 +00001522 return TentativeDefinition;
1523
1524 // What's left is (in C, block-scope) declarations without initializers or
1525 // external storage. These are definitions.
1526 return Definition;
1527}
1528
Sebastian Redle9d12b62010-01-31 22:27:38 +00001529VarDecl *VarDecl::getActingDefinition() {
1530 DefinitionKind Kind = isThisDeclarationADefinition();
1531 if (Kind != TentativeDefinition)
1532 return 0;
1533
Chris Lattnerf0ed9ef2010-06-14 18:31:46 +00001534 VarDecl *LastTentative = 0;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001535 VarDecl *First = getFirstDeclaration();
1536 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1537 I != E; ++I) {
1538 Kind = (*I)->isThisDeclarationADefinition();
1539 if (Kind == Definition)
1540 return 0;
1541 else if (Kind == TentativeDefinition)
1542 LastTentative = *I;
1543 }
1544 return LastTentative;
1545}
1546
1547bool VarDecl::isTentativeDefinitionNow() const {
1548 DefinitionKind Kind = isThisDeclarationADefinition();
1549 if (Kind != TentativeDefinition)
1550 return false;
1551
1552 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1553 if ((*I)->isThisDeclarationADefinition() == Definition)
1554 return false;
1555 }
Sebastian Redl31310a22010-02-01 20:16:42 +00001556 return true;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001557}
1558
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001559VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redle2c52d22010-02-02 17:55:12 +00001560 VarDecl *First = getFirstDeclaration();
1561 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1562 I != E; ++I) {
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001563 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl31310a22010-02-01 20:16:42 +00001564 return *I;
1565 }
1566 return 0;
1567}
1568
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001569VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall110e8e52010-10-29 22:22:43 +00001570 DefinitionKind Kind = DeclarationOnly;
1571
1572 const VarDecl *First = getFirstDeclaration();
1573 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar047da192012-03-06 23:52:46 +00001574 I != E; ++I) {
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001575 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar047da192012-03-06 23:52:46 +00001576 if (Kind == Definition)
1577 break;
1578 }
John McCall110e8e52010-10-29 22:22:43 +00001579
1580 return Kind;
1581}
1582
Sebastian Redl31310a22010-02-01 20:16:42 +00001583const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001584 redecl_iterator I = redecls_begin(), E = redecls_end();
1585 while (I != E && !I->getInit())
1586 ++I;
1587
1588 if (I != E) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001589 D = *I;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001590 return I->getInit();
1591 }
1592 return 0;
1593}
1594
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001595bool VarDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00001596 if (Decl::isOutOfLine())
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001597 return true;
Chandler Carruth8761d682010-02-21 07:08:09 +00001598
1599 if (!isStaticDataMember())
1600 return false;
1601
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001602 // If this static data member was instantiated from a static data member of
1603 // a class template, check whether that static data member was defined
1604 // out-of-line.
1605 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1606 return VD->isOutOfLine();
1607
1608 return false;
1609}
1610
Douglas Gregor0d035142009-10-27 18:42:08 +00001611VarDecl *VarDecl::getOutOfLineDefinition() {
1612 if (!isStaticDataMember())
1613 return 0;
1614
1615 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1616 RD != RDEnd; ++RD) {
1617 if (RD->getLexicalDeclContext()->isFileContext())
1618 return *RD;
1619 }
1620
1621 return 0;
1622}
1623
Douglas Gregor838db382010-02-11 01:19:42 +00001624void VarDecl::setInit(Expr *I) {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001625 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1626 Eval->~EvaluatedStmt();
Douglas Gregor838db382010-02-11 01:19:42 +00001627 getASTContext().Deallocate(Eval);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001628 }
1629
1630 Init = I;
1631}
1632
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001633bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00001634 const LangOptions &Lang = C.getLangOpts();
Richard Smith1d238ea2011-12-21 02:55:12 +00001635
Richard Smith16581332012-03-02 04:14:40 +00001636 if (!Lang.CPlusPlus)
1637 return false;
1638
1639 // In C++11, any variable of reference type can be used in a constant
1640 // expression if it is initialized by a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00001641 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith16581332012-03-02 04:14:40 +00001642 return true;
1643
1644 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith1d238ea2011-12-21 02:55:12 +00001645 // not require the variable to be non-volatile, but we consider this to be a
1646 // defect.
Richard Smith16581332012-03-02 04:14:40 +00001647 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith1d238ea2011-12-21 02:55:12 +00001648 return false;
1649
1650 // In C++, const, non-volatile variables of integral or enumeration types
1651 // can be used in constant expressions.
1652 if (getType()->isIntegralOrEnumerationType())
1653 return true;
1654
Richard Smith16581332012-03-02 04:14:40 +00001655 // Additionally, in C++11, non-volatile constexpr variables can be used in
1656 // constant expressions.
Richard Smith80ad52f2013-01-02 11:42:31 +00001657 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith1d238ea2011-12-21 02:55:12 +00001658}
1659
Richard Smith099e7f62011-12-19 06:19:21 +00001660/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1661/// form, which contains extra information on the evaluated value of the
1662/// initializer.
1663EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1664 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1665 if (!Eval) {
1666 Stmt *S = Init.get<Stmt *>();
1667 Eval = new (getASTContext()) EvaluatedStmt;
1668 Eval->Value = S;
1669 Init = Eval;
1670 }
1671 return Eval;
1672}
1673
Richard Smith2d6a5672012-01-14 04:30:29 +00001674APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001675 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith2d6a5672012-01-14 04:30:29 +00001676 return evaluateValue(Notes);
1677}
1678
1679APValue *VarDecl::evaluateValue(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001680 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith099e7f62011-12-19 06:19:21 +00001681 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1682
1683 // We only produce notes indicating why an initializer is non-constant the
1684 // first time it is evaluated. FIXME: The notes won't always be emitted the
1685 // first time we try evaluation, so might not be produced at all.
1686 if (Eval->WasEvaluated)
Richard Smith2d6a5672012-01-14 04:30:29 +00001687 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smith099e7f62011-12-19 06:19:21 +00001688
1689 const Expr *Init = cast<Expr>(Eval->Value);
1690 assert(!Init->isValueDependent());
1691
1692 if (Eval->IsEvaluating) {
1693 // FIXME: Produce a diagnostic for self-initialization.
1694 Eval->CheckedICE = true;
1695 Eval->IsICE = false;
Richard Smith2d6a5672012-01-14 04:30:29 +00001696 return 0;
Richard Smith099e7f62011-12-19 06:19:21 +00001697 }
1698
1699 Eval->IsEvaluating = true;
1700
1701 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1702 this, Notes);
1703
1704 // Ensure the result is an uninitialized APValue if evaluation fails.
1705 if (!Result)
1706 Eval->Evaluated = APValue();
1707
1708 Eval->IsEvaluating = false;
1709 Eval->WasEvaluated = true;
1710
1711 // In C++11, we have determined whether the initializer was a constant
1712 // expression as a side-effect.
Richard Smith80ad52f2013-01-02 11:42:31 +00001713 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smith099e7f62011-12-19 06:19:21 +00001714 Eval->CheckedICE = true;
Eli Friedman210386e2012-02-06 21:50:18 +00001715 Eval->IsICE = Result && Notes.empty();
Richard Smith099e7f62011-12-19 06:19:21 +00001716 }
1717
Richard Smith2d6a5672012-01-14 04:30:29 +00001718 return Result ? &Eval->Evaluated : 0;
Richard Smith099e7f62011-12-19 06:19:21 +00001719}
1720
1721bool VarDecl::checkInitIsICE() const {
John McCall73076432012-01-05 00:13:19 +00001722 // Initializers of weak variables are never ICEs.
1723 if (isWeak())
1724 return false;
1725
Richard Smith099e7f62011-12-19 06:19:21 +00001726 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1727 if (Eval->CheckedICE)
1728 // We have already checked whether this subexpression is an
1729 // integral constant expression.
1730 return Eval->IsICE;
1731
1732 const Expr *Init = cast<Expr>(Eval->Value);
1733 assert(!Init->isValueDependent());
1734
1735 // In C++11, evaluate the initializer to check whether it's a constant
1736 // expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00001737 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001738 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00001739 evaluateValue(Notes);
1740 return Eval->IsICE;
1741 }
1742
1743 // It's an ICE whether or not the definition we found is
1744 // out-of-line. See DR 721 and the discussion in Clang PR
1745 // 6206 for details.
1746
1747 if (Eval->CheckingICE)
1748 return false;
1749 Eval->CheckingICE = true;
1750
1751 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1752 Eval->CheckingICE = false;
1753 Eval->CheckedICE = true;
1754 return Eval->IsICE;
1755}
1756
Douglas Gregor03e80032011-06-21 17:03:29 +00001757bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregor0b581082011-06-21 18:20:46 +00001758 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregor03e80032011-06-21 17:03:29 +00001759
1760 const Expr *E = getInit();
1761 if (!E)
1762 return false;
1763
1764 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1765 E = Cleanups->getSubExpr();
1766
1767 return isa<MaterializeTemporaryExpr>(E);
1768}
1769
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001770VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001771 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001772 return cast<VarDecl>(MSI->getInstantiatedFrom());
1773
1774 return 0;
1775}
1776
Douglas Gregor663b5a02009-10-14 20:14:33 +00001777TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redle9d12b62010-01-31 22:27:38 +00001778 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001779 return MSI->getTemplateSpecializationKind();
1780
1781 return TSK_Undeclared;
1782}
1783
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001784MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001785 return getASTContext().getInstantiatedFromStaticDataMember(this);
1786}
1787
Douglas Gregor0a897e32009-10-15 17:21:20 +00001788void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1789 SourceLocation PointOfInstantiation) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001790 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001791 assert(MSI && "Not an instantiated static data member?");
1792 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor0a897e32009-10-15 17:21:20 +00001793 if (TSK != TSK_ExplicitSpecialization &&
1794 PointOfInstantiation.isValid() &&
1795 MSI->getPointOfInstantiation().isInvalid())
1796 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001797}
1798
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001799//===----------------------------------------------------------------------===//
1800// ParmVarDecl Implementation
1801//===----------------------------------------------------------------------===//
Douglas Gregor275a3692009-03-10 23:43:53 +00001802
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001803ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001804 SourceLocation StartLoc,
1805 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001806 QualType T, TypeSourceInfo *TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001807 StorageClass S, StorageClass SCAsWritten,
1808 Expr *DefArg) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001809 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001810 S, SCAsWritten, DefArg);
Douglas Gregor275a3692009-03-10 23:43:53 +00001811}
1812
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001813ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1814 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1815 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1816 0, QualType(), 0, SC_None, SC_None, 0);
1817}
1818
Argyrios Kyrtzidis0bfe83b2011-07-30 17:23:26 +00001819SourceRange ParmVarDecl::getSourceRange() const {
1820 if (!hasInheritedDefaultArg()) {
1821 SourceRange ArgRange = getDefaultArgRange();
1822 if (ArgRange.isValid())
1823 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1824 }
1825
1826 return DeclaratorDecl::getSourceRange();
1827}
1828
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001829Expr *ParmVarDecl::getDefaultArg() {
1830 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1831 assert(!hasUninstantiatedDefaultArg() &&
1832 "Default argument is not yet instantiated!");
1833
1834 Expr *Arg = getInit();
John McCall4765fa02010-12-06 08:20:24 +00001835 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001836 return E->getSubExpr();
Douglas Gregor275a3692009-03-10 23:43:53 +00001837
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001838 return Arg;
1839}
1840
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001841SourceRange ParmVarDecl::getDefaultArgRange() const {
1842 if (const Expr *E = getInit())
1843 return E->getSourceRange();
1844
1845 if (hasUninstantiatedDefaultArg())
1846 return getUninstantiatedDefaultArg()->getSourceRange();
1847
1848 return SourceRange();
Argyrios Kyrtzidisfc7e2a82009-07-05 22:21:56 +00001849}
1850
Douglas Gregor1fe85ea2011-01-05 21:11:38 +00001851bool ParmVarDecl::isParameterPack() const {
1852 return isa<PackExpansionType>(getType());
1853}
1854
Ted Kremenekd211cb72011-10-06 05:00:56 +00001855void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1856 getASTContext().setParameterIndex(this, parameterIndex);
1857 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1858}
1859
1860unsigned ParmVarDecl::getParameterIndexLarge() const {
1861 return getASTContext().getParameterIndex(this);
1862}
1863
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001864//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00001865// FunctionDecl Implementation
1866//===----------------------------------------------------------------------===//
1867
Douglas Gregorda2142f2011-02-19 18:51:44 +00001868void FunctionDecl::getNameForDiagnostic(std::string &S,
1869 const PrintingPolicy &Policy,
1870 bool Qualified) const {
1871 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1872 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1873 if (TemplateArgs)
1874 S += TemplateSpecializationType::PrintTemplateArgumentList(
1875 TemplateArgs->data(),
1876 TemplateArgs->size(),
1877 Policy);
1878
1879}
1880
Ted Kremenek9498d382010-04-29 16:49:01 +00001881bool FunctionDecl::isVariadic() const {
1882 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1883 return FT->isVariadic();
1884 return false;
1885}
1886
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001887bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1888 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001889 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001890 Definition = *I;
1891 return true;
1892 }
1893 }
1894
1895 return false;
1896}
1897
Anders Carlssonffb945f2011-05-14 23:26:09 +00001898bool FunctionDecl::hasTrivialBody() const
1899{
1900 Stmt *S = getBody();
1901 if (!S) {
1902 // Since we don't have a body for this function, we don't know if it's
1903 // trivial or not.
1904 return false;
1905 }
1906
1907 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1908 return true;
1909 return false;
1910}
1911
Sean Hunt10620eb2011-05-06 20:44:56 +00001912bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1913 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Sean Huntcd10dec2011-05-23 23:14:04 +00001914 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Sean Hunt10620eb2011-05-06 20:44:56 +00001915 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1916 return true;
1917 }
1918 }
1919
1920 return false;
1921}
1922
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001923Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidisc37929c2009-07-14 03:20:21 +00001924 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1925 if (I->Body) {
1926 Definition = *I;
1927 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet8387e2a2011-04-22 22:18:13 +00001928 } else if (I->IsLateTemplateParsed) {
1929 Definition = *I;
1930 return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +00001931 }
1932 }
1933
1934 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001935}
1936
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001937void FunctionDecl::setBody(Stmt *B) {
1938 Body = B;
Douglas Gregorb5f35ba2010-12-06 17:49:01 +00001939 if (B)
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001940 EndRangeLoc = B->getLocEnd();
1941}
1942
Douglas Gregor21386642010-09-28 21:55:22 +00001943void FunctionDecl::setPure(bool P) {
1944 IsPure = P;
1945 if (P)
1946 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1947 Parent->markedVirtualFunctionPure();
1948}
1949
Douglas Gregor48a83b52009-09-12 00:17:51 +00001950bool FunctionDecl::isMain() const {
John McCall23c608d2011-05-15 17:49:20 +00001951 const TranslationUnitDecl *tunit =
1952 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1953 return tunit &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001954 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall23c608d2011-05-15 17:49:20 +00001955 getIdentifier() &&
1956 getIdentifier()->isStr("main");
1957}
1958
1959bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1960 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1961 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1962 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1963 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1964 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1965
1966 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1967 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1968
1969 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1970 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1971
1972 ASTContext &Context =
1973 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1974 ->getASTContext();
1975
1976 // The result type and first argument type are constant across all
1977 // these operators. The second argument must be exactly void*.
1978 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregor04495c82009-02-24 01:23:02 +00001979}
1980
Rafael Espindola950fee22013-02-14 01:18:37 +00001981LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindola6dcea672013-01-12 15:27:44 +00001982 // Users expect to be able to write
1983 // extern "C" void *__builtin_alloca (size_t);
1984 // so consider builtins as having C language linkage.
Rafael Espindola508276c2013-01-12 15:27:43 +00001985 if (getBuiltinID())
Rafael Espindola950fee22013-02-14 01:18:37 +00001986 return CLanguageLinkage;
Rafael Espindola508276c2013-01-12 15:27:43 +00001987
Rafael Espindola950fee22013-02-14 01:18:37 +00001988 return getLanguageLinkageTemplate(*this);
Rafael Espindola78eeba82012-12-28 14:21:58 +00001989}
1990
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001991bool FunctionDecl::isGlobal() const {
1992 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1993 return Method->isStatic();
1994
John McCalld931b082010-08-26 03:08:43 +00001995 if (getStorageClass() == SC_Static)
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001996 return false;
1997
Mike Stump1eb44332009-09-09 15:08:12 +00001998 for (const DeclContext *DC = getDeclContext();
Douglas Gregor8499f3f2009-03-31 16:35:03 +00001999 DC->isNamespace();
2000 DC = DC->getParent()) {
2001 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2002 if (!Namespace->getDeclName())
2003 return false;
2004 break;
2005 }
2006 }
2007
2008 return true;
2009}
2010
Richard Smithcd8ab512013-01-17 01:30:42 +00002011bool FunctionDecl::isNoReturn() const {
2012 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smith7586a6e2013-01-30 05:45:05 +00002013 hasAttr<C11NoReturnAttr>() ||
Richard Smithcd8ab512013-01-17 01:30:42 +00002014 getType()->getAs<FunctionType>()->getNoReturnAttr();
2015}
2016
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002017void
2018FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2019 redeclarable_base::setPreviousDeclaration(PrevDecl);
2020
2021 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2022 FunctionTemplateDecl *PrevFunTmpl
2023 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2024 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2025 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2026 }
Douglas Gregor8f150942010-12-09 16:59:22 +00002027
Axel Naumannd9d137e2011-11-08 18:21:06 +00002028 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregor8f150942010-12-09 16:59:22 +00002029 IsInline = true;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002030}
2031
2032const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2033 return getFirstDeclaration();
2034}
2035
2036FunctionDecl *FunctionDecl::getCanonicalDecl() {
2037 return getFirstDeclaration();
2038}
2039
Douglas Gregor381d34e2010-12-06 18:36:25 +00002040void FunctionDecl::setStorageClass(StorageClass SC) {
2041 assert(isLegalForFunction(SC));
2042 if (getStorageClass() != SC)
Rafael Espindola838dc592013-01-12 06:42:30 +00002043 ClearLinkageCache();
Douglas Gregor381d34e2010-12-06 18:36:25 +00002044
2045 SClass = SC;
2046}
2047
Douglas Gregor3e41d602009-02-13 23:20:09 +00002048/// \brief Returns a value indicating whether this function
2049/// corresponds to a builtin function.
2050///
2051/// The function corresponds to a built-in function if it is
2052/// declared at translation scope or within an extern "C" block and
2053/// its name matches with the name of a builtin. The returned value
2054/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump1eb44332009-09-09 15:08:12 +00002055/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregor3e41d602009-02-13 23:20:09 +00002056/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002057unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar60d302a2012-03-06 23:52:37 +00002058 if (!getIdentifier())
Douglas Gregor3c385e52009-02-14 18:57:46 +00002059 return 0;
2060
2061 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar60d302a2012-03-06 23:52:37 +00002062 if (!BuiltinID)
2063 return 0;
2064
2065 ASTContext &Context = getASTContext();
Douglas Gregor3c385e52009-02-14 18:57:46 +00002066 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2067 return BuiltinID;
2068
2069 // This function has the name of a known C library
2070 // function. Determine whether it actually refers to the C library
2071 // function or whether it just has the same name.
2072
Douglas Gregor9add3172009-02-17 03:23:10 +00002073 // If this is a static function, it's not a builtin.
John McCalld931b082010-08-26 03:08:43 +00002074 if (getStorageClass() == SC_Static)
Douglas Gregor9add3172009-02-17 03:23:10 +00002075 return 0;
2076
Douglas Gregor3c385e52009-02-14 18:57:46 +00002077 // If this function is at translation-unit scope and we're not in
2078 // C++, it refers to the C library function.
David Blaikie4e4d0842012-03-11 07:00:24 +00002079 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +00002080 getDeclContext()->isTranslationUnit())
2081 return BuiltinID;
2082
2083 // If the function is in an extern "C" linkage specification and is
2084 // not marked "overloadable", it's the real function.
2085 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002086 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregor3c385e52009-02-14 18:57:46 +00002087 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002088 !getAttr<OverloadableAttr>())
Douglas Gregor3c385e52009-02-14 18:57:46 +00002089 return BuiltinID;
2090
2091 // Not a builtin
Douglas Gregor3e41d602009-02-13 23:20:09 +00002092 return 0;
2093}
2094
2095
Chris Lattner1ad9b282009-04-25 06:03:53 +00002096/// getNumParams - Return the number of parameters this function must have
Bob Wilson8dbfbf42011-01-10 18:23:55 +00002097/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner1ad9b282009-04-25 06:03:53 +00002098/// after it has been created.
2099unsigned FunctionDecl::getNumParams() const {
Eli Friedman482466b2012-08-30 22:22:09 +00002100 const FunctionType *FT = getType()->castAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002101 if (isa<FunctionNoProtoType>(FT))
Chris Lattnerd3b90652008-03-15 05:43:15 +00002102 return 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00002103 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +00002104
Reid Spencer5f016e22007-07-11 17:01:13 +00002105}
2106
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002107void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002108 ArrayRef<ParmVarDecl *> NewParamInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002109 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie4278c652011-09-21 18:16:56 +00002110 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00002113 if (!NewParamInfo.empty()) {
2114 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2115 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 }
2117}
2118
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002119void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy16f1f712012-02-29 10:24:19 +00002120 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2121
2122 if (!NewDecls.empty()) {
2123 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2124 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002125 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy16f1f712012-02-29 10:24:19 +00002126 }
2127}
2128
Chris Lattner8123a952008-04-10 02:22:51 +00002129/// getMinRequiredArguments - Returns the minimum number of arguments
2130/// needed to call this function. This may be fewer than the number of
2131/// function parameters, if some of the parameters have default
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002132/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner8123a952008-04-10 02:22:51 +00002133unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikie4e4d0842012-03-11 07:00:24 +00002134 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002135 return getNumParams();
2136
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002137 unsigned NumRequiredArgs = getNumParams();
2138
2139 // If the last parameter is a parameter pack, we don't need an argument for
2140 // it.
2141 if (NumRequiredArgs > 0 &&
2142 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2143 --NumRequiredArgs;
2144
2145 // If this parameter has a default argument, we don't need an argument for
2146 // it.
2147 while (NumRequiredArgs > 0 &&
2148 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner8123a952008-04-10 02:22:51 +00002149 --NumRequiredArgs;
2150
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002151 // We might have parameter packs before the end. These can't be deduced,
2152 // but they can still handle multiple arguments.
2153 unsigned ArgIdx = NumRequiredArgs;
2154 while (ArgIdx > 0) {
2155 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2156 NumRequiredArgs = ArgIdx;
2157
2158 --ArgIdx;
2159 }
2160
Chris Lattner8123a952008-04-10 02:22:51 +00002161 return NumRequiredArgs;
2162}
2163
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002164static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2165 // Only consider file-scope declarations in this test.
2166 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2167 return false;
2168
2169 // Only consider explicit declarations; the presence of a builtin for a
2170 // libcall shouldn't affect whether a definition is externally visible.
2171 if (Redecl->isImplicit())
2172 return false;
2173
2174 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2175 return true; // Not an inline definition
2176
2177 return false;
2178}
2179
Nick Lewyckydce67a72011-07-18 05:26:13 +00002180/// \brief For a function declaration in C or C++, determine whether this
2181/// declaration causes the definition to be externally visible.
2182///
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002183/// Specifically, this determines if adding the current declaration to the set
2184/// of redeclarations of the given functions causes
2185/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewyckydce67a72011-07-18 05:26:13 +00002186bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2187 assert(!doesThisDeclarationHaveABody() &&
2188 "Must have a declaration without a body.");
2189
2190 ASTContext &Context = getASTContext();
2191
David Blaikie4e4d0842012-03-11 07:00:24 +00002192 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002193 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2194 // an externally visible definition.
2195 //
2196 // FIXME: What happens if gnu_inline gets added on after the first
2197 // declaration?
2198 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
2199 return false;
2200
2201 const FunctionDecl *Prev = this;
2202 bool FoundBody = false;
2203 while ((Prev = Prev->getPreviousDecl())) {
2204 FoundBody |= Prev->Body;
2205
2206 if (Prev->Body) {
2207 // If it's not the case that both 'inline' and 'extern' are
2208 // specified on the definition, then it is always externally visible.
2209 if (!Prev->isInlineSpecified() ||
2210 Prev->getStorageClassAsWritten() != SC_Extern)
2211 return false;
2212 } else if (Prev->isInlineSpecified() &&
2213 Prev->getStorageClassAsWritten() != SC_Extern) {
2214 return false;
2215 }
2216 }
2217 return FoundBody;
2218 }
2219
David Blaikie4e4d0842012-03-11 07:00:24 +00002220 if (Context.getLangOpts().CPlusPlus)
Nick Lewyckydce67a72011-07-18 05:26:13 +00002221 return false;
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002222
2223 // C99 6.7.4p6:
2224 // [...] If all of the file scope declarations for a function in a
2225 // translation unit include the inline function specifier without extern,
2226 // then the definition in that translation unit is an inline definition.
2227 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewyckydce67a72011-07-18 05:26:13 +00002228 return false;
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002229 const FunctionDecl *Prev = this;
2230 bool FoundBody = false;
2231 while ((Prev = Prev->getPreviousDecl())) {
2232 FoundBody |= Prev->Body;
2233 if (RedeclForcesDefC99(Prev))
2234 return false;
2235 }
2236 return FoundBody;
Nick Lewyckydce67a72011-07-18 05:26:13 +00002237}
2238
Richard Smithd4497dd2013-01-25 00:08:28 +00002239/// \brief For an inline function definition in C, or for a gnu_inline function
2240/// in C++, determine whether the definition will be externally visible.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002241///
2242/// Inline function definitions are always available for inlining optimizations.
2243/// However, depending on the language dialect, declaration specifiers, and
2244/// attributes, the definition of an inline function may or may not be
2245/// "externally" visible to other translation units in the program.
2246///
2247/// In C99, inline definitions are not externally visible by default. However,
Mike Stump1e5fd7f2010-01-06 02:05:39 +00002248/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002249/// inline definition becomes externally visible (C99 6.7.4p6).
2250///
2251/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2252/// definition, we use the GNU semantics for inline, which are nearly the
2253/// opposite of C99 semantics. In particular, "inline" by itself will create
2254/// an externally visible symbol, but "extern inline" will not create an
2255/// externally visible symbol.
2256bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Sean Hunt10620eb2011-05-06 20:44:56 +00002257 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002258 assert(isInlined() && "Function must be inline");
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00002259 ASTContext &Context = getASTContext();
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002260
David Blaikie4e4d0842012-03-11 07:00:24 +00002261 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002262 // Note: If you change the logic here, please change
2263 // doesDeclarationForceExternallyVisibleDefinition as well.
2264 //
Douglas Gregor8f150942010-12-09 16:59:22 +00002265 // If it's not the case that both 'inline' and 'extern' are
2266 // specified on the definition, then this inline definition is
2267 // externally visible.
2268 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2269 return true;
2270
2271 // If any declaration is 'inline' but not 'extern', then this definition
2272 // is externally visible.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002273 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2274 Redecl != RedeclEnd;
2275 ++Redecl) {
Douglas Gregor8f150942010-12-09 16:59:22 +00002276 if (Redecl->isInlineSpecified() &&
2277 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002278 return true;
Douglas Gregor8f150942010-12-09 16:59:22 +00002279 }
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002280
Douglas Gregor9f9bf252009-04-28 06:37:30 +00002281 return false;
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002282 }
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002283
Richard Smithd4497dd2013-01-25 00:08:28 +00002284 // The rest of this function is C-only.
2285 assert(!Context.getLangOpts().CPlusPlus &&
2286 "should not use C inline rules in C++");
2287
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002288 // C99 6.7.4p6:
2289 // [...] If all of the file scope declarations for a function in a
2290 // translation unit include the inline function specifier without extern,
2291 // then the definition in that translation unit is an inline definition.
2292 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2293 Redecl != RedeclEnd;
2294 ++Redecl) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002295 if (RedeclForcesDefC99(*Redecl))
2296 return true;
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002297 }
2298
2299 // C99 6.7.4p6:
2300 // An inline definition does not provide an external definition for the
2301 // function, and does not forbid an external definition in another
2302 // translation unit.
Douglas Gregor9f9bf252009-04-28 06:37:30 +00002303 return false;
2304}
2305
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002306/// getOverloadedOperator - Which C++ overloaded operator this
2307/// function represents, if any.
2308OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregore94ca9e42008-11-18 14:39:36 +00002309 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2310 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002311 else
2312 return OO_None;
2313}
2314
Sean Hunta6c058d2010-01-13 09:01:02 +00002315/// getLiteralIdentifier - The literal suffix identifier this function
2316/// represents, if any.
2317const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2318 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2319 return getDeclName().getCXXLiteralIdentifier();
2320 else
2321 return 0;
2322}
2323
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002324FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2325 if (TemplateOrSpecialization.isNull())
2326 return TK_NonTemplate;
2327 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2328 return TK_FunctionTemplate;
2329 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2330 return TK_MemberSpecialization;
2331 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2332 return TK_FunctionTemplateSpecialization;
2333 if (TemplateOrSpecialization.is
2334 <DependentFunctionTemplateSpecializationInfo*>())
2335 return TK_DependentFunctionTemplateSpecialization;
2336
David Blaikieb219cfc2011-09-23 05:06:16 +00002337 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002338}
2339
Douglas Gregor2db32322009-10-07 23:56:10 +00002340FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002341 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregor2db32322009-10-07 23:56:10 +00002342 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2343
2344 return 0;
2345}
2346
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002347MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2348 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2349}
2350
Douglas Gregor2db32322009-10-07 23:56:10 +00002351void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002352FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2353 FunctionDecl *FD,
Douglas Gregor2db32322009-10-07 23:56:10 +00002354 TemplateSpecializationKind TSK) {
2355 assert(TemplateOrSpecialization.isNull() &&
2356 "Member function is already a specialization");
2357 MemberSpecializationInfo *Info
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002358 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregor2db32322009-10-07 23:56:10 +00002359 TemplateOrSpecialization = Info;
2360}
2361
Douglas Gregor3b846b62009-10-27 20:53:28 +00002362bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002363 // If the function is invalid, it can't be implicitly instantiated.
2364 if (isInvalidDecl())
Douglas Gregor3b846b62009-10-27 20:53:28 +00002365 return false;
2366
2367 switch (getTemplateSpecializationKind()) {
2368 case TSK_Undeclared:
Douglas Gregor3b846b62009-10-27 20:53:28 +00002369 case TSK_ExplicitInstantiationDefinition:
2370 return false;
2371
2372 case TSK_ImplicitInstantiation:
2373 return true;
2374
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002375 // It is possible to instantiate TSK_ExplicitSpecialization kind
2376 // if the FunctionDecl has a class scope specialization pattern.
2377 case TSK_ExplicitSpecialization:
2378 return getClassScopeSpecializationPattern() != 0;
2379
Douglas Gregor3b846b62009-10-27 20:53:28 +00002380 case TSK_ExplicitInstantiationDeclaration:
2381 // Handled below.
2382 break;
2383 }
2384
2385 // Find the actual template from which we will instantiate.
2386 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002387 bool HasPattern = false;
Douglas Gregor3b846b62009-10-27 20:53:28 +00002388 if (PatternDecl)
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002389 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregor3b846b62009-10-27 20:53:28 +00002390
2391 // C++0x [temp.explicit]p9:
2392 // Except for inline functions, other explicit instantiation declarations
2393 // have the effect of suppressing the implicit instantiation of the entity
2394 // to which they refer.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002395 if (!HasPattern || !PatternDecl)
Douglas Gregor3b846b62009-10-27 20:53:28 +00002396 return true;
2397
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002398 return PatternDecl->isInlined();
Ted Kremenek75df4ee2011-12-01 00:59:17 +00002399}
2400
2401bool FunctionDecl::isTemplateInstantiation() const {
2402 switch (getTemplateSpecializationKind()) {
2403 case TSK_Undeclared:
2404 case TSK_ExplicitSpecialization:
2405 return false;
2406 case TSK_ImplicitInstantiation:
2407 case TSK_ExplicitInstantiationDeclaration:
2408 case TSK_ExplicitInstantiationDefinition:
2409 return true;
2410 }
2411 llvm_unreachable("All TSK values handled.");
2412}
Douglas Gregor3b846b62009-10-27 20:53:28 +00002413
2414FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002415 // Handle class scope explicit specialization special case.
2416 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2417 return getClassScopeSpecializationPattern();
2418
Douglas Gregor3b846b62009-10-27 20:53:28 +00002419 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2420 while (Primary->getInstantiatedFromMemberTemplate()) {
2421 // If we have hit a point where the user provided a specialization of
2422 // this template, we're done looking.
2423 if (Primary->isMemberSpecialization())
2424 break;
2425
2426 Primary = Primary->getInstantiatedFromMemberTemplate();
2427 }
2428
2429 return Primary->getTemplatedDecl();
2430 }
2431
2432 return getInstantiatedFromMemberFunction();
2433}
2434
Douglas Gregor16e8be22009-06-29 17:30:29 +00002435FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002436 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00002437 = TemplateOrSpecialization
2438 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002439 return Info->Template.getPointer();
Douglas Gregor16e8be22009-06-29 17:30:29 +00002440 }
2441 return 0;
2442}
2443
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002444FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2445 return getASTContext().getClassScopeSpecializationPattern(this);
2446}
2447
Douglas Gregor16e8be22009-06-29 17:30:29 +00002448const TemplateArgumentList *
2449FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002450 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002451 = TemplateOrSpecialization
2452 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor16e8be22009-06-29 17:30:29 +00002453 return Info->TemplateArguments;
2454 }
2455 return 0;
2456}
2457
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00002458const ASTTemplateArgumentListInfo *
Abramo Bagnarae03db982010-05-20 15:32:11 +00002459FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2460 if (FunctionTemplateSpecializationInfo *Info
2461 = TemplateOrSpecialization
2462 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2463 return Info->TemplateArgumentsAsWritten;
2464 }
2465 return 0;
2466}
2467
Mike Stump1eb44332009-09-09 15:08:12 +00002468void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002469FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2470 FunctionTemplateDecl *Template,
Douglas Gregor127102b2009-06-29 20:59:39 +00002471 const TemplateArgumentList *TemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002472 void *InsertPos,
Abramo Bagnarae03db982010-05-20 15:32:11 +00002473 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis7b081c82010-07-05 10:37:55 +00002474 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2475 SourceLocation PointOfInstantiation) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002476 assert(TSK != TSK_Undeclared &&
2477 "Must specify the type of function template specialization");
Mike Stump1eb44332009-09-09 15:08:12 +00002478 FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00002479 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor1637be72009-06-26 00:10:03 +00002480 if (!Info)
Argyrios Kyrtzidisa626a3d2010-09-09 11:28:23 +00002481 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2482 TemplateArgs,
2483 TemplateArgsAsWritten,
2484 PointOfInstantiation);
Douglas Gregor1637be72009-06-26 00:10:03 +00002485 TemplateOrSpecialization = Info;
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002486 Template->addSpecialization(Info, InsertPos);
Douglas Gregor1637be72009-06-26 00:10:03 +00002487}
2488
John McCallaf2094e2010-04-08 09:05:18 +00002489void
2490FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2491 const UnresolvedSetImpl &Templates,
2492 const TemplateArgumentListInfo &TemplateArgs) {
2493 assert(TemplateOrSpecialization.isNull());
2494 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2495 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall21c01602010-04-13 22:18:28 +00002496 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallaf2094e2010-04-08 09:05:18 +00002497 void *Buffer = Context.Allocate(Size);
2498 DependentFunctionTemplateSpecializationInfo *Info =
2499 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2500 TemplateArgs);
2501 TemplateOrSpecialization = Info;
2502}
2503
2504DependentFunctionTemplateSpecializationInfo::
2505DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2506 const TemplateArgumentListInfo &TArgs)
2507 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2508
2509 d.NumTemplates = Ts.size();
2510 d.NumArgs = TArgs.size();
2511
2512 FunctionTemplateDecl **TsArray =
2513 const_cast<FunctionTemplateDecl**>(getTemplates());
2514 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2515 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2516
2517 TemplateArgumentLoc *ArgsArray =
2518 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2519 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2520 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2521}
2522
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002523TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002524 // For a function template specialization, query the specialization
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002525 // information object.
Douglas Gregor2db32322009-10-07 23:56:10 +00002526 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002527 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor2db32322009-10-07 23:56:10 +00002528 if (FTSInfo)
2529 return FTSInfo->getTemplateSpecializationKind();
Mike Stump1eb44332009-09-09 15:08:12 +00002530
Douglas Gregor2db32322009-10-07 23:56:10 +00002531 MemberSpecializationInfo *MSInfo
2532 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2533 if (MSInfo)
2534 return MSInfo->getTemplateSpecializationKind();
2535
2536 return TSK_Undeclared;
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002537}
2538
Mike Stump1eb44332009-09-09 15:08:12 +00002539void
Douglas Gregor0a897e32009-10-15 17:21:20 +00002540FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2541 SourceLocation PointOfInstantiation) {
2542 if (FunctionTemplateSpecializationInfo *FTSInfo
2543 = TemplateOrSpecialization.dyn_cast<
2544 FunctionTemplateSpecializationInfo*>()) {
2545 FTSInfo->setTemplateSpecializationKind(TSK);
2546 if (TSK != TSK_ExplicitSpecialization &&
2547 PointOfInstantiation.isValid() &&
2548 FTSInfo->getPointOfInstantiation().isInvalid())
2549 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2550 } else if (MemberSpecializationInfo *MSInfo
2551 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2552 MSInfo->setTemplateSpecializationKind(TSK);
2553 if (TSK != TSK_ExplicitSpecialization &&
2554 PointOfInstantiation.isValid() &&
2555 MSInfo->getPointOfInstantiation().isInvalid())
2556 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2557 } else
David Blaikieb219cfc2011-09-23 05:06:16 +00002558 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor0a897e32009-10-15 17:21:20 +00002559}
2560
2561SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregor2db32322009-10-07 23:56:10 +00002562 if (FunctionTemplateSpecializationInfo *FTSInfo
2563 = TemplateOrSpecialization.dyn_cast<
2564 FunctionTemplateSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00002565 return FTSInfo->getPointOfInstantiation();
Douglas Gregor2db32322009-10-07 23:56:10 +00002566 else if (MemberSpecializationInfo *MSInfo
2567 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00002568 return MSInfo->getPointOfInstantiation();
2569
2570 return SourceLocation();
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002571}
2572
Douglas Gregor9f185072009-09-11 20:15:17 +00002573bool FunctionDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00002574 if (Decl::isOutOfLine())
Douglas Gregor9f185072009-09-11 20:15:17 +00002575 return true;
2576
2577 // If this function was instantiated from a member function of a
2578 // class template, check whether that member function was defined out-of-line.
2579 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2580 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002581 if (FD->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00002582 return Definition->isOutOfLine();
2583 }
2584
2585 // If this function was instantiated from a function template,
2586 // check whether that function template was defined out-of-line.
2587 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2588 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002589 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00002590 return Definition->isOutOfLine();
2591 }
2592
2593 return false;
2594}
2595
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002596SourceRange FunctionDecl::getSourceRange() const {
2597 return SourceRange(getOuterLocStart(), EndRangeLoc);
2598}
2599
Anna Zaks9392d4e2012-01-18 02:45:01 +00002600unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaksd9b859a2012-01-13 21:52:01 +00002601 IdentifierInfo *FnInfo = getIdentifier();
2602
2603 if (!FnInfo)
Anna Zaks0a151a12012-01-17 00:37:07 +00002604 return 0;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002605
2606 // Builtin handling.
2607 switch (getBuiltinID()) {
2608 case Builtin::BI__builtin_memset:
2609 case Builtin::BI__builtin___memset_chk:
2610 case Builtin::BImemset:
Anna Zaks0a151a12012-01-17 00:37:07 +00002611 return Builtin::BImemset;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002612
2613 case Builtin::BI__builtin_memcpy:
2614 case Builtin::BI__builtin___memcpy_chk:
2615 case Builtin::BImemcpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002616 return Builtin::BImemcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002617
2618 case Builtin::BI__builtin_memmove:
2619 case Builtin::BI__builtin___memmove_chk:
2620 case Builtin::BImemmove:
Anna Zaks0a151a12012-01-17 00:37:07 +00002621 return Builtin::BImemmove;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002622
2623 case Builtin::BIstrlcpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002624 return Builtin::BIstrlcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002625 case Builtin::BIstrlcat:
Anna Zaks0a151a12012-01-17 00:37:07 +00002626 return Builtin::BIstrlcat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002627
2628 case Builtin::BI__builtin_memcmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002629 case Builtin::BImemcmp:
2630 return Builtin::BImemcmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002631
2632 case Builtin::BI__builtin_strncpy:
2633 case Builtin::BI__builtin___strncpy_chk:
2634 case Builtin::BIstrncpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002635 return Builtin::BIstrncpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002636
2637 case Builtin::BI__builtin_strncmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002638 case Builtin::BIstrncmp:
2639 return Builtin::BIstrncmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002640
2641 case Builtin::BI__builtin_strncasecmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002642 case Builtin::BIstrncasecmp:
2643 return Builtin::BIstrncasecmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002644
2645 case Builtin::BI__builtin_strncat:
Anna Zaksc36bedc2012-02-01 19:08:57 +00002646 case Builtin::BI__builtin___strncat_chk:
Anna Zaksd9b859a2012-01-13 21:52:01 +00002647 case Builtin::BIstrncat:
Anna Zaks0a151a12012-01-17 00:37:07 +00002648 return Builtin::BIstrncat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002649
2650 case Builtin::BI__builtin_strndup:
2651 case Builtin::BIstrndup:
Anna Zaks0a151a12012-01-17 00:37:07 +00002652 return Builtin::BIstrndup;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002653
Anna Zaksc36bedc2012-02-01 19:08:57 +00002654 case Builtin::BI__builtin_strlen:
2655 case Builtin::BIstrlen:
2656 return Builtin::BIstrlen;
2657
Anna Zaksd9b859a2012-01-13 21:52:01 +00002658 default:
Rafael Espindolad2fdd422013-02-14 01:47:04 +00002659 if (isExternC()) {
Anna Zaksd9b859a2012-01-13 21:52:01 +00002660 if (FnInfo->isStr("memset"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002661 return Builtin::BImemset;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002662 else if (FnInfo->isStr("memcpy"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002663 return Builtin::BImemcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002664 else if (FnInfo->isStr("memmove"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002665 return Builtin::BImemmove;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002666 else if (FnInfo->isStr("memcmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002667 return Builtin::BImemcmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002668 else if (FnInfo->isStr("strncpy"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002669 return Builtin::BIstrncpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002670 else if (FnInfo->isStr("strncmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002671 return Builtin::BIstrncmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002672 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002673 return Builtin::BIstrncasecmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002674 else if (FnInfo->isStr("strncat"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002675 return Builtin::BIstrncat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002676 else if (FnInfo->isStr("strndup"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002677 return Builtin::BIstrndup;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002678 else if (FnInfo->isStr("strlen"))
2679 return Builtin::BIstrlen;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002680 }
2681 break;
2682 }
Anna Zaks0a151a12012-01-17 00:37:07 +00002683 return 0;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002684}
2685
Chris Lattner8a934232008-03-31 00:36:02 +00002686//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002687// FieldDecl Implementation
2688//===----------------------------------------------------------------------===//
2689
Jay Foad4ba2a172011-01-12 09:06:06 +00002690FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002691 SourceLocation StartLoc, SourceLocation IdLoc,
2692 IdentifierInfo *Id, QualType T,
Richard Smith7a614d82011-06-11 17:19:42 +00002693 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smithca523302012-06-10 03:12:00 +00002694 InClassInitStyle InitStyle) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002695 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +00002696 BW, Mutable, InitStyle);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002697}
2698
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002699FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2700 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2701 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
Richard Smithca523302012-06-10 03:12:00 +00002702 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002703}
2704
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002705bool FieldDecl::isAnonymousStructOrUnion() const {
2706 if (!isImplicit() || getDeclName())
2707 return false;
2708
2709 if (const RecordType *Record = getType()->getAs<RecordType>())
2710 return Record->getDecl()->isAnonymousStructOrUnion();
2711
2712 return false;
2713}
2714
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002715unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2716 assert(isBitField() && "not a bitfield");
2717 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2718 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2719}
2720
John McCallba4f5d52011-01-20 07:57:12 +00002721unsigned FieldDecl::getFieldIndex() const {
2722 if (CachedFieldIndex) return CachedFieldIndex - 1;
2723
Richard Smith180f4792011-11-10 06:34:14 +00002724 unsigned Index = 0;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002725 const RecordDecl *RD = getParent();
2726 const FieldDecl *LastFD = 0;
Eli Friedman5f608ae2012-10-12 23:29:20 +00002727 bool IsMsStruct = RD->isMsStruct(getASTContext());
Richard Smith180f4792011-11-10 06:34:14 +00002728
2729 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2730 I != E; ++I, ++Index) {
David Blaikie262bc182012-04-30 02:36:29 +00002731 I->CachedFieldIndex = Index + 1;
John McCallba4f5d52011-01-20 07:57:12 +00002732
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002733 if (IsMsStruct) {
2734 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie581deb32012-06-06 20:45:41 +00002735 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
Richard Smith180f4792011-11-10 06:34:14 +00002736 --Index;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002737 continue;
2738 }
David Blaikie581deb32012-06-06 20:45:41 +00002739 LastFD = *I;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002740 }
John McCallba4f5d52011-01-20 07:57:12 +00002741 }
2742
Richard Smith180f4792011-11-10 06:34:14 +00002743 assert(CachedFieldIndex && "failed to find field in parent");
2744 return CachedFieldIndex - 1;
John McCallba4f5d52011-01-20 07:57:12 +00002745}
2746
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00002747SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnarad330e232011-08-05 08:02:55 +00002748 if (const Expr *E = InitializerOrBitWidth.getPointer())
2749 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002750 return DeclaratorDecl::getSourceRange();
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00002751}
2752
Abramo Bagnaraa5335762012-07-02 20:35:48 +00002753void FieldDecl::setBitWidth(Expr *Width) {
2754 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2755 "bit width or initializer already set");
2756 InitializerOrBitWidth.setPointer(Width);
2757}
2758
Richard Smith7a614d82011-06-11 17:19:42 +00002759void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smithca523302012-06-10 03:12:00 +00002760 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith7a614d82011-06-11 17:19:42 +00002761 "bit width or initializer already set");
2762 InitializerOrBitWidth.setPointer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002763}
2764
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002765//===----------------------------------------------------------------------===//
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002766// TagDecl Implementation
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002767//===----------------------------------------------------------------------===//
2768
Douglas Gregor1693e152010-07-06 18:42:40 +00002769SourceLocation TagDecl::getOuterLocStart() const {
2770 return getTemplateOrInnerLocStart(this);
2771}
2772
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00002773SourceRange TagDecl::getSourceRange() const {
2774 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregor1693e152010-07-06 18:42:40 +00002775 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00002776}
2777
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00002778TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002779 return getFirstDeclaration();
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00002780}
2781
Richard Smith162e1c12011-04-15 14:24:37 +00002782void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2783 TypedefNameDeclOrQualifier = TDD;
Douglas Gregor60e70642010-05-19 18:39:18 +00002784 if (TypeForDecl)
Rafael Espindola838dc592013-01-12 06:42:30 +00002785 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2786 ClearLinkageCache();
Douglas Gregor60e70642010-05-19 18:39:18 +00002787}
2788
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002789void TagDecl::startDefinition() {
Sebastian Redled48a8f2010-08-02 18:27:05 +00002790 IsBeingDefined = true;
John McCall86ff3082010-02-04 22:26:26 +00002791
David Blaikie66cff722012-11-14 01:52:05 +00002792 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall86ff3082010-02-04 22:26:26 +00002793 struct CXXRecordDecl::DefinitionData *Data =
2794 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall22432882010-03-26 21:56:38 +00002795 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2796 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall86ff3082010-02-04 22:26:26 +00002797 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002798}
2799
2800void TagDecl::completeDefinition() {
John McCall5cfa0112010-02-05 01:33:36 +00002801 assert((!isa<CXXRecordDecl>(this) ||
2802 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2803 "definition completed but not started");
2804
John McCall5e1cdac2011-10-07 06:10:15 +00002805 IsCompleteDefinition = true;
Sebastian Redled48a8f2010-08-02 18:27:05 +00002806 IsBeingDefined = false;
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00002807
2808 if (ASTMutationListener *L = getASTMutationListener())
2809 L->CompletedTagDefinition(this);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002810}
2811
John McCall5e1cdac2011-10-07 06:10:15 +00002812TagDecl *TagDecl::getDefinition() const {
2813 if (isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002814 return const_cast<TagDecl *>(this);
Douglas Gregor6bd99292013-02-09 01:35:03 +00002815
2816 // If it's possible for us to have an out-of-date definition, check now.
2817 if (MayHaveOutOfDateDef) {
2818 if (IdentifierInfo *II = getIdentifier()) {
2819 if (II->isOutOfDate()) {
2820 updateOutOfDate(*II);
2821 }
2822 }
2823 }
2824
Andrew Trick220a9c82010-10-19 21:54:32 +00002825 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2826 return CXXRD->getDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002827
2828 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002829 R != REnd; ++R)
John McCall5e1cdac2011-10-07 06:10:15 +00002830 if (R->isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002831 return *R;
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002833 return 0;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002834}
2835
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002836void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2837 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00002838 // Make sure the extended qualifier info is allocated.
2839 if (!hasExtInfo())
Richard Smith162e1c12011-04-15 14:24:37 +00002840 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCallb6217662010-03-15 10:12:16 +00002841 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002842 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00002843 } else {
John McCallb6217662010-03-15 10:12:16 +00002844 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00002845 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002846 if (getExtInfo()->NumTemplParamLists == 0) {
2847 getASTContext().Deallocate(getExtInfo());
Richard Smith162e1c12011-04-15 14:24:37 +00002848 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002849 }
2850 else
2851 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00002852 }
2853 }
2854}
2855
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002856void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2857 unsigned NumTPLists,
2858 TemplateParameterList **TPLists) {
2859 assert(NumTPLists > 0);
2860 // Make sure the extended decl info is allocated.
2861 if (!hasExtInfo())
2862 // Allocate external info struct.
Richard Smith162e1c12011-04-15 14:24:37 +00002863 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002864 // Set the template parameter lists info.
2865 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2866}
2867
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002868//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002869// EnumDecl Implementation
2870//===----------------------------------------------------------------------===//
2871
David Blaikie99ba9e32011-12-20 02:48:34 +00002872void EnumDecl::anchor() { }
2873
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002874EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2875 SourceLocation StartLoc, SourceLocation IdLoc,
2876 IdentifierInfo *Id,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00002877 EnumDecl *PrevDecl, bool IsScoped,
2878 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002879 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00002880 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor6bd99292013-02-09 01:35:03 +00002881 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002882 C.getTypeDeclType(Enum, PrevDecl);
2883 return Enum;
2884}
2885
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002886EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2887 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
Douglas Gregor6bd99292013-02-09 01:35:03 +00002888 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2889 0, 0, false, false, false);
2890 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2891 return Enum;
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00002892}
2893
Douglas Gregor838db382010-02-11 01:19:42 +00002894void EnumDecl::completeDefinition(QualType NewType,
John McCall1b5a6182010-05-06 08:49:23 +00002895 QualType NewPromotionType,
2896 unsigned NumPositiveBits,
2897 unsigned NumNegativeBits) {
John McCall5e1cdac2011-10-07 06:10:15 +00002898 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor1274ccd2010-10-08 23:50:27 +00002899 if (!IntegerType)
2900 IntegerType = NewType.getTypePtr();
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002901 PromotionType = NewPromotionType;
John McCall1b5a6182010-05-06 08:49:23 +00002902 setNumPositiveBits(NumPositiveBits);
2903 setNumNegativeBits(NumNegativeBits);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002904 TagDecl::completeDefinition();
2905}
2906
Richard Smith1af83c42012-03-23 03:33:32 +00002907TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2908 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2909 return MSI->getTemplateSpecializationKind();
2910
2911 return TSK_Undeclared;
2912}
2913
2914void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2915 SourceLocation PointOfInstantiation) {
2916 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2917 assert(MSI && "Not an instantiated member enumeration?");
2918 MSI->setTemplateSpecializationKind(TSK);
2919 if (TSK != TSK_ExplicitSpecialization &&
2920 PointOfInstantiation.isValid() &&
2921 MSI->getPointOfInstantiation().isInvalid())
2922 MSI->setPointOfInstantiation(PointOfInstantiation);
2923}
2924
Richard Smithf1c66b42012-03-14 23:13:10 +00002925EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2926 if (SpecializationInfo)
2927 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2928
2929 return 0;
2930}
2931
2932void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2933 TemplateSpecializationKind TSK) {
2934 assert(!SpecializationInfo && "Member enum is already a specialization");
2935 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2936}
2937
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002938//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00002939// RecordDecl Implementation
2940//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00002941
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002942RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2943 SourceLocation StartLoc, SourceLocation IdLoc,
2944 IdentifierInfo *Id, RecordDecl *PrevDecl)
2945 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek63597922008-09-02 21:12:32 +00002946 HasFlexibleArrayMember = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002947 AnonymousStructOrUnion = false;
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00002948 HasObjectMember = false;
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +00002949 HasVolatileMember = false;
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002950 LoadedFieldsFromExternalStorage = false;
Ted Kremenek63597922008-09-02 21:12:32 +00002951 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek63597922008-09-02 21:12:32 +00002952}
2953
Jay Foad4ba2a172011-01-12 09:06:06 +00002954RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002955 SourceLocation StartLoc, SourceLocation IdLoc,
2956 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2957 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2958 PrevDecl);
Douglas Gregor6bd99292013-02-09 01:35:03 +00002959 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2960
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002961 C.getTypeDeclType(R, PrevDecl);
2962 return R;
Ted Kremenek63597922008-09-02 21:12:32 +00002963}
2964
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002965RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2966 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
Douglas Gregor6bd99292013-02-09 01:35:03 +00002967 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2968 SourceLocation(), 0, 0);
2969 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2970 return R;
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00002971}
2972
Douglas Gregorc9b5b402009-03-25 15:59:44 +00002973bool RecordDecl::isInjectedClassName() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002974 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregorc9b5b402009-03-25 15:59:44 +00002975 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2976}
2977
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00002978RecordDecl::field_iterator RecordDecl::field_begin() const {
2979 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2980 LoadFieldsFromExternalStorage();
2981
2982 return field_iterator(decl_iterator(FirstDecl));
2983}
2984
Douglas Gregorda2142f2011-02-19 18:51:44 +00002985/// completeDefinition - Notes that the definition of this type is now
2986/// complete.
2987void RecordDecl::completeDefinition() {
John McCall5e1cdac2011-10-07 06:10:15 +00002988 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorda2142f2011-02-19 18:51:44 +00002989 TagDecl::completeDefinition();
2990}
2991
Eli Friedman5f608ae2012-10-12 23:29:20 +00002992/// isMsStruct - Get whether or not this record uses ms_struct layout.
2993/// This which can be turned on with an attribute, pragma, or the
2994/// -mms-bitfields command-line option.
2995bool RecordDecl::isMsStruct(const ASTContext &C) const {
2996 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
2997}
2998
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00002999static bool isFieldOrIndirectField(Decl::Kind K) {
3000 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3001}
3002
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003003void RecordDecl::LoadFieldsFromExternalStorage() const {
3004 ExternalASTSource *Source = getASTContext().getExternalSource();
3005 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3006
3007 // Notify that we have a RecordDecl doing some initialization.
3008 ExternalASTSource::Deserializing TheFields(Source);
3009
Chris Lattner5f9e2722011-07-23 10:55:15 +00003010 SmallVector<Decl*, 64> Decls;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003011 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00003012 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3013 Decls)) {
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003014 case ELR_Success:
3015 break;
3016
3017 case ELR_AlreadyLoaded:
3018 case ELR_Failure:
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003019 return;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003020 }
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003021
3022#ifndef NDEBUG
3023 // Check that all decls we got were FieldDecls.
3024 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00003025 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003026#endif
3027
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003028 if (Decls.empty())
3029 return;
3030
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +00003031 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3032 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003033}
3034
Steve Naroff56ee6892008-10-08 17:01:13 +00003035//===----------------------------------------------------------------------===//
3036// BlockDecl Implementation
3037//===----------------------------------------------------------------------===//
3038
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003039void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffe78b8092009-03-13 16:56:44 +00003040 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Steve Naroffe78b8092009-03-13 16:56:44 +00003042 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00003043 if (!NewParamInfo.empty()) {
3044 NumParams = NewParamInfo.size();
3045 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3046 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffe78b8092009-03-13 16:56:44 +00003047 }
3048}
3049
John McCall6b5a61b2011-02-07 10:33:21 +00003050void BlockDecl::setCaptures(ASTContext &Context,
3051 const Capture *begin,
3052 const Capture *end,
3053 bool capturesCXXThis) {
John McCall469a1eb2011-02-02 13:00:07 +00003054 CapturesCXXThis = capturesCXXThis;
3055
3056 if (begin == end) {
John McCall6b5a61b2011-02-07 10:33:21 +00003057 NumCaptures = 0;
3058 Captures = 0;
John McCall469a1eb2011-02-02 13:00:07 +00003059 return;
3060 }
3061
John McCall6b5a61b2011-02-07 10:33:21 +00003062 NumCaptures = end - begin;
3063
3064 // Avoid new Capture[] because we don't want to provide a default
3065 // constructor.
3066 size_t allocationSize = NumCaptures * sizeof(Capture);
3067 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3068 memcpy(buffer, begin, allocationSize);
3069 Captures = static_cast<Capture*>(buffer);
Steve Naroffe78b8092009-03-13 16:56:44 +00003070}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003071
John McCall204e1332011-06-15 22:51:16 +00003072bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3073 for (capture_const_iterator
3074 i = capture_begin(), e = capture_end(); i != e; ++i)
3075 // Only auto vars can be captured, so no redeclaration worries.
3076 if (i->getVariable() == variable)
3077 return true;
3078
3079 return false;
3080}
3081
Douglas Gregor2fcbcef2010-12-21 16:27:07 +00003082SourceRange BlockDecl::getSourceRange() const {
3083 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3084}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003085
3086//===----------------------------------------------------------------------===//
3087// Other Decl Allocation/Deallocation Method Implementations
3088//===----------------------------------------------------------------------===//
3089
David Blaikie99ba9e32011-12-20 02:48:34 +00003090void TranslationUnitDecl::anchor() { }
3091
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003092TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3093 return new (C) TranslationUnitDecl(C);
3094}
3095
David Blaikie99ba9e32011-12-20 02:48:34 +00003096void LabelDecl::anchor() { }
3097
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003098LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara67843042011-03-05 18:21:20 +00003099 SourceLocation IdentL, IdentifierInfo *II) {
3100 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3101}
3102
3103LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3104 SourceLocation IdentL, IdentifierInfo *II,
3105 SourceLocation GnuLabelL) {
3106 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3107 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003108}
3109
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003110LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3111 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3112 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor06c91932010-10-27 19:49:05 +00003113}
3114
David Blaikie99ba9e32011-12-20 02:48:34 +00003115void ValueDecl::anchor() { }
3116
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +00003117bool ValueDecl::isWeak() const {
3118 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3119 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3120 return true;
3121
3122 return isWeakImported();
3123}
3124
David Blaikie99ba9e32011-12-20 02:48:34 +00003125void ImplicitParamDecl::anchor() { }
3126
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003127ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003128 SourceLocation IdLoc,
3129 IdentifierInfo *Id,
3130 QualType Type) {
3131 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003132}
3133
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003134ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3135 unsigned ID) {
3136 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3137 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3138}
3139
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003140FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003141 SourceLocation StartLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00003142 const DeclarationNameInfo &NameInfo,
3143 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003144 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregor8f150942010-12-09 16:59:22 +00003145 bool isInlineSpecified,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003146 bool hasWrittenPrototype,
3147 bool isConstexprSpecified) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003148 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3149 T, TInfo, SC, SCAsWritten,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003150 isInlineSpecified,
3151 isConstexprSpecified);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003152 New->HasWrittenPrototype = hasWrittenPrototype;
3153 return New;
3154}
3155
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003156FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3157 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3158 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3159 DeclarationNameInfo(), QualType(), 0,
3160 SC_None, SC_None, false, false);
3161}
3162
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003163BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3164 return new (C) BlockDecl(DC, L);
3165}
3166
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003167BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3168 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3169 return new (Mem) BlockDecl(0, SourceLocation());
3170}
3171
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003172EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3173 SourceLocation L,
3174 IdentifierInfo *Id, QualType T,
3175 Expr *E, const llvm::APSInt &V) {
3176 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3177}
3178
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003179EnumConstantDecl *
3180EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3181 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3182 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3183 llvm::APSInt());
3184}
3185
David Blaikie99ba9e32011-12-20 02:48:34 +00003186void IndirectFieldDecl::anchor() { }
3187
Benjamin Kramerd9811462010-11-21 14:11:41 +00003188IndirectFieldDecl *
3189IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3190 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3191 unsigned CHS) {
Francois Pichet87c2e122010-11-21 06:08:52 +00003192 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3193}
3194
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003195IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3196 unsigned ID) {
3197 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3198 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3199 QualType(), 0, 0);
3200}
3201
Douglas Gregor8e7139c2010-09-01 20:41:53 +00003202SourceRange EnumConstantDecl::getSourceRange() const {
3203 SourceLocation End = getLocation();
3204 if (Init)
3205 End = Init->getLocEnd();
3206 return SourceRange(getLocation(), End);
3207}
3208
David Blaikie99ba9e32011-12-20 02:48:34 +00003209void TypeDecl::anchor() { }
3210
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003211TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003212 SourceLocation StartLoc, SourceLocation IdLoc,
3213 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3214 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003215}
3216
David Blaikie99ba9e32011-12-20 02:48:34 +00003217void TypedefNameDecl::anchor() { }
3218
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003219TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3220 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3221 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3222}
3223
Richard Smith162e1c12011-04-15 14:24:37 +00003224TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3225 SourceLocation StartLoc,
3226 SourceLocation IdLoc, IdentifierInfo *Id,
3227 TypeSourceInfo *TInfo) {
3228 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3229}
3230
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003231TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3232 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3233 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3234}
3235
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00003236SourceRange TypedefDecl::getSourceRange() const {
3237 SourceLocation RangeEnd = getLocation();
3238 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3239 if (typeIsPostfix(TInfo->getType()))
3240 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3241 }
3242 return SourceRange(getLocStart(), RangeEnd);
3243}
3244
Richard Smith162e1c12011-04-15 14:24:37 +00003245SourceRange TypeAliasDecl::getSourceRange() const {
3246 SourceLocation RangeEnd = getLocStart();
3247 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3248 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3249 return SourceRange(getLocStart(), RangeEnd);
3250}
3251
David Blaikie99ba9e32011-12-20 02:48:34 +00003252void FileScopeAsmDecl::anchor() { }
3253
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003254FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara21e006e2011-03-03 14:20:18 +00003255 StringLiteral *Str,
3256 SourceLocation AsmLoc,
3257 SourceLocation RParenLoc) {
3258 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003259}
Douglas Gregor15de72c2011-12-02 23:23:56 +00003260
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003261FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3262 unsigned ID) {
3263 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3264 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3265}
3266
Douglas Gregor15de72c2011-12-02 23:23:56 +00003267//===----------------------------------------------------------------------===//
3268// ImportDecl Implementation
3269//===----------------------------------------------------------------------===//
3270
3271/// \brief Retrieve the number of module identifiers needed to name the given
3272/// module.
3273static unsigned getNumModuleIdentifiers(Module *Mod) {
3274 unsigned Result = 1;
3275 while (Mod->Parent) {
3276 Mod = Mod->Parent;
3277 ++Result;
3278 }
3279 return Result;
3280}
3281
Douglas Gregor5948ae12012-01-03 18:04:46 +00003282ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00003283 Module *Imported,
3284 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor5948ae12012-01-03 18:04:46 +00003285 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregore6649772011-12-03 00:30:27 +00003286 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00003287{
3288 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3289 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3290 memcpy(StoredLocs, IdentifierLocs.data(),
3291 IdentifierLocs.size() * sizeof(SourceLocation));
3292}
3293
Douglas Gregor5948ae12012-01-03 18:04:46 +00003294ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00003295 Module *Imported, SourceLocation EndLoc)
Douglas Gregor5948ae12012-01-03 18:04:46 +00003296 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregore6649772011-12-03 00:30:27 +00003297 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00003298{
3299 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3300}
3301
3302ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00003303 SourceLocation StartLoc, Module *Imported,
Douglas Gregor15de72c2011-12-02 23:23:56 +00003304 ArrayRef<SourceLocation> IdentifierLocs) {
3305 void *Mem = C.Allocate(sizeof(ImportDecl) +
3306 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor5948ae12012-01-03 18:04:46 +00003307 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +00003308}
3309
3310ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00003311 SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00003312 Module *Imported,
3313 SourceLocation EndLoc) {
3314 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor5948ae12012-01-03 18:04:46 +00003315 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregor15de72c2011-12-02 23:23:56 +00003316 Import->setImplicit();
3317 return Import;
3318}
3319
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003320ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3321 unsigned NumLocations) {
3322 void *Mem = AllocateDeserializedDecl(C, ID,
3323 (sizeof(ImportDecl) +
3324 NumLocations * sizeof(SourceLocation)));
Douglas Gregor15de72c2011-12-02 23:23:56 +00003325 return new (Mem) ImportDecl(EmptyShell());
3326}
3327
3328ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3329 if (!ImportedAndComplete.getInt())
3330 return ArrayRef<SourceLocation>();
3331
3332 const SourceLocation *StoredLocs
3333 = reinterpret_cast<const SourceLocation *>(this + 1);
3334 return ArrayRef<SourceLocation>(StoredLocs,
3335 getNumModuleIdentifiers(getImportedModule()));
3336}
3337
3338SourceRange ImportDecl::getSourceRange() const {
3339 if (!ImportedAndComplete.getInt())
3340 return SourceRange(getLocation(),
3341 *reinterpret_cast<const SourceLocation *>(this + 1));
3342
3343 return SourceRange(getLocation(), getIdentifierLocs().back());
3344}