blob: b8439cae743d58eb5963b38f2c4705243110d029 [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"
John McCall3892d022013-02-21 23:42:58 +000032#include "llvm/Support/type_traits.h"
David Blaikie4278c652011-09-21 18:16:56 +000033#include <algorithm>
34
Reid Spencer5f016e22007-07-11 17:01:13 +000035using namespace clang;
36
Chris Lattnerd3b90652008-03-15 05:43:15 +000037//===----------------------------------------------------------------------===//
Douglas Gregor4afa39d2009-01-20 01:17:11 +000038// NamedDecl Implementation
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000039//===----------------------------------------------------------------------===//
40
John McCall5a758de2013-02-16 00:17:33 +000041// Visibility rules aren't rigorously externally specified, but here
42// are the basic principles behind what we implement:
43//
44// 1. An explicit visibility attribute is generally a direct expression
45// of the user's intent and should be honored. Only the innermost
46// visibility attribute applies. If no visibility attribute applies,
47// global visibility settings are considered.
48//
49// 2. There is one caveat to the above: on or in a template pattern,
50// an explicit visibility attribute is just a default rule, and
51// visibility can be decreased by the visibility of template
52// arguments. But this, too, has an exception: an attribute on an
53// explicit specialization or instantiation causes all the visibility
54// restrictions of the template arguments to be ignored.
55//
56// 3. A variable that does not otherwise have explicit visibility can
57// be restricted by the visibility of its type.
58//
59// 4. A visibility restriction is explicit if it comes from an
60// attribute (or something like it), not a global visibility setting.
61// When emitting a reference to an external symbol, visibility
62// restrictions are ignored unless they are explicit.
John McCalld4c3d662013-02-20 01:54:26 +000063//
64// 5. When computing the visibility of a non-type, including a
65// non-type member of a class, only non-type visibility restrictions
66// are considered: the 'visibility' attribute, global value-visibility
67// settings, and a few special cases like __private_extern.
68//
69// 6. When computing the visibility of a type, including a type member
70// of a class, only type visibility restrictions are considered:
71// the 'type_visibility' attribute and global type-visibility settings.
72// However, a 'visibility' attribute counts as a 'type_visibility'
73// attribute on any declaration that only has the former.
74//
75// The visibility of a "secondary" entity, like a template argument,
76// is computed using the kind of that entity, not the kind of the
77// primary entity for which we are computing visibility. For example,
78// the visibility of a specialization of either of these templates:
79// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
80// template <class T, bool (&compare)(T, X)> class matcher;
81// is restricted according to the type visibility of the argument 'T',
82// the type visibility of 'bool(&)(T,X)', and the value visibility of
83// the argument function 'compare'. That 'has_match' is a value
84// and 'matcher' is a type only matters when looking for attributes
85// and settings from the immediate context.
John McCall5a758de2013-02-16 00:17:33 +000086
John McCall3892d022013-02-21 23:42:58 +000087const unsigned IgnoreExplicitVisibilityBit = 2;
88
John McCall5a758de2013-02-16 00:17:33 +000089/// Kinds of LV computation. The linkage side of the computation is
90/// always the same, but different things can change how visibility is
91/// computed.
92enum LVComputationKind {
John McCall3892d022013-02-21 23:42:58 +000093 /// Do an LV computation for, ultimately, a type.
94 /// Visibility may be restricted by type visibility settings and
95 /// the visibility of template arguments.
John McCalld4c3d662013-02-20 01:54:26 +000096 LVForType = NamedDecl::VisibilityForType,
John McCall5a758de2013-02-16 00:17:33 +000097
John McCall3892d022013-02-21 23:42:58 +000098 /// Do an LV computation for, ultimately, a non-type declaration.
99 /// Visibility may be restricted by value visibility settings and
100 /// the visibility of template arguments.
John McCalld4c3d662013-02-20 01:54:26 +0000101 LVForValue = NamedDecl::VisibilityForValue,
102
John McCall3892d022013-02-21 23:42:58 +0000103 /// Do an LV computation for, ultimately, a type that already has
104 /// some sort of explicit visibility. Visibility may only be
105 /// restricted by the visibility of template arguments.
106 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld4c3d662013-02-20 01:54:26 +0000107
John McCall3892d022013-02-21 23:42:58 +0000108 /// Do an LV computation for, ultimately, a non-type declaration
109 /// that already has some sort of explicit visibility. Visibility
110 /// may only be restricted by the visibility of template arguments.
111 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit)
John McCall5a758de2013-02-16 00:17:33 +0000112};
113
John McCalld4c3d662013-02-20 01:54:26 +0000114/// Does this computation kind permit us to consider additional
115/// visibility settings from attributes and the like?
116static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall3892d022013-02-21 23:42:58 +0000117 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld4c3d662013-02-20 01:54:26 +0000118}
119
120/// Given an LVComputationKind, return one of the same type/value sort
121/// that records that it already has explicit visibility.
122static LVComputationKind
123withExplicitVisibilityAlready(LVComputationKind oldKind) {
124 LVComputationKind newKind =
John McCall3892d022013-02-21 23:42:58 +0000125 static_cast<LVComputationKind>(unsigned(oldKind) |
126 IgnoreExplicitVisibilityBit);
John McCalld4c3d662013-02-20 01:54:26 +0000127 assert(oldKind != LVForType || newKind == LVForExplicitType);
128 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
129 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
130 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
131 return newKind;
132}
133
David Blaikiedc84cd52013-02-20 22:23:23 +0000134static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
135 LVComputationKind kind) {
John McCalld4c3d662013-02-20 01:54:26 +0000136 assert(!hasExplicitVisibilityAlready(kind) &&
137 "asking for explicit visibility when we shouldn't be");
138 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
139}
140
John McCall5a758de2013-02-16 00:17:33 +0000141/// Is the given declaration a "type" or a "value" for the purposes of
142/// visibility computation?
143static bool usesTypeVisibility(const NamedDecl *D) {
John McCalla880b192013-02-19 01:57:35 +0000144 return isa<TypeDecl>(D) ||
145 isa<ClassTemplateDecl>(D) ||
146 isa<ObjCInterfaceDecl>(D);
John McCall5a758de2013-02-16 00:17:33 +0000147}
148
John McCall3892d022013-02-21 23:42:58 +0000149/// Does the given declaration have member specialization information,
150/// and if so, is it an explicit specialization?
151template <class T> static typename
152llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value,
153 bool>::type
154isExplicitMemberSpecialization(const T *D) {
155 if (const MemberSpecializationInfo *member =
156 D->getMemberSpecializationInfo()) {
157 return member->isExplicitSpecialization();
158 }
159 return false;
160}
161
162/// For templates, this question is easier: a member template can't be
163/// explicitly instantiated, so there's a single bit indicating whether
164/// or not this is an explicit member specialization.
165static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
166 return D->isMemberSpecialization();
167}
168
John McCalld4c3d662013-02-20 01:54:26 +0000169/// Given a visibility attribute, return the explicit visibility
170/// associated with it.
171template <class T>
172static Visibility getVisibilityFromAttr(const T *attr) {
173 switch (attr->getVisibility()) {
174 case T::Default:
175 return DefaultVisibility;
176 case T::Hidden:
177 return HiddenVisibility;
178 case T::Protected:
179 return ProtectedVisibility;
180 }
181 llvm_unreachable("bad visibility kind");
182}
183
John McCall5a758de2013-02-16 00:17:33 +0000184/// Return the explicit visibility of the given declaration.
David Blaikiedc84cd52013-02-20 22:23:23 +0000185static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld4c3d662013-02-20 01:54:26 +0000186 NamedDecl::ExplicitVisibilityKind kind) {
187 // If we're ultimately computing the visibility of a type, look for
188 // a 'type_visibility' attribute before looking for 'visibility'.
189 if (kind == NamedDecl::VisibilityForType) {
190 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
191 return getVisibilityFromAttr(A);
192 }
193 }
194
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000195 // If this declaration has an explicit visibility attribute, use it.
196 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld4c3d662013-02-20 01:54:26 +0000197 return getVisibilityFromAttr(A);
John McCall1fb0caa2010-10-22 21:05:15 +0000198 }
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000199
200 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
201 // implies visibility(default).
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000202 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000203 for (specific_attr_iterator<AvailabilityAttr>
204 A = D->specific_attr_begin<AvailabilityAttr>(),
205 AEnd = D->specific_attr_end<AvailabilityAttr>();
206 A != AEnd; ++A)
207 if ((*A)->getPlatform()->getName().equals("macosx"))
208 return DefaultVisibility;
209 }
210
David Blaikie66874fb2013-02-21 01:47:18 +0000211 return None;
John McCall1fb0caa2010-10-22 21:05:15 +0000212}
213
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000214/// \brief Get the most restrictive linkage for the types in the given
John McCall5a758de2013-02-16 00:17:33 +0000215/// template parameter list. For visibility purposes, template
216/// parameters are part of the signature of a template.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000217static LinkageInfo
John McCall5a758de2013-02-16 00:17:33 +0000218getLVForTemplateParameterList(const TemplateParameterList *params) {
219 LinkageInfo LV;
220 for (TemplateParameterList::const_iterator P = params->begin(),
221 PEnd = params->end();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000222 P != PEnd; ++P) {
John McCall5a758de2013-02-16 00:17:33 +0000223
224 // Template type parameters are the most common and never
225 // contribute to visibility, pack or not.
226 if (isa<TemplateTypeParmDecl>(*P))
227 continue;
228
229 // Non-type template parameters can be restricted by the value type, e.g.
230 // template <enum X> class A { ... };
231 // We have to be careful here, though, because we can be dealing with
232 // dependent types.
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000233 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCall5a758de2013-02-16 00:17:33 +0000234 // Handle the non-pack case first.
235 if (!NTTP->isExpandedParameterPack()) {
236 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola18895dc2013-02-27 02:27:19 +0000237 LV.merge(NTTP->getType()->getLinkageAndVisibility());
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000238 }
239 continue;
240 }
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000241
John McCall5a758de2013-02-16 00:17:33 +0000242 // Look at all the types in an expanded pack.
243 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
244 QualType type = NTTP->getExpansionType(i);
245 if (!type->isDependentType())
Rafael Espindola18895dc2013-02-27 02:27:19 +0000246 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000247 }
John McCall5a758de2013-02-16 00:17:33 +0000248 continue;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000249 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000250
John McCall5a758de2013-02-16 00:17:33 +0000251 // Template template parameters can be restricted by their
252 // template parameters, recursively.
253 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
254
255 // Handle the non-pack case first.
256 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola093ecc92012-01-14 00:30:36 +0000257 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
John McCall5a758de2013-02-16 00:17:33 +0000258 continue;
259 }
260
261 // Look at all expansions in an expanded pack.
262 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
263 i != n; ++i) {
264 LV.merge(getLVForTemplateParameterList(
265 TTP->getExpansionTemplateParameters(i)));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000266 }
267 }
268
John McCall1fb0caa2010-10-22 21:05:15 +0000269 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000270}
271
Rafael Espindola838dc592013-01-12 06:42:30 +0000272/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCall5a758de2013-02-16 00:17:33 +0000273static LinkageInfo getLVForDecl(const NamedDecl *D,
274 LVComputationKind computation);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000275
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000276/// \brief Get the most restrictive linkage for the types and
277/// declarations in the given template argument list.
John McCall5a758de2013-02-16 00:17:33 +0000278///
279/// Note that we don't take an LVComputationKind because we always
280/// want to honor the visibility of template arguments in the same way.
281static LinkageInfo
282getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
283 LinkageInfo LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000284
John McCall5a758de2013-02-16 00:17:33 +0000285 for (unsigned i = 0, e = args.size(); i != e; ++i) {
286 const TemplateArgument &arg = args[i];
287 switch (arg.getKind()) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000288 case TemplateArgument::Null:
289 case TemplateArgument::Integral:
290 case TemplateArgument::Expression:
John McCall5a758de2013-02-16 00:17:33 +0000291 continue;
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000292
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000293 case TemplateArgument::Type:
Rafael Espindola18895dc2013-02-27 02:27:19 +0000294 LV.merge(arg.getAsType()->getLinkageAndVisibility());
John McCall5a758de2013-02-16 00:17:33 +0000295 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000296
297 case TemplateArgument::Declaration:
John McCall5a758de2013-02-16 00:17:33 +0000298 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
299 assert(!usesTypeVisibility(ND));
300 LV.merge(getLVForDecl(ND, LVForValue));
301 }
302 continue;
Eli Friedmand7a6b162012-09-26 02:36:12 +0000303
304 case TemplateArgument::NullPtr:
Rafael Espindola18895dc2013-02-27 02:27:19 +0000305 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
John McCall5a758de2013-02-16 00:17:33 +0000306 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000307
308 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +0000309 case TemplateArgument::TemplateExpansion:
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000310 if (TemplateDecl *Template
John McCall5a758de2013-02-16 00:17:33 +0000311 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
312 LV.merge(getLVForDecl(Template, LVForValue));
313 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000314
315 case TemplateArgument::Pack:
John McCall5a758de2013-02-16 00:17:33 +0000316 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
317 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000318 }
John McCall5a758de2013-02-16 00:17:33 +0000319 llvm_unreachable("bad template argument kind");
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000320 }
321
John McCall1fb0caa2010-10-22 21:05:15 +0000322 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000323}
324
Rafael Espindola093ecc92012-01-14 00:30:36 +0000325static LinkageInfo
John McCall5a758de2013-02-16 00:17:33 +0000326getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
327 return getLVForTemplateArgumentList(TArgs.asArray());
John McCall3cdfc4d2010-08-13 08:35:10 +0000328}
329
John McCall3892d022013-02-21 23:42:58 +0000330static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
331 const FunctionTemplateSpecializationInfo *specInfo) {
332 // Include visibility from the template parameters and arguments
333 // only if this is not an explicit instantiation or specialization
334 // with direct explicit visibility. (Implicit instantiations won't
335 // have a direct attribute.)
336 if (!specInfo->isExplicitInstantiationOrSpecialization())
337 return true;
338
339 return !fn->hasAttr<VisibilityAttr>();
340}
341
John McCall5a758de2013-02-16 00:17:33 +0000342/// Merge in template-related linkage and visibility for the given
343/// function template specialization.
344///
345/// We don't need a computation kind here because we can assume
346/// LVForValue.
John McCall3892d022013-02-21 23:42:58 +0000347///
NAKAMURA Takumid9bd83e2013-02-22 04:06:28 +0000348/// \param[out] LV the computation to use for the parent
John McCall3892d022013-02-21 23:42:58 +0000349static void
350mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
351 const FunctionTemplateSpecializationInfo *specInfo) {
352 bool considerVisibility =
353 shouldConsiderTemplateVisibility(fn, specInfo);
John McCall5a758de2013-02-16 00:17:33 +0000354
355 // Merge information from the template parameters.
John McCall3892d022013-02-21 23:42:58 +0000356 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCall5a758de2013-02-16 00:17:33 +0000357 LinkageInfo tempLV =
358 getLVForTemplateParameterList(temp->getTemplateParameters());
359 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
360
361 // Merge information from the template arguments.
362 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
363 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
364 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCall6ce51ee2011-06-27 23:06:04 +0000365}
366
John McCall3892d022013-02-21 23:42:58 +0000367/// Does the given declaration have a direct visibility attribute
368/// that would match the given rules?
369static bool hasDirectVisibilityAttribute(const NamedDecl *D,
370 LVComputationKind computation) {
371 switch (computation) {
372 case LVForType:
373 case LVForExplicitType:
374 if (D->hasAttr<TypeVisibilityAttr>())
375 return true;
376 // fallthrough
377 case LVForValue:
378 case LVForExplicitValue:
379 if (D->hasAttr<VisibilityAttr>())
380 return true;
381 return false;
382 }
383 llvm_unreachable("bad visibility computation kind");
384}
385
John McCalld4c3d662013-02-20 01:54:26 +0000386/// Should we consider visibility associated with the template
387/// arguments and parameters of the given class template specialization?
388static bool shouldConsiderTemplateVisibility(
389 const ClassTemplateSpecializationDecl *spec,
390 LVComputationKind computation) {
John McCall5a758de2013-02-16 00:17:33 +0000391 // Include visibility from the template parameters and arguments
392 // only if this is not an explicit instantiation or specialization
393 // with direct explicit visibility (and note that implicit
394 // instantiations won't have a direct attribute).
395 //
396 // Furthermore, we want to ignore template parameters and arguments
John McCalld4c3d662013-02-20 01:54:26 +0000397 // for an explicit specialization when computing the visibility of a
398 // member thereof with explicit visibility.
John McCall5a758de2013-02-16 00:17:33 +0000399 //
400 // This is a bit complex; let's unpack it.
401 //
402 // An explicit class specialization is an independent, top-level
403 // declaration. As such, if it or any of its members has an
404 // explicit visibility attribute, that must directly express the
405 // user's intent, and we should honor it. The same logic applies to
406 // an explicit instantiation of a member of such a thing.
John McCalld4c3d662013-02-20 01:54:26 +0000407
408 // Fast path: if this is not an explicit instantiation or
409 // specialization, we always want to consider template-related
410 // visibility restrictions.
411 if (!spec->isExplicitInstantiationOrSpecialization())
412 return true;
413
414 // This is the 'member thereof' check.
415 if (spec->isExplicitSpecialization() &&
416 hasExplicitVisibilityAlready(computation))
417 return false;
418
John McCall3892d022013-02-21 23:42:58 +0000419 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld4c3d662013-02-20 01:54:26 +0000420}
421
422/// Merge in template-related linkage and visibility for the given
423/// class template specialization.
424static void mergeTemplateLV(LinkageInfo &LV,
425 const ClassTemplateSpecializationDecl *spec,
426 LVComputationKind computation) {
427 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCall5a758de2013-02-16 00:17:33 +0000428
429 // Merge information from the template parameters, but ignore
430 // visibility if we're only considering template arguments.
431
John McCalld4c3d662013-02-20 01:54:26 +0000432 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCall5a758de2013-02-16 00:17:33 +0000433 LinkageInfo tempLV =
434 getLVForTemplateParameterList(temp->getTemplateParameters());
435 LV.mergeMaybeWithVisibility(tempLV,
John McCalld4c3d662013-02-20 01:54:26 +0000436 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCall5a758de2013-02-16 00:17:33 +0000437
438 // Merge information from the template arguments. We ignore
439 // template-argument visibility if we've got an explicit
440 // instantiation with a visibility attribute.
441 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
442 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
443 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCall6ce51ee2011-06-27 23:06:04 +0000444}
445
Rafael Espindolab04b7312012-07-13 14:25:36 +0000446static bool useInlineVisibilityHidden(const NamedDecl *D) {
447 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola0bab9da2012-07-13 23:26:43 +0000448 const LangOptions &Opts = D->getASTContext().getLangOpts();
449 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolab04b7312012-07-13 14:25:36 +0000450 return false;
451
452 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
453 if (!FD)
454 return false;
455
456 TemplateSpecializationKind TSK = TSK_Undeclared;
457 if (FunctionTemplateSpecializationInfo *spec
458 = FD->getTemplateSpecializationInfo()) {
459 TSK = spec->getTemplateSpecializationKind();
460 } else if (MemberSpecializationInfo *MSI =
461 FD->getMemberSpecializationInfo()) {
462 TSK = MSI->getTemplateSpecializationKind();
463 }
464
465 const FunctionDecl *Def = 0;
466 // InlineVisibilityHidden only applies to definitions, and
467 // isInlined() only gives meaningful answers on definitions
468 // anyway.
469 return TSK != TSK_ExplicitInstantiationDeclaration &&
470 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindola0142f0c2012-10-11 16:32:25 +0000471 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolab04b7312012-07-13 14:25:36 +0000472}
473
Benjamin Kramera574c892013-02-15 12:30:38 +0000474template <typename T> static bool isInExternCContext(T *D) {
Rafael Espindola950fee22013-02-14 01:18:37 +0000475 const T *First = D->getFirstDeclaration();
476 return First->getDeclContext()->isExternCContext();
477}
478
Rafael Espindola1266b612012-04-21 23:28:21 +0000479static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCall5a758de2013-02-16 00:17:33 +0000480 LVComputationKind computation) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000481 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregord85b5b92009-11-25 22:24:25 +0000482 "Not a name having namespace scope");
483 ASTContext &Context = D->getASTContext();
484
485 // C++ [basic.link]p3:
486 // A name having namespace scope (3.3.6) has internal linkage if it
487 // is the name of
488 // - an object, reference, function or function template that is
489 // explicitly declared static; or,
490 // (This bullet corresponds to C99 6.2.2p3.)
491 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
492 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000493 if (Var->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000494 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000495
Richard Smith820e9a72012-10-19 06:37:48 +0000496 // - a non-volatile object or reference that is explicitly declared const
497 // or constexpr and neither explicitly declared extern nor previously
498 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikie4e4d0842012-03-11 07:00:24 +0000499 if (Context.getLangOpts().CPlusPlus &&
Richard Smith820e9a72012-10-19 06:37:48 +0000500 Var->getType().isConstQualified() &&
501 !Var->getType().isVolatileQualified() &&
John McCalld931b082010-08-26 03:08:43 +0000502 Var->getStorageClass() != SC_Extern &&
503 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregord85b5b92009-11-25 22:24:25 +0000504 bool FoundExtern = false;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000505 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000506 PrevVar && !FoundExtern;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000507 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000508 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregord85b5b92009-11-25 22:24:25 +0000509 FoundExtern = true;
510
511 if (!FoundExtern)
John McCallaf146032010-10-30 11:50:40 +0000512 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000513 }
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000514 if (Var->getStorageClass() == SC_None) {
Douglas Gregoref96ee02012-01-14 16:38:05 +0000515 const VarDecl *PrevVar = Var->getPreviousDecl();
516 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000517 if (PrevVar->getStorageClass() == SC_PrivateExtern)
518 break;
Eli Friedman8c7a1852012-10-26 23:05:34 +0000519 if (PrevVar)
520 return PrevVar->getLinkageAndVisibility();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000521 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000522 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000523 // C++ [temp]p4:
524 // A non-member function template can have internal linkage; any
525 // other template name shall have external linkage.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000526 const FunctionDecl *Function = 0;
527 if (const FunctionTemplateDecl *FunTmpl
528 = dyn_cast<FunctionTemplateDecl>(D))
529 Function = FunTmpl->getTemplatedDecl();
530 else
531 Function = cast<FunctionDecl>(D);
532
533 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000534 if (Function->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000535 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000536 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
537 // - a data member of an anonymous union.
538 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallaf146032010-10-30 11:50:40 +0000539 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000540 }
541
Chandler Carruth094b6432011-02-24 19:03:39 +0000542 if (D->isInAnonymousNamespace()) {
543 const VarDecl *Var = dyn_cast<VarDecl>(D);
544 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindola950fee22013-02-14 01:18:37 +0000545 if ((!Var || !isInExternCContext(Var)) &&
546 (!Func || !isInExternCContext(Func)))
Chandler Carruth094b6432011-02-24 19:03:39 +0000547 return LinkageInfo::uniqueExternal();
548 }
John McCalle7bc9722010-10-28 04:18:25 +0000549
John McCall1fb0caa2010-10-22 21:05:15 +0000550 // Set up the defaults.
551
552 // C99 6.2.2p5:
553 // If the declaration of an identifier for an object has file
554 // scope and no storage-class specifier, its linkage is
555 // external.
John McCallaf146032010-10-30 11:50:40 +0000556 LinkageInfo LV;
557
John McCalld4c3d662013-02-20 01:54:26 +0000558 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000559 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola5727cf52012-04-19 02:22:07 +0000560 LV.mergeVisibility(*Vis, true);
Rafael Espindolae9836a22012-04-16 18:46:26 +0000561 } else {
562 // If we're declared in a namespace with a visibility attribute,
John McCall5a758de2013-02-16 00:17:33 +0000563 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindolae9836a22012-04-16 18:46:26 +0000564 for (const DeclContext *DC = D->getDeclContext();
565 !isa<TranslationUnitDecl>(DC);
566 DC = DC->getParent()) {
567 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
568 if (!ND) continue;
David Blaikiedc84cd52013-02-20 22:23:23 +0000569 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola5727cf52012-04-19 02:22:07 +0000570 LV.mergeVisibility(*Vis, true);
Rafael Espindolae9836a22012-04-16 18:46:26 +0000571 break;
572 }
573 }
574 }
Rafael Espindolae9836a22012-04-16 18:46:26 +0000575
John McCall5a758de2013-02-16 00:17:33 +0000576 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000577 if (!LV.isVisibilityExplicit()) {
John McCalla880b192013-02-19 01:57:35 +0000578 // Use global type/value visibility as appropriate.
579 Visibility globalVisibility;
580 if (computation == LVForValue) {
581 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
582 } else {
583 assert(computation == LVForType);
584 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
585 }
586 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCall5a758de2013-02-16 00:17:33 +0000587
588 // If we're paying attention to global visibility, apply
589 // -finline-visibility-hidden if this is an inline method.
590 if (useInlineVisibilityHidden(D))
591 LV.mergeVisibility(HiddenVisibility, true);
592 }
Rafael Espindolab04b7312012-07-13 14:25:36 +0000593 }
Rafael Espindolaff257982012-04-19 02:55:01 +0000594
Douglas Gregord85b5b92009-11-25 22:24:25 +0000595 // C++ [basic.link]p4:
John McCall1fb0caa2010-10-22 21:05:15 +0000596
Douglas Gregord85b5b92009-11-25 22:24:25 +0000597 // A name having namespace scope has external linkage if it is the
598 // name of
599 //
600 // - an object or reference, unless it has internal linkage; or
601 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall110e8e52010-10-29 22:22:43 +0000602 // GCC applies the following optimization to variables and static
603 // data members, but not to functions:
604 //
John McCall1fb0caa2010-10-22 21:05:15 +0000605 // Modify the variable's LV by the LV of its type unless this is
606 // C or extern "C". This follows from [basic.link]p9:
607 // A type without linkage shall not be used as the type of a
608 // variable or function with external linkage unless
609 // - the entity has C language linkage, or
610 // - the entity is declared within an unnamed namespace, or
611 // - the entity is not used or is defined in the same
612 // translation unit.
613 // and [basic.link]p10:
614 // ...the types specified by all declarations referring to a
615 // given variable or function shall be identical...
616 // C does not have an equivalent rule.
617 //
John McCallac65c622010-10-26 04:59:26 +0000618 // Ignore this if we've got an explicit attribute; the user
619 // probably knows what they're doing.
620 //
John McCall1fb0caa2010-10-22 21:05:15 +0000621 // Note that we don't want to make the variable non-external
622 // because of this, but unique-external linkage suits us.
David Blaikie4e4d0842012-03-11 07:00:24 +0000623 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman750dc2b2012-01-15 01:23:58 +0000624 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola18895dc2013-02-27 02:27:19 +0000625 LinkageInfo TypeLV = Var->getType()->getLinkageAndVisibility();
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000626 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000627 return LinkageInfo::uniqueExternal();
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000628 if (!LV.isVisibilityExplicit())
John McCall5a758de2013-02-16 00:17:33 +0000629 LV.mergeVisibility(TypeLV);
John McCall110e8e52010-10-29 22:22:43 +0000630 }
631
John McCall35cebc32010-11-02 18:38:13 +0000632 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola5727cf52012-04-19 02:22:07 +0000633 LV.mergeVisibility(HiddenVisibility, true);
John McCall35cebc32010-11-02 18:38:13 +0000634
Rafael Espindola538fb982012-11-12 04:10:23 +0000635 // Note that Sema::MergeVarDecl already takes care of implementing
636 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
637 // to do it here.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000638
Douglas Gregord85b5b92009-11-25 22:24:25 +0000639 // - a function, unless it has internal linkage; or
John McCall1fb0caa2010-10-22 21:05:15 +0000640 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall67fa6d52010-10-28 07:07:52 +0000641 // In theory, we can modify the function's LV by the LV of its
642 // type unless it has C linkage (see comment above about variables
643 // for justification). In practice, GCC doesn't do this, so it's
644 // just too painful to make work.
John McCall1fb0caa2010-10-22 21:05:15 +0000645
John McCall35cebc32010-11-02 18:38:13 +0000646 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola5727cf52012-04-19 02:22:07 +0000647 LV.mergeVisibility(HiddenVisibility, true);
John McCall35cebc32010-11-02 18:38:13 +0000648
Rafael Espindola51758612012-11-21 02:47:19 +0000649 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
650 // merging storage classes and visibility attributes, so we don't have to
651 // look at previous decls in here.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000652
John McCallaf8ca372011-02-10 06:50:24 +0000653 // In C++, then if the type of the function uses a type with
654 // unique-external linkage, it's not legally usable from outside
655 // this translation unit. However, we should use the C linkage
656 // rules instead for extern "C" declarations.
David Blaikie4e4d0842012-03-11 07:00:24 +0000657 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman750dc2b2012-01-15 01:23:58 +0000658 !Function->getDeclContext()->isExternCContext() &&
John McCallaf8ca372011-02-10 06:50:24 +0000659 Function->getType()->getLinkage() == UniqueExternalLinkage)
660 return LinkageInfo::uniqueExternal();
661
John McCall3892d022013-02-21 23:42:58 +0000662 // Consider LV from the template and the template arguments.
663 // We're at file scope, so we do not need to worry about nested
664 // specializations.
John McCall6ce51ee2011-06-27 23:06:04 +0000665 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000666 = Function->getTemplateSpecializationInfo()) {
John McCall5a758de2013-02-16 00:17:33 +0000667 mergeTemplateLV(LV, Function, specInfo);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000668 }
669
Douglas Gregord85b5b92009-11-25 22:24:25 +0000670 // - a named class (Clause 9), or an unnamed class defined in a
671 // typedef declaration in which the class has the typedef name
672 // for linkage purposes (7.1.3); or
673 // - a named enumeration (7.2), or an unnamed enumeration
674 // defined in a typedef declaration in which the enumeration
675 // has the typedef name for linkage purposes (7.1.3); or
John McCall1fb0caa2010-10-22 21:05:15 +0000676 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
677 // Unnamed tags have no linkage.
Richard Smith162e1c12011-04-15 14:24:37 +0000678 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallaf146032010-10-30 11:50:40 +0000679 return LinkageInfo::none();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000680
John McCall1fb0caa2010-10-22 21:05:15 +0000681 // If this is a class template specialization, consider the
John McCall3892d022013-02-21 23:42:58 +0000682 // linkage of the template and template arguments. We're at file
683 // scope, so we do not need to worry about nested specializations.
John McCall6ce51ee2011-06-27 23:06:04 +0000684 if (const ClassTemplateSpecializationDecl *spec
John McCall1fb0caa2010-10-22 21:05:15 +0000685 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCall5a758de2013-02-16 00:17:33 +0000686 mergeTemplateLV(LV, spec, computation);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000687 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000688
689 // - an enumerator belonging to an enumeration with external linkage;
John McCall1fb0caa2010-10-22 21:05:15 +0000690 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola1266b612012-04-21 23:28:21 +0000691 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCall5a758de2013-02-16 00:17:33 +0000692 computation);
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000693 if (!isExternalLinkage(EnumLV.getLinkage()))
John McCallaf146032010-10-30 11:50:40 +0000694 return LinkageInfo::none();
695 LV.merge(EnumLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000696
697 // - a template, unless it is a function template that has
698 // internal linkage (Clause 14);
John McCall1a0918a2011-03-04 10:39:25 +0000699 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld4c3d662013-02-20 01:54:26 +0000700 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCall5a758de2013-02-16 00:17:33 +0000701 LinkageInfo tempLV =
702 getLVForTemplateParameterList(temp->getTemplateParameters());
703 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
704
Douglas Gregord85b5b92009-11-25 22:24:25 +0000705 // - a namespace (7.3), unless it is declared within an unnamed
706 // namespace.
John McCall1fb0caa2010-10-22 21:05:15 +0000707 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
708 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000709
John McCall1fb0caa2010-10-22 21:05:15 +0000710 // By extension, we assign external linkage to Objective-C
711 // interfaces.
712 } else if (isa<ObjCInterfaceDecl>(D)) {
713 // fallout
714
715 // Everything not covered here has no linkage.
716 } else {
John McCallaf146032010-10-30 11:50:40 +0000717 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000718 }
719
720 // If we ended up with non-external linkage, visibility should
721 // always be default.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000722 if (LV.getLinkage() != ExternalLinkage)
723 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall1fb0caa2010-10-22 21:05:15 +0000724
John McCall1fb0caa2010-10-22 21:05:15 +0000725 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000726}
727
John McCall5a758de2013-02-16 00:17:33 +0000728static LinkageInfo getLVForClassMember(const NamedDecl *D,
729 LVComputationKind computation) {
John McCall1fb0caa2010-10-22 21:05:15 +0000730 // Only certain class members have linkage. Note that fields don't
731 // really have linkage, but it's convenient to say they do for the
732 // purposes of calculating linkage of pointer-to-data-member
733 // template arguments.
John McCall3cdfc4d2010-08-13 08:35:10 +0000734 if (!(isa<CXXMethodDecl>(D) ||
735 isa<VarDecl>(D) ||
John McCall1fb0caa2010-10-22 21:05:15 +0000736 isa<FieldDecl>(D) ||
David Blaikie66cff722012-11-14 01:52:05 +0000737 isa<TagDecl>(D)))
John McCallaf146032010-10-30 11:50:40 +0000738 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000739
John McCall36987482010-11-02 01:45:15 +0000740 LinkageInfo LV;
741
John McCall36987482010-11-02 01:45:15 +0000742 // If we have an explicit visibility attribute, merge that in.
John McCalld4c3d662013-02-20 01:54:26 +0000743 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000744 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000745 LV.mergeVisibility(*Vis, true);
Rafael Espindolab04b7312012-07-13 14:25:36 +0000746 // If we're paying attention to global visibility, apply
747 // -finline-visibility-hidden if this is an inline method.
748 //
749 // Note that we do this before merging information about
750 // the class visibility.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000751 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolab04b7312012-07-13 14:25:36 +0000752 LV.mergeVisibility(HiddenVisibility, true);
John McCall36987482010-11-02 01:45:15 +0000753 }
Rafael Espindolac7e60602012-04-19 05:50:08 +0000754
755 // If this class member has an explicit visibility attribute, the only
756 // thing that can change its visibility is the template arguments, so
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000757 // only look for them when processing the class.
John McCalld4c3d662013-02-20 01:54:26 +0000758 LVComputationKind classComputation = computation;
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000759 if (LV.isVisibilityExplicit())
John McCalld4c3d662013-02-20 01:54:26 +0000760 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola0f905902012-04-16 18:25:01 +0000761
John McCall3892d022013-02-21 23:42:58 +0000762 LinkageInfo classLV =
763 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000764 if (!isExternalLinkage(classLV.getLinkage()))
John McCallaf146032010-10-30 11:50:40 +0000765 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000766
767 // If the class already has unique-external linkage, we can't improve.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000768 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000769 return LinkageInfo::uniqueExternal();
John McCall3cdfc4d2010-08-13 08:35:10 +0000770
John McCall3892d022013-02-21 23:42:58 +0000771 // Otherwise, don't merge in classLV yet, because in certain cases
772 // we need to completely ignore the visibility from it.
773
774 // Specifically, if this decl exists and has an explicit attribute.
775 const NamedDecl *explicitSpecSuppressor = 0;
776
John McCall3cdfc4d2010-08-13 08:35:10 +0000777 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallaf8ca372011-02-10 06:50:24 +0000778 // If the type of the function uses a type with unique-external
779 // linkage, it's not legally usable from outside this translation unit.
780 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
781 return LinkageInfo::uniqueExternal();
782
John McCall1fb0caa2010-10-22 21:05:15 +0000783 // If this is a method template specialization, use the linkage for
784 // the template parameters and arguments.
John McCall6ce51ee2011-06-27 23:06:04 +0000785 if (FunctionTemplateSpecializationInfo *spec
John McCall3cdfc4d2010-08-13 08:35:10 +0000786 = MD->getTemplateSpecializationInfo()) {
John McCall5a758de2013-02-16 00:17:33 +0000787 mergeTemplateLV(LV, MD, spec);
John McCall3892d022013-02-21 23:42:58 +0000788 if (spec->isExplicitSpecialization()) {
789 explicitSpecSuppressor = MD;
790 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
791 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
792 }
793 } else if (isExplicitMemberSpecialization(MD)) {
794 explicitSpecSuppressor = MD;
John McCall66cbcf32010-11-01 01:29:57 +0000795 }
John McCall1fb0caa2010-10-22 21:05:15 +0000796
John McCall110e8e52010-10-29 22:22:43 +0000797 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000798 if (const ClassTemplateSpecializationDecl *spec
John McCall110e8e52010-10-29 22:22:43 +0000799 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCall5a758de2013-02-16 00:17:33 +0000800 mergeTemplateLV(LV, spec, computation);
John McCall3892d022013-02-21 23:42:58 +0000801 if (spec->isExplicitSpecialization()) {
802 explicitSpecSuppressor = spec;
803 } else {
804 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
805 if (isExplicitMemberSpecialization(temp)) {
806 explicitSpecSuppressor = temp->getTemplatedDecl();
807 }
808 }
809 } else if (isExplicitMemberSpecialization(RD)) {
810 explicitSpecSuppressor = RD;
John McCall110e8e52010-10-29 22:22:43 +0000811 }
812
John McCall110e8e52010-10-29 22:22:43 +0000813 // Static data members.
814 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallee301022010-10-30 09:18:49 +0000815 // Modify the variable's linkage by its type, but ignore the
816 // type's visibility unless it's a definition.
Rafael Espindola18895dc2013-02-27 02:27:19 +0000817 LinkageInfo typeLV = VD->getType()->getLinkageAndVisibility();
John McCall3892d022013-02-21 23:42:58 +0000818 LV.mergeMaybeWithVisibility(typeLV,
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000819 !LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit());
John McCall3892d022013-02-21 23:42:58 +0000820
821 if (isExplicitMemberSpecialization(VD)) {
822 explicitSpecSuppressor = VD;
823 }
John McCall5a758de2013-02-16 00:17:33 +0000824
825 // Template members.
826 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
827 bool considerVisibility =
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000828 (!LV.isVisibilityExplicit() &&
829 !classLV.isVisibilityExplicit() &&
John McCalld4c3d662013-02-20 01:54:26 +0000830 !hasExplicitVisibilityAlready(computation));
John McCall5a758de2013-02-16 00:17:33 +0000831 LinkageInfo tempLV =
832 getLVForTemplateParameterList(temp->getTemplateParameters());
833 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall3892d022013-02-21 23:42:58 +0000834
835 if (const RedeclarableTemplateDecl *redeclTemp =
836 dyn_cast<RedeclarableTemplateDecl>(temp)) {
837 if (isExplicitMemberSpecialization(redeclTemp)) {
838 explicitSpecSuppressor = temp->getTemplatedDecl();
839 }
840 }
John McCall110e8e52010-10-29 22:22:43 +0000841 }
842
John McCall3892d022013-02-21 23:42:58 +0000843 // We should never be looking for an attribute directly on a template.
844 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
845
846 // If this member is an explicit member specialization, and it has
847 // an explicit attribute, ignore visibility from the parent.
848 bool considerClassVisibility = true;
849 if (explicitSpecSuppressor &&
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000850 // optimization: hasDVA() is true only with explicit visibility.
851 LV.isVisibilityExplicit() &&
852 classLV.getVisibility() != DefaultVisibility &&
John McCall3892d022013-02-21 23:42:58 +0000853 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
854 considerClassVisibility = false;
855 }
856
857 // Finally, merge in information from the class.
858 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall1fb0caa2010-10-22 21:05:15 +0000859 return LV;
John McCall3cdfc4d2010-08-13 08:35:10 +0000860}
861
John McCallf76b0922011-02-08 19:01:05 +0000862static void clearLinkageForClass(const CXXRecordDecl *record) {
863 for (CXXRecordDecl::decl_iterator
864 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
865 Decl *child = *i;
866 if (isa<NamedDecl>(child))
Rafael Espindola838dc592013-01-12 06:42:30 +0000867 cast<NamedDecl>(child)->ClearLinkageCache();
John McCallf76b0922011-02-08 19:01:05 +0000868 }
869}
870
David Blaikie99ba9e32011-12-20 02:48:34 +0000871void NamedDecl::anchor() { }
872
Rafael Espindola838dc592013-01-12 06:42:30 +0000873void NamedDecl::ClearLinkageCache() {
John McCallf76b0922011-02-08 19:01:05 +0000874 // Note that we can't skip clearing the linkage of children just
875 // because the parent doesn't have cached linkage: we don't cache
876 // when computing linkage for parent contexts.
877
Rafael Espindola838dc592013-01-12 06:42:30 +0000878 HasCachedLinkage = 0;
John McCallf76b0922011-02-08 19:01:05 +0000879
880 // If we're changing the linkage of a class, we need to reset the
881 // linkage of child declarations, too.
882 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
883 clearLinkageForClass(record);
884
Dmitri Gribenkof8c12142013-02-03 16:10:26 +0000885 if (ClassTemplateDecl *temp = dyn_cast<ClassTemplateDecl>(this)) {
John McCallf76b0922011-02-08 19:01:05 +0000886 // Clear linkage for the template pattern.
887 CXXRecordDecl *record = temp->getTemplatedDecl();
Rafael Espindola838dc592013-01-12 06:42:30 +0000888 record->HasCachedLinkage = 0;
John McCallf76b0922011-02-08 19:01:05 +0000889 clearLinkageForClass(record);
890
John McCall15e310a2011-02-19 02:53:41 +0000891 // We need to clear linkage for specializations, too.
892 for (ClassTemplateDecl::spec_iterator
893 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola838dc592013-01-12 06:42:30 +0000894 i->ClearLinkageCache();
John McCallf76b0922011-02-08 19:01:05 +0000895 }
John McCall15e310a2011-02-19 02:53:41 +0000896
897 // Clear cached linkage for function template decls, too.
Dmitri Gribenkof8c12142013-02-03 16:10:26 +0000898 if (FunctionTemplateDecl *temp = dyn_cast<FunctionTemplateDecl>(this)) {
Rafael Espindola838dc592013-01-12 06:42:30 +0000899 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall15e310a2011-02-19 02:53:41 +0000900 for (FunctionTemplateDecl::spec_iterator
901 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola838dc592013-01-12 06:42:30 +0000902 i->ClearLinkageCache();
John McCall78951942011-03-22 06:58:49 +0000903 }
John McCall15e310a2011-02-19 02:53:41 +0000904
John McCallf76b0922011-02-08 19:01:05 +0000905}
906
Douglas Gregor381d34e2010-12-06 18:36:25 +0000907Linkage NamedDecl::getLinkage() const {
Richard Smithad0e27b2013-02-12 05:48:23 +0000908 if (HasCachedLinkage)
Rafael Espindola838dc592013-01-12 06:42:30 +0000909 return Linkage(CachedLinkage);
Rafael Espindola838dc592013-01-12 06:42:30 +0000910
John McCalld4c3d662013-02-20 01:54:26 +0000911 // We don't care about visibility here, so ask for the cheapest
912 // possible visibility analysis.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000913 CachedLinkage = getLVForDecl(this, LVForExplicitValue).getLinkage();
Rafael Espindola838dc592013-01-12 06:42:30 +0000914 HasCachedLinkage = 1;
915
916#ifndef NDEBUG
917 verifyLinkage();
918#endif
919
920 return Linkage(CachedLinkage);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000921}
922
John McCallaf146032010-10-30 11:50:40 +0000923LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCall5a758de2013-02-16 00:17:33 +0000924 LVComputationKind computation =
925 (usesTypeVisibility(this) ? LVForType : LVForValue);
926 LinkageInfo LI = getLVForDecl(this, computation);
Rafael Espindola838dc592013-01-12 06:42:30 +0000927 if (HasCachedLinkage) {
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000928 assert(Linkage(CachedLinkage) == LI.getLinkage());
Rafael Espindola838dc592013-01-12 06:42:30 +0000929 return LI;
Rafael Espindola140aadf2012-12-25 07:31:49 +0000930 }
Rafael Espindola838dc592013-01-12 06:42:30 +0000931 HasCachedLinkage = 1;
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000932 CachedLinkage = LI.getLinkage();
Rafael Espindola6acc4bc2013-01-05 01:28:37 +0000933
934#ifndef NDEBUG
Rafael Espindola838dc592013-01-12 06:42:30 +0000935 verifyLinkage();
936#endif
937
938 return LI;
939}
940
941void NamedDecl::verifyLinkage() const {
Rafael Espindola6acc4bc2013-01-05 01:28:37 +0000942 // In C (because of gnu inline) and in c++ with microsoft extensions an
943 // static can follow an extern, so we can have two decls with different
944 // linkages.
945 const LangOptions &Opts = getASTContext().getLangOpts();
946 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
Rafael Espindola838dc592013-01-12 06:42:30 +0000947 return;
Rafael Espindola6acc4bc2013-01-05 01:28:37 +0000948
949 // We have just computed the linkage for this decl. By induction we know
950 // that all other computed linkages match, check that the one we just computed
951 // also does.
952 NamedDecl *D = NULL;
953 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
954 NamedDecl *T = cast<NamedDecl>(*I);
955 if (T == this)
956 continue;
Rafael Espindola838dc592013-01-12 06:42:30 +0000957 if (T->HasCachedLinkage != 0) {
Rafael Espindola6acc4bc2013-01-05 01:28:37 +0000958 D = T;
959 break;
960 }
961 }
962 assert(!D || D->CachedLinkage == CachedLinkage);
John McCall0df95872010-10-29 00:29:13 +0000963}
Ted Kremenekbecc3082010-04-20 23:15:35 +0000964
David Blaikiedc84cd52013-02-20 22:23:23 +0000965Optional<Visibility>
John McCalld4c3d662013-02-20 01:54:26 +0000966NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +0000967 // Check the declaration itself first.
968 if (Optional<Visibility> V = getVisibilityOf(this, kind))
969 return V;
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000970
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +0000971 // If this is a member class of a specialization of a class template
972 // and the corresponding decl has explicit visibility, use that.
973 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
974 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
975 if (InstantiatedFrom)
976 return getVisibilityOf(InstantiatedFrom, kind);
977 }
978
979 // If there wasn't explicit visibility there, and this is a
980 // specialization of a class template, check for visibility
981 // on the pattern.
982 if (const ClassTemplateSpecializationDecl *spec
983 = dyn_cast<ClassTemplateSpecializationDecl>(this))
984 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
985 kind);
986
987 // Use the most recent declaration.
988 const NamedDecl *MostRecent = cast<NamedDecl>(this->getMostRecentDecl());
989 if (MostRecent != this)
990 return MostRecent->getExplicitVisibility(kind);
991
992 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola797105a2012-05-16 02:10:38 +0000993 if (Var->isStaticDataMember()) {
994 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
995 if (InstantiatedFrom)
John McCalld4c3d662013-02-20 01:54:26 +0000996 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola797105a2012-05-16 02:10:38 +0000997 }
998
David Blaikie66874fb2013-02-21 01:47:18 +0000999 return None;
Rafael Espindola797105a2012-05-16 02:10:38 +00001000 }
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +00001001 // Also handle function template specializations.
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001002 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001003 // If the function is a specialization of a template with an
1004 // explicit visibility attribute, use that.
1005 if (FunctionTemplateSpecializationInfo *templateInfo
1006 = fn->getTemplateSpecializationInfo())
John McCalld4c3d662013-02-20 01:54:26 +00001007 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1008 kind);
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001009
Rafael Espindola860097c2012-02-23 04:17:32 +00001010 // If the function is a member of a specialization of a class template
1011 // and the corresponding decl has explicit visibility, use that.
1012 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1013 if (InstantiatedFrom)
John McCalld4c3d662013-02-20 01:54:26 +00001014 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola860097c2012-02-23 04:17:32 +00001015
David Blaikie66874fb2013-02-21 01:47:18 +00001016 return None;
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001017 }
1018
Rafael Espindola98499012012-07-31 19:02:02 +00001019 // The visibility of a template is stored in the templated decl.
1020 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
John McCalld4c3d662013-02-20 01:54:26 +00001021 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindola98499012012-07-31 19:02:02 +00001022
David Blaikie66874fb2013-02-21 01:47:18 +00001023 return None;
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001024}
1025
John McCall5a758de2013-02-16 00:17:33 +00001026static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1027 LVComputationKind computation) {
1028 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1029 if (Function->isInAnonymousNamespace() &&
1030 !Function->getDeclContext()->isExternCContext())
1031 return LinkageInfo::uniqueExternal();
1032
1033 // This is a "void f();" which got merged with a file static.
1034 if (Function->getStorageClass() == SC_Static)
1035 return LinkageInfo::internal();
1036
1037 LinkageInfo LV;
John McCalld4c3d662013-02-20 01:54:26 +00001038 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001039 if (Optional<Visibility> Vis =
1040 getExplicitVisibility(Function, computation))
John McCall5a758de2013-02-16 00:17:33 +00001041 LV.mergeVisibility(*Vis, true);
1042 }
1043
1044 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1045 // merging storage classes and visibility attributes, so we don't have to
1046 // look at previous decls in here.
1047
1048 return LV;
1049 }
1050
1051 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1052 if (Var->getStorageClassAsWritten() == SC_Extern ||
1053 Var->getStorageClassAsWritten() == SC_PrivateExtern) {
1054 if (Var->isInAnonymousNamespace() &&
1055 !Var->getDeclContext()->isExternCContext())
1056 return LinkageInfo::uniqueExternal();
1057
1058 // This is an "extern int foo;" which got merged with a file static.
1059 if (Var->getStorageClass() == SC_Static)
1060 return LinkageInfo::internal();
1061
1062 LinkageInfo LV;
1063 if (Var->getStorageClass() == SC_PrivateExtern)
1064 LV.mergeVisibility(HiddenVisibility, true);
John McCalld4c3d662013-02-20 01:54:26 +00001065 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001066 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCall5a758de2013-02-16 00:17:33 +00001067 LV.mergeVisibility(*Vis, true);
1068 }
1069
1070 // Note that Sema::MergeVarDecl already takes care of implementing
1071 // C99 6.2.2p4 and propagating the visibility attribute, so we don't
1072 // have to do it here.
1073 return LV;
1074 }
1075 }
1076
1077 return LinkageInfo::none();
1078}
1079
1080static LinkageInfo getLVForDecl(const NamedDecl *D,
1081 LVComputationKind computation) {
Ted Kremenekbecc3082010-04-20 23:15:35 +00001082 // Objective-C: treat all Objective-C declarations as having external
1083 // linkage.
John McCall0df95872010-10-29 00:29:13 +00001084 switch (D->getKind()) {
Ted Kremenekbecc3082010-04-20 23:15:35 +00001085 default:
1086 break;
Argyrios Kyrtzidisf8d34ed2011-12-01 01:28:21 +00001087 case Decl::ParmVar:
1088 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +00001089 case Decl::TemplateTemplateParm: // count these as external
1090 case Decl::NonTypeTemplateParm:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001091 case Decl::ObjCAtDefsField:
1092 case Decl::ObjCCategory:
1093 case Decl::ObjCCategoryImpl:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001094 case Decl::ObjCCompatibleAlias:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001095 case Decl::ObjCImplementation:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001096 case Decl::ObjCMethod:
1097 case Decl::ObjCProperty:
1098 case Decl::ObjCPropertyImpl:
1099 case Decl::ObjCProtocol:
John McCallaf146032010-10-30 11:50:40 +00001100 return LinkageInfo::external();
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001101
1102 case Decl::CXXRecord: {
1103 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1104 if (Record->isLambda()) {
1105 if (!Record->getLambdaManglingNumber()) {
1106 // This lambda has no mangling number, so it's internal.
1107 return LinkageInfo::internal();
1108 }
1109
1110 // This lambda has its linkage/visibility determined by its owner.
1111 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1112 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1113 if (isa<ParmVarDecl>(ContextDecl))
1114 DC = ContextDecl->getDeclContext()->getRedeclContext();
1115 else
John McCall5a758de2013-02-16 00:17:33 +00001116 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001117 }
1118
1119 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
John McCall5a758de2013-02-16 00:17:33 +00001120 return getLVForDecl(ND, computation);
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001121
1122 return LinkageInfo::external();
1123 }
1124
1125 break;
1126 }
Ted Kremenekbecc3082010-04-20 23:15:35 +00001127 }
1128
Douglas Gregord85b5b92009-11-25 22:24:25 +00001129 // Handle linkage for namespace-scope names.
John McCall0df95872010-10-29 00:29:13 +00001130 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5a758de2013-02-16 00:17:33 +00001131 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001132
1133 // C++ [basic.link]p5:
1134 // In addition, a member function, static data member, a named
1135 // class or enumeration of class scope, or an unnamed class or
1136 // enumeration defined in a class-scope typedef declaration such
1137 // that the class or enumeration has the typedef name for linkage
1138 // purposes (7.1.3), has external linkage if the name of the class
1139 // has external linkage.
John McCall0df95872010-10-29 00:29:13 +00001140 if (D->getDeclContext()->isRecord())
John McCall5a758de2013-02-16 00:17:33 +00001141 return getLVForClassMember(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001142
1143 // C++ [basic.link]p6:
1144 // The name of a function declared in block scope and the name of
1145 // an object declared by a block scope extern declaration have
1146 // linkage. If there is a visible declaration of an entity with
1147 // linkage having the same name and type, ignoring entities
1148 // declared outside the innermost enclosing namespace scope, the
1149 // block scope declaration declares that same entity and receives
1150 // the linkage of the previous declaration. If there is more than
1151 // one such matching entity, the program is ill-formed. Otherwise,
1152 // if no matching entity is found, the block scope entity receives
1153 // external linkage.
John McCall5a758de2013-02-16 00:17:33 +00001154 if (D->getDeclContext()->isFunctionOrMethod())
1155 return getLVForLocalDecl(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001156
1157 // C++ [basic.link]p6:
1158 // Names not covered by these rules have no linkage.
John McCallaf146032010-10-30 11:50:40 +00001159 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +00001160}
Douglas Gregord85b5b92009-11-25 22:24:25 +00001161
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001162std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregorba103062012-03-27 23:34:16 +00001163 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson3a082d82009-09-08 18:24:21 +00001164}
1165
1166std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001167 std::string QualName;
1168 llvm::raw_string_ostream OS(QualName);
1169 printQualifiedName(OS, P);
1170 return OS.str();
1171}
1172
1173void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1174 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1175}
1176
1177void NamedDecl::printQualifiedName(raw_ostream &OS,
1178 const PrintingPolicy &P) const {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001179 const DeclContext *Ctx = getDeclContext();
1180
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001181 if (Ctx->isFunctionOrMethod()) {
1182 printName(OS);
1183 return;
1184 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001185
Chris Lattner5f9e2722011-07-23 10:55:15 +00001186 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001187 ContextsTy Contexts;
1188
1189 // Collect contexts.
1190 while (Ctx && isa<NamedDecl>(Ctx)) {
1191 Contexts.push_back(Ctx);
1192 Ctx = Ctx->getParent();
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001193 }
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001194
1195 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1196 I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001197 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001198 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer5eada842013-02-22 15:46:01 +00001199 OS << Spec->getName();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001200 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00001201 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1202 TemplateArgs.data(),
1203 TemplateArgs.size(),
1204 P);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001205 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig6be11202009-12-24 23:15:03 +00001206 if (ND->isAnonymousNamespace())
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001207 OS << "<anonymous namespace>";
Sam Weinig6be11202009-12-24 23:15:03 +00001208 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001209 OS << *ND;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001210 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1211 if (!RD->getIdentifier())
1212 OS << "<anonymous " << RD->getKindName() << '>';
1213 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001214 OS << *RD;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001215 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinig3521d012009-12-28 03:19:38 +00001216 const FunctionProtoType *FT = 0;
1217 if (FD->hasWrittenPrototype())
Eli Friedman482466b2012-08-30 22:22:09 +00001218 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinig3521d012009-12-28 03:19:38 +00001219
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001220 OS << *FD << '(';
Sam Weinig3521d012009-12-28 03:19:38 +00001221 if (FT) {
Sam Weinig3521d012009-12-28 03:19:38 +00001222 unsigned NumParams = FD->getNumParams();
1223 for (unsigned i = 0; i < NumParams; ++i) {
1224 if (i)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001225 OS << ", ";
Argyrios Kyrtzidis7ad5c992012-05-05 04:20:37 +00001226 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinig3521d012009-12-28 03:19:38 +00001227 }
1228
1229 if (FT->isVariadic()) {
1230 if (NumParams > 0)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001231 OS << ", ";
1232 OS << "...";
Sam Weinig3521d012009-12-28 03:19:38 +00001233 }
1234 }
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001235 OS << ')';
1236 } else {
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001237 OS << *cast<NamedDecl>(*I);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001238 }
1239 OS << "::";
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001240 }
1241
John McCall8472af42010-03-16 21:48:18 +00001242 if (getDeclName())
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001243 OS << *this;
John McCall8472af42010-03-16 21:48:18 +00001244 else
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001245 OS << "<anonymous>";
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001246}
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001247
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001248void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1249 const PrintingPolicy &Policy,
1250 bool Qualified) const {
1251 if (Qualified)
1252 printQualifiedName(OS, Policy);
1253 else
1254 printName(OS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001255}
1256
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001257bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001258 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1259
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001260 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1261 // We want to keep it, unless it nominates same namespace.
1262 if (getKind() == Decl::UsingDirective) {
Douglas Gregordb992412011-02-25 16:33:46 +00001263 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1264 ->getOriginalNamespace() ==
1265 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1266 ->getOriginalNamespace();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001267 }
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001269 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1270 // For function declarations, we keep track of redeclarations.
Douglas Gregoref96ee02012-01-14 16:38:05 +00001271 return FD->getPreviousDecl() == OldD;
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001272
Douglas Gregore53060f2009-06-25 22:08:12 +00001273 // For function templates, the underlying function declarations are linked.
1274 if (const FunctionTemplateDecl *FunctionTemplate
1275 = dyn_cast<FunctionTemplateDecl>(this))
1276 if (const FunctionTemplateDecl *OldFunctionTemplate
1277 = dyn_cast<FunctionTemplateDecl>(OldD))
1278 return FunctionTemplate->getTemplatedDecl()
1279 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Steve Naroff0de21fd2009-02-22 19:35:57 +00001281 // For method declarations, we keep track of redeclarations.
1282 if (isa<ObjCMethodDecl>(this))
1283 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001284
John McCallf36e02d2009-10-09 21:13:30 +00001285 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1286 return true;
1287
John McCall9488ea12009-11-17 05:59:44 +00001288 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1289 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1290 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1291
Douglas Gregordc355712011-02-25 00:36:19 +00001292 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1293 ASTContext &Context = getASTContext();
1294 return Context.getCanonicalNestedNameSpecifier(
1295 cast<UsingDecl>(this)->getQualifier()) ==
1296 Context.getCanonicalNestedNameSpecifier(
1297 cast<UsingDecl>(OldD)->getQualifier());
1298 }
Argyrios Kyrtzidisc80117e2010-11-04 08:48:52 +00001299
Douglas Gregor7a537402012-01-03 23:26:26 +00001300 // A typedef of an Objective-C class type can replace an Objective-C class
1301 // declaration or definition, and vice versa.
1302 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1303 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1304 return true;
1305
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001306 // For non-function declarations, if the declarations are of the
1307 // same kind then this must be a redeclaration, or semantic analysis
1308 // would not have given us the new declaration.
1309 return this->getKind() == OldD->getKind();
1310}
1311
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001312bool NamedDecl::hasLinkage() const {
Douglas Gregord85b5b92009-11-25 22:24:25 +00001313 return getLinkage() != NoLinkage;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001314}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001315
Daniel Dunbar6daffa52012-03-08 18:20:41 +00001316NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlssone136e0e2009-06-26 06:29:23 +00001317 NamedDecl *ND = this;
Benjamin Kramer56757e92012-03-08 21:00:45 +00001318 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1319 ND = UD->getTargetDecl();
1320
1321 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1322 return AD->getClassInterface();
1323
1324 return ND;
Anders Carlssone136e0e2009-06-26 06:29:23 +00001325}
1326
John McCall161755a2010-04-06 21:38:20 +00001327bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor5bc37f62012-03-08 02:08:05 +00001328 if (!isCXXClassMember())
1329 return false;
1330
John McCall161755a2010-04-06 21:38:20 +00001331 const NamedDecl *D = this;
1332 if (isa<UsingShadowDecl>(D))
1333 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1334
Francois Pichet87c2e122010-11-21 06:08:52 +00001335 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCall161755a2010-04-06 21:38:20 +00001336 return true;
1337 if (isa<CXXMethodDecl>(D))
1338 return cast<CXXMethodDecl>(D)->isInstance();
1339 if (isa<FunctionTemplateDecl>(D))
1340 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1341 ->getTemplatedDecl())->isInstance();
1342 return false;
1343}
1344
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001345//===----------------------------------------------------------------------===//
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001346// DeclaratorDecl Implementation
1347//===----------------------------------------------------------------------===//
1348
Douglas Gregor1693e152010-07-06 18:42:40 +00001349template <typename DeclT>
1350static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1351 if (decl->getNumTemplateParameterLists() > 0)
1352 return decl->getTemplateParameterList(0)->getTemplateLoc();
1353 else
1354 return decl->getInnerLocStart();
1355}
1356
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001357SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCall4e449832010-05-28 23:32:21 +00001358 TypeSourceInfo *TSI = getTypeSourceInfo();
1359 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001360 return SourceLocation();
1361}
1362
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001363void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1364 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00001365 // Make sure the extended decl info is allocated.
1366 if (!hasExtInfo()) {
1367 // Save (non-extended) type source info pointer.
1368 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1369 // Allocate external info struct.
1370 DeclInfo = new (getASTContext()) ExtInfo;
1371 // Restore savedTInfo into (extended) decl info.
1372 getExtInfo()->TInfo = savedTInfo;
1373 }
1374 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001375 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00001376 } else {
John McCallb6217662010-03-15 10:12:16 +00001377 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00001378 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001379 if (getExtInfo()->NumTemplParamLists == 0) {
1380 // Save type source info pointer.
1381 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1382 // Deallocate the extended decl info.
1383 getASTContext().Deallocate(getExtInfo());
1384 // Restore savedTInfo into (non-extended) decl info.
1385 DeclInfo = savedTInfo;
1386 }
1387 else
1388 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00001389 }
1390 }
1391}
1392
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001393void
1394DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1395 unsigned NumTPLists,
1396 TemplateParameterList **TPLists) {
1397 assert(NumTPLists > 0);
1398 // Make sure the extended decl info is allocated.
1399 if (!hasExtInfo()) {
1400 // Save (non-extended) type source info pointer.
1401 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1402 // Allocate external info struct.
1403 DeclInfo = new (getASTContext()) ExtInfo;
1404 // Restore savedTInfo into (extended) decl info.
1405 getExtInfo()->TInfo = savedTInfo;
1406 }
1407 // Set the template parameter lists info.
1408 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1409}
1410
Douglas Gregor1693e152010-07-06 18:42:40 +00001411SourceLocation DeclaratorDecl::getOuterLocStart() const {
1412 return getTemplateOrInnerLocStart(this);
1413}
1414
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001415namespace {
1416
1417// Helper function: returns true if QT is or contains a type
1418// having a postfix component.
1419bool typeIsPostfix(clang::QualType QT) {
1420 while (true) {
1421 const Type* T = QT.getTypePtr();
1422 switch (T->getTypeClass()) {
1423 default:
1424 return false;
1425 case Type::Pointer:
1426 QT = cast<PointerType>(T)->getPointeeType();
1427 break;
1428 case Type::BlockPointer:
1429 QT = cast<BlockPointerType>(T)->getPointeeType();
1430 break;
1431 case Type::MemberPointer:
1432 QT = cast<MemberPointerType>(T)->getPointeeType();
1433 break;
1434 case Type::LValueReference:
1435 case Type::RValueReference:
1436 QT = cast<ReferenceType>(T)->getPointeeType();
1437 break;
1438 case Type::PackExpansion:
1439 QT = cast<PackExpansionType>(T)->getPattern();
1440 break;
1441 case Type::Paren:
1442 case Type::ConstantArray:
1443 case Type::DependentSizedArray:
1444 case Type::IncompleteArray:
1445 case Type::VariableArray:
1446 case Type::FunctionProto:
1447 case Type::FunctionNoProto:
1448 return true;
1449 }
1450 }
1451}
1452
1453} // namespace
1454
1455SourceRange DeclaratorDecl::getSourceRange() const {
1456 SourceLocation RangeEnd = getLocation();
1457 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1458 if (typeIsPostfix(TInfo->getType()))
1459 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1460 }
1461 return SourceRange(getOuterLocStart(), RangeEnd);
1462}
1463
Abramo Bagnara9b934882010-06-12 08:15:14 +00001464void
Douglas Gregorc722ea42010-06-15 17:44:38 +00001465QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1466 unsigned NumTPLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00001467 TemplateParameterList **TPLists) {
1468 assert((NumTPLists == 0 || TPLists != 0) &&
1469 "Empty array of template parameters with positive size!");
Abramo Bagnara9b934882010-06-12 08:15:14 +00001470
1471 // Free previous template parameters (if any).
1472 if (NumTemplParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001473 Context.Deallocate(TemplParamLists);
Abramo Bagnara9b934882010-06-12 08:15:14 +00001474 TemplParamLists = 0;
1475 NumTemplParamLists = 0;
1476 }
1477 // Set info on matched template parameter lists (if any).
1478 if (NumTPLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001479 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnara9b934882010-06-12 08:15:14 +00001480 NumTemplParamLists = NumTPLists;
1481 for (unsigned i = NumTPLists; i-- > 0; )
1482 TemplParamLists[i] = TPLists[i];
1483 }
1484}
1485
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001486//===----------------------------------------------------------------------===//
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001487// VarDecl Implementation
1488//===----------------------------------------------------------------------===//
1489
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001490const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1491 switch (SC) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00001492 case SC_None: break;
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001493 case SC_Auto: return "auto";
1494 case SC_Extern: return "extern";
1495 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1496 case SC_PrivateExtern: return "__private_extern__";
1497 case SC_Register: return "register";
1498 case SC_Static: return "static";
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001499 }
1500
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001501 llvm_unreachable("Invalid storage class");
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001502}
1503
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001504VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1505 SourceLocation StartL, SourceLocation IdL,
John McCalla93c9342009-12-07 02:54:59 +00001506 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001507 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001508 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001509}
1510
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001511VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1512 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1513 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1514 QualType(), 0, SC_None, SC_None);
1515}
1516
Douglas Gregor381d34e2010-12-06 18:36:25 +00001517void VarDecl::setStorageClass(StorageClass SC) {
1518 assert(isLegalForVariable(SC));
1519 if (getStorageClass() != SC)
Rafael Espindola838dc592013-01-12 06:42:30 +00001520 ClearLinkageCache();
Douglas Gregor381d34e2010-12-06 18:36:25 +00001521
John McCallf1e4fbf2011-05-01 02:13:58 +00001522 VarDeclBits.SClass = SC;
Douglas Gregor381d34e2010-12-06 18:36:25 +00001523}
1524
Douglas Gregor1693e152010-07-06 18:42:40 +00001525SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidisd69f31c2012-10-08 23:08:41 +00001526 if (const Expr *Init = getInit()) {
1527 SourceLocation InitEnd = Init->getLocEnd();
Nico Weber3a344f92013-01-22 17:00:09 +00001528 // If Init is implicit, ignore its source range and fallback on
1529 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1530 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidisd69f31c2012-10-08 23:08:41 +00001531 return SourceRange(getOuterLocStart(), InitEnd);
1532 }
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001533 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001534}
1535
Rafael Espindola7ac928b2013-01-04 21:18:45 +00001536template<typename T>
Rafael Espindola950fee22013-02-14 01:18:37 +00001537static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindolad2fdd422013-02-14 01:47:04 +00001538 // C++ [dcl.link]p1: All function types, function names with external linkage,
1539 // and variable names with external linkage have a language linkage.
1540 if (!isExternalLinkage(D.getLinkage()))
1541 return NoLanguageLinkage;
1542
1543 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola2b721f52013-01-04 20:41:40 +00001544 // C language linkage fits the implementation nicely.
Rafael Espindola78eeba82012-12-28 14:21:58 +00001545 ASTContext &Context = D.getASTContext();
1546 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola950fee22013-02-14 01:18:37 +00001547 return CLanguageLinkage;
1548
Rafael Espindolad2fdd422013-02-14 01:47:04 +00001549 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1550 // language linkage of the names of class members and the function type of
1551 // class member functions.
Rafael Espindola78eeba82012-12-28 14:21:58 +00001552 const DeclContext *DC = D.getDeclContext();
1553 if (DC->isRecord())
Rafael Espindola950fee22013-02-14 01:18:37 +00001554 return CXXLanguageLinkage;
Rafael Espindola78eeba82012-12-28 14:21:58 +00001555
1556 // If the first decl is in an extern "C" context, any other redeclaration
1557 // will have C language linkage. If the first one is not in an extern "C"
1558 // context, we would have reported an error for any other decl being in one.
Rafael Espindola7ac928b2013-01-04 21:18:45 +00001559 const T *First = D.getFirstDeclaration();
Rafael Espindola950fee22013-02-14 01:18:37 +00001560 if (First->getDeclContext()->isExternCContext())
1561 return CLanguageLinkage;
1562 return CXXLanguageLinkage;
Rafael Espindola78eeba82012-12-28 14:21:58 +00001563}
1564
Rafael Espindola950fee22013-02-14 01:18:37 +00001565LanguageLinkage VarDecl::getLanguageLinkage() const {
1566 return getLanguageLinkageTemplate(*this);
Rafael Espindola78eeba82012-12-28 14:21:58 +00001567}
1568
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001569VarDecl *VarDecl::getCanonicalDecl() {
1570 return getFirstDeclaration();
1571}
1572
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001573VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1574 ASTContext &C) const
1575{
Sebastian Redle9d12b62010-01-31 22:27:38 +00001576 // C++ [basic.def]p2:
1577 // A declaration is a definition unless [...] it contains the 'extern'
1578 // specifier or a linkage-specification and neither an initializer [...],
1579 // it declares a static data member in a class declaration [...].
1580 // C++ [temp.expl.spec]p15:
1581 // An explicit specialization of a static data member of a template is a
1582 // definition if the declaration includes an initializer; otherwise, it is
1583 // a declaration.
1584 if (isStaticDataMember()) {
1585 if (isOutOfLine() && (hasInit() ||
1586 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1587 return Definition;
1588 else
1589 return DeclarationOnly;
1590 }
1591 // C99 6.7p5:
1592 // A definition of an identifier is a declaration for that identifier that
1593 // [...] causes storage to be reserved for that object.
1594 // Note: that applies for all non-file-scope objects.
1595 // C99 6.9.2p1:
1596 // If the declaration of an identifier for an object has file scope and an
1597 // initializer, the declaration is an external definition for the identifier
1598 if (hasInit())
1599 return Definition;
1600 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1601 if (hasExternalStorage())
1602 return DeclarationOnly;
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001603
John McCalld931b082010-08-26 03:08:43 +00001604 if (getStorageClassAsWritten() == SC_Extern ||
1605 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregoref96ee02012-01-14 16:38:05 +00001606 for (const VarDecl *PrevVar = getPreviousDecl();
1607 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Rafael Espindola372df452012-12-17 22:23:47 +00001608 if (PrevVar->getLinkage() == InternalLinkage)
Fariborz Jahanian2bf6d7b2010-06-21 16:08:37 +00001609 return DeclarationOnly;
1610 }
1611 }
Sebastian Redle9d12b62010-01-31 22:27:38 +00001612 // C99 6.9.2p2:
1613 // A declaration of an object that has file scope without an initializer,
1614 // and without a storage class specifier or the scs 'static', constitutes
1615 // a tentative definition.
1616 // No such thing in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00001617 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redle9d12b62010-01-31 22:27:38 +00001618 return TentativeDefinition;
1619
1620 // What's left is (in C, block-scope) declarations without initializers or
1621 // external storage. These are definitions.
1622 return Definition;
1623}
1624
Sebastian Redle9d12b62010-01-31 22:27:38 +00001625VarDecl *VarDecl::getActingDefinition() {
1626 DefinitionKind Kind = isThisDeclarationADefinition();
1627 if (Kind != TentativeDefinition)
1628 return 0;
1629
Chris Lattnerf0ed9ef2010-06-14 18:31:46 +00001630 VarDecl *LastTentative = 0;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001631 VarDecl *First = getFirstDeclaration();
1632 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1633 I != E; ++I) {
1634 Kind = (*I)->isThisDeclarationADefinition();
1635 if (Kind == Definition)
1636 return 0;
1637 else if (Kind == TentativeDefinition)
1638 LastTentative = *I;
1639 }
1640 return LastTentative;
1641}
1642
1643bool VarDecl::isTentativeDefinitionNow() const {
1644 DefinitionKind Kind = isThisDeclarationADefinition();
1645 if (Kind != TentativeDefinition)
1646 return false;
1647
1648 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1649 if ((*I)->isThisDeclarationADefinition() == Definition)
1650 return false;
1651 }
Sebastian Redl31310a22010-02-01 20:16:42 +00001652 return true;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001653}
1654
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001655VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redle2c52d22010-02-02 17:55:12 +00001656 VarDecl *First = getFirstDeclaration();
1657 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1658 I != E; ++I) {
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001659 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl31310a22010-02-01 20:16:42 +00001660 return *I;
1661 }
1662 return 0;
1663}
1664
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001665VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall110e8e52010-10-29 22:22:43 +00001666 DefinitionKind Kind = DeclarationOnly;
1667
1668 const VarDecl *First = getFirstDeclaration();
1669 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar047da192012-03-06 23:52:46 +00001670 I != E; ++I) {
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001671 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar047da192012-03-06 23:52:46 +00001672 if (Kind == Definition)
1673 break;
1674 }
John McCall110e8e52010-10-29 22:22:43 +00001675
1676 return Kind;
1677}
1678
Sebastian Redl31310a22010-02-01 20:16:42 +00001679const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001680 redecl_iterator I = redecls_begin(), E = redecls_end();
1681 while (I != E && !I->getInit())
1682 ++I;
1683
1684 if (I != E) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001685 D = *I;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001686 return I->getInit();
1687 }
1688 return 0;
1689}
1690
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001691bool VarDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00001692 if (Decl::isOutOfLine())
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001693 return true;
Chandler Carruth8761d682010-02-21 07:08:09 +00001694
1695 if (!isStaticDataMember())
1696 return false;
1697
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001698 // If this static data member was instantiated from a static data member of
1699 // a class template, check whether that static data member was defined
1700 // out-of-line.
1701 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1702 return VD->isOutOfLine();
1703
1704 return false;
1705}
1706
Douglas Gregor0d035142009-10-27 18:42:08 +00001707VarDecl *VarDecl::getOutOfLineDefinition() {
1708 if (!isStaticDataMember())
1709 return 0;
1710
1711 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1712 RD != RDEnd; ++RD) {
1713 if (RD->getLexicalDeclContext()->isFileContext())
1714 return *RD;
1715 }
1716
1717 return 0;
1718}
1719
Douglas Gregor838db382010-02-11 01:19:42 +00001720void VarDecl::setInit(Expr *I) {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001721 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1722 Eval->~EvaluatedStmt();
Douglas Gregor838db382010-02-11 01:19:42 +00001723 getASTContext().Deallocate(Eval);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001724 }
1725
1726 Init = I;
1727}
1728
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001729bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00001730 const LangOptions &Lang = C.getLangOpts();
Richard Smith1d238ea2011-12-21 02:55:12 +00001731
Richard Smith16581332012-03-02 04:14:40 +00001732 if (!Lang.CPlusPlus)
1733 return false;
1734
1735 // In C++11, any variable of reference type can be used in a constant
1736 // expression if it is initialized by a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00001737 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith16581332012-03-02 04:14:40 +00001738 return true;
1739
1740 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith1d238ea2011-12-21 02:55:12 +00001741 // not require the variable to be non-volatile, but we consider this to be a
1742 // defect.
Richard Smith16581332012-03-02 04:14:40 +00001743 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith1d238ea2011-12-21 02:55:12 +00001744 return false;
1745
1746 // In C++, const, non-volatile variables of integral or enumeration types
1747 // can be used in constant expressions.
1748 if (getType()->isIntegralOrEnumerationType())
1749 return true;
1750
Richard Smith16581332012-03-02 04:14:40 +00001751 // Additionally, in C++11, non-volatile constexpr variables can be used in
1752 // constant expressions.
Richard Smith80ad52f2013-01-02 11:42:31 +00001753 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith1d238ea2011-12-21 02:55:12 +00001754}
1755
Richard Smith099e7f62011-12-19 06:19:21 +00001756/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1757/// form, which contains extra information on the evaluated value of the
1758/// initializer.
1759EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1760 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1761 if (!Eval) {
1762 Stmt *S = Init.get<Stmt *>();
1763 Eval = new (getASTContext()) EvaluatedStmt;
1764 Eval->Value = S;
1765 Init = Eval;
1766 }
1767 return Eval;
1768}
1769
Richard Smith2d6a5672012-01-14 04:30:29 +00001770APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001771 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith2d6a5672012-01-14 04:30:29 +00001772 return evaluateValue(Notes);
1773}
1774
1775APValue *VarDecl::evaluateValue(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001776 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith099e7f62011-12-19 06:19:21 +00001777 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1778
1779 // We only produce notes indicating why an initializer is non-constant the
1780 // first time it is evaluated. FIXME: The notes won't always be emitted the
1781 // first time we try evaluation, so might not be produced at all.
1782 if (Eval->WasEvaluated)
Richard Smith2d6a5672012-01-14 04:30:29 +00001783 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smith099e7f62011-12-19 06:19:21 +00001784
1785 const Expr *Init = cast<Expr>(Eval->Value);
1786 assert(!Init->isValueDependent());
1787
1788 if (Eval->IsEvaluating) {
1789 // FIXME: Produce a diagnostic for self-initialization.
1790 Eval->CheckedICE = true;
1791 Eval->IsICE = false;
Richard Smith2d6a5672012-01-14 04:30:29 +00001792 return 0;
Richard Smith099e7f62011-12-19 06:19:21 +00001793 }
1794
1795 Eval->IsEvaluating = true;
1796
1797 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1798 this, Notes);
1799
1800 // Ensure the result is an uninitialized APValue if evaluation fails.
1801 if (!Result)
1802 Eval->Evaluated = APValue();
1803
1804 Eval->IsEvaluating = false;
1805 Eval->WasEvaluated = true;
1806
1807 // In C++11, we have determined whether the initializer was a constant
1808 // expression as a side-effect.
Richard Smith80ad52f2013-01-02 11:42:31 +00001809 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smith099e7f62011-12-19 06:19:21 +00001810 Eval->CheckedICE = true;
Eli Friedman210386e2012-02-06 21:50:18 +00001811 Eval->IsICE = Result && Notes.empty();
Richard Smith099e7f62011-12-19 06:19:21 +00001812 }
1813
Richard Smith2d6a5672012-01-14 04:30:29 +00001814 return Result ? &Eval->Evaluated : 0;
Richard Smith099e7f62011-12-19 06:19:21 +00001815}
1816
1817bool VarDecl::checkInitIsICE() const {
John McCall73076432012-01-05 00:13:19 +00001818 // Initializers of weak variables are never ICEs.
1819 if (isWeak())
1820 return false;
1821
Richard Smith099e7f62011-12-19 06:19:21 +00001822 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1823 if (Eval->CheckedICE)
1824 // We have already checked whether this subexpression is an
1825 // integral constant expression.
1826 return Eval->IsICE;
1827
1828 const Expr *Init = cast<Expr>(Eval->Value);
1829 assert(!Init->isValueDependent());
1830
1831 // In C++11, evaluate the initializer to check whether it's a constant
1832 // expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00001833 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001834 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00001835 evaluateValue(Notes);
1836 return Eval->IsICE;
1837 }
1838
1839 // It's an ICE whether or not the definition we found is
1840 // out-of-line. See DR 721 and the discussion in Clang PR
1841 // 6206 for details.
1842
1843 if (Eval->CheckingICE)
1844 return false;
1845 Eval->CheckingICE = true;
1846
1847 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1848 Eval->CheckingICE = false;
1849 Eval->CheckedICE = true;
1850 return Eval->IsICE;
1851}
1852
Douglas Gregor03e80032011-06-21 17:03:29 +00001853bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregor0b581082011-06-21 18:20:46 +00001854 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregor03e80032011-06-21 17:03:29 +00001855
1856 const Expr *E = getInit();
1857 if (!E)
1858 return false;
1859
1860 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1861 E = Cleanups->getSubExpr();
1862
1863 return isa<MaterializeTemporaryExpr>(E);
1864}
1865
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001866VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001867 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001868 return cast<VarDecl>(MSI->getInstantiatedFrom());
1869
1870 return 0;
1871}
1872
Douglas Gregor663b5a02009-10-14 20:14:33 +00001873TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redle9d12b62010-01-31 22:27:38 +00001874 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001875 return MSI->getTemplateSpecializationKind();
1876
1877 return TSK_Undeclared;
1878}
1879
Douglas Gregor1028c9f2009-10-14 21:29:40 +00001880MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001881 return getASTContext().getInstantiatedFromStaticDataMember(this);
1882}
1883
Douglas Gregor0a897e32009-10-15 17:21:20 +00001884void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1885 SourceLocation PointOfInstantiation) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00001886 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001887 assert(MSI && "Not an instantiated static data member?");
1888 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor0a897e32009-10-15 17:21:20 +00001889 if (TSK != TSK_ExplicitSpecialization &&
1890 PointOfInstantiation.isValid() &&
1891 MSI->getPointOfInstantiation().isInvalid())
1892 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor7caa6822009-07-24 20:34:43 +00001893}
1894
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001895//===----------------------------------------------------------------------===//
1896// ParmVarDecl Implementation
1897//===----------------------------------------------------------------------===//
Douglas Gregor275a3692009-03-10 23:43:53 +00001898
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001899ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001900 SourceLocation StartLoc,
1901 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001902 QualType T, TypeSourceInfo *TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001903 StorageClass S, StorageClass SCAsWritten,
1904 Expr *DefArg) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001905 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001906 S, SCAsWritten, DefArg);
Douglas Gregor275a3692009-03-10 23:43:53 +00001907}
1908
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001909ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1910 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1911 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1912 0, QualType(), 0, SC_None, SC_None, 0);
1913}
1914
Argyrios Kyrtzidis0bfe83b2011-07-30 17:23:26 +00001915SourceRange ParmVarDecl::getSourceRange() const {
1916 if (!hasInheritedDefaultArg()) {
1917 SourceRange ArgRange = getDefaultArgRange();
1918 if (ArgRange.isValid())
1919 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1920 }
1921
1922 return DeclaratorDecl::getSourceRange();
1923}
1924
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001925Expr *ParmVarDecl::getDefaultArg() {
1926 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1927 assert(!hasUninstantiatedDefaultArg() &&
1928 "Default argument is not yet instantiated!");
1929
1930 Expr *Arg = getInit();
John McCall4765fa02010-12-06 08:20:24 +00001931 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001932 return E->getSubExpr();
Douglas Gregor275a3692009-03-10 23:43:53 +00001933
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001934 return Arg;
1935}
1936
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001937SourceRange ParmVarDecl::getDefaultArgRange() const {
1938 if (const Expr *E = getInit())
1939 return E->getSourceRange();
1940
1941 if (hasUninstantiatedDefaultArg())
1942 return getUninstantiatedDefaultArg()->getSourceRange();
1943
1944 return SourceRange();
Argyrios Kyrtzidisfc7e2a82009-07-05 22:21:56 +00001945}
1946
Douglas Gregor1fe85ea2011-01-05 21:11:38 +00001947bool ParmVarDecl::isParameterPack() const {
1948 return isa<PackExpansionType>(getType());
1949}
1950
Ted Kremenekd211cb72011-10-06 05:00:56 +00001951void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1952 getASTContext().setParameterIndex(this, parameterIndex);
1953 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1954}
1955
1956unsigned ParmVarDecl::getParameterIndexLarge() const {
1957 return getASTContext().getParameterIndex(this);
1958}
1959
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001960//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00001961// FunctionDecl Implementation
1962//===----------------------------------------------------------------------===//
1963
Benjamin Kramer5eada842013-02-22 15:46:01 +00001964void FunctionDecl::getNameForDiagnostic(
1965 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
1966 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorda2142f2011-02-19 18:51:44 +00001967 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1968 if (TemplateArgs)
Benjamin Kramer5eada842013-02-22 15:46:01 +00001969 TemplateSpecializationType::PrintTemplateArgumentList(
1970 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorda2142f2011-02-19 18:51:44 +00001971}
1972
Ted Kremenek9498d382010-04-29 16:49:01 +00001973bool FunctionDecl::isVariadic() const {
1974 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1975 return FT->isVariadic();
1976 return false;
1977}
1978
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001979bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1980 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00001981 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001982 Definition = *I;
1983 return true;
1984 }
1985 }
1986
1987 return false;
1988}
1989
Anders Carlssonffb945f2011-05-14 23:26:09 +00001990bool FunctionDecl::hasTrivialBody() const
1991{
1992 Stmt *S = getBody();
1993 if (!S) {
1994 // Since we don't have a body for this function, we don't know if it's
1995 // trivial or not.
1996 return false;
1997 }
1998
1999 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2000 return true;
2001 return false;
2002}
2003
Sean Hunt10620eb2011-05-06 20:44:56 +00002004bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2005 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Sean Huntcd10dec2011-05-23 23:14:04 +00002006 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002007 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
2008 return true;
2009 }
2010 }
2011
2012 return false;
2013}
2014
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002015Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidisc37929c2009-07-14 03:20:21 +00002016 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2017 if (I->Body) {
2018 Definition = *I;
2019 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet8387e2a2011-04-22 22:18:13 +00002020 } else if (I->IsLateTemplateParsed) {
2021 Definition = *I;
2022 return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +00002023 }
2024 }
2025
2026 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002027}
2028
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00002029void FunctionDecl::setBody(Stmt *B) {
2030 Body = B;
Douglas Gregorb5f35ba2010-12-06 17:49:01 +00002031 if (B)
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00002032 EndRangeLoc = B->getLocEnd();
2033}
2034
Douglas Gregor21386642010-09-28 21:55:22 +00002035void FunctionDecl::setPure(bool P) {
2036 IsPure = P;
2037 if (P)
2038 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2039 Parent->markedVirtualFunctionPure();
2040}
2041
Douglas Gregor48a83b52009-09-12 00:17:51 +00002042bool FunctionDecl::isMain() const {
John McCall23c608d2011-05-15 17:49:20 +00002043 const TranslationUnitDecl *tunit =
2044 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2045 return tunit &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002046 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall23c608d2011-05-15 17:49:20 +00002047 getIdentifier() &&
2048 getIdentifier()->isStr("main");
2049}
2050
2051bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2052 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2053 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2054 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2055 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2056 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2057
2058 if (isa<CXXRecordDecl>(getDeclContext())) return false;
2059 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
2060
2061 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2062 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
2063
2064 ASTContext &Context =
2065 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2066 ->getASTContext();
2067
2068 // The result type and first argument type are constant across all
2069 // these operators. The second argument must be exactly void*.
2070 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregor04495c82009-02-24 01:23:02 +00002071}
2072
Rafael Espindola950fee22013-02-14 01:18:37 +00002073LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindola6dcea672013-01-12 15:27:44 +00002074 // Users expect to be able to write
2075 // extern "C" void *__builtin_alloca (size_t);
2076 // so consider builtins as having C language linkage.
Rafael Espindola508276c2013-01-12 15:27:43 +00002077 if (getBuiltinID())
Rafael Espindola950fee22013-02-14 01:18:37 +00002078 return CLanguageLinkage;
Rafael Espindola508276c2013-01-12 15:27:43 +00002079
Rafael Espindola950fee22013-02-14 01:18:37 +00002080 return getLanguageLinkageTemplate(*this);
Rafael Espindola78eeba82012-12-28 14:21:58 +00002081}
2082
Douglas Gregor8499f3f2009-03-31 16:35:03 +00002083bool FunctionDecl::isGlobal() const {
2084 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2085 return Method->isStatic();
2086
John McCalld931b082010-08-26 03:08:43 +00002087 if (getStorageClass() == SC_Static)
Douglas Gregor8499f3f2009-03-31 16:35:03 +00002088 return false;
2089
Mike Stump1eb44332009-09-09 15:08:12 +00002090 for (const DeclContext *DC = getDeclContext();
Douglas Gregor8499f3f2009-03-31 16:35:03 +00002091 DC->isNamespace();
2092 DC = DC->getParent()) {
2093 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2094 if (!Namespace->getDeclName())
2095 return false;
2096 break;
2097 }
2098 }
2099
2100 return true;
2101}
2102
Richard Smithcd8ab512013-01-17 01:30:42 +00002103bool FunctionDecl::isNoReturn() const {
2104 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smith7586a6e2013-01-30 05:45:05 +00002105 hasAttr<C11NoReturnAttr>() ||
Richard Smithcd8ab512013-01-17 01:30:42 +00002106 getType()->getAs<FunctionType>()->getNoReturnAttr();
2107}
2108
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002109void
2110FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2111 redeclarable_base::setPreviousDeclaration(PrevDecl);
2112
2113 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2114 FunctionTemplateDecl *PrevFunTmpl
2115 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2116 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2117 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2118 }
Douglas Gregor8f150942010-12-09 16:59:22 +00002119
Axel Naumannd9d137e2011-11-08 18:21:06 +00002120 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregor8f150942010-12-09 16:59:22 +00002121 IsInline = true;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002122}
2123
2124const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2125 return getFirstDeclaration();
2126}
2127
2128FunctionDecl *FunctionDecl::getCanonicalDecl() {
2129 return getFirstDeclaration();
2130}
2131
Douglas Gregor381d34e2010-12-06 18:36:25 +00002132void FunctionDecl::setStorageClass(StorageClass SC) {
2133 assert(isLegalForFunction(SC));
2134 if (getStorageClass() != SC)
Rafael Espindola838dc592013-01-12 06:42:30 +00002135 ClearLinkageCache();
Douglas Gregor381d34e2010-12-06 18:36:25 +00002136
2137 SClass = SC;
2138}
2139
Douglas Gregor3e41d602009-02-13 23:20:09 +00002140/// \brief Returns a value indicating whether this function
2141/// corresponds to a builtin function.
2142///
2143/// The function corresponds to a built-in function if it is
2144/// declared at translation scope or within an extern "C" block and
2145/// its name matches with the name of a builtin. The returned value
2146/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump1eb44332009-09-09 15:08:12 +00002147/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregor3e41d602009-02-13 23:20:09 +00002148/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002149unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar60d302a2012-03-06 23:52:37 +00002150 if (!getIdentifier())
Douglas Gregor3c385e52009-02-14 18:57:46 +00002151 return 0;
2152
2153 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar60d302a2012-03-06 23:52:37 +00002154 if (!BuiltinID)
2155 return 0;
2156
2157 ASTContext &Context = getASTContext();
Douglas Gregor3c385e52009-02-14 18:57:46 +00002158 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2159 return BuiltinID;
2160
2161 // This function has the name of a known C library
2162 // function. Determine whether it actually refers to the C library
2163 // function or whether it just has the same name.
2164
Douglas Gregor9add3172009-02-17 03:23:10 +00002165 // If this is a static function, it's not a builtin.
John McCalld931b082010-08-26 03:08:43 +00002166 if (getStorageClass() == SC_Static)
Douglas Gregor9add3172009-02-17 03:23:10 +00002167 return 0;
2168
Douglas Gregor3c385e52009-02-14 18:57:46 +00002169 // If this function is at translation-unit scope and we're not in
2170 // C++, it refers to the C library function.
David Blaikie4e4d0842012-03-11 07:00:24 +00002171 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregor3c385e52009-02-14 18:57:46 +00002172 getDeclContext()->isTranslationUnit())
2173 return BuiltinID;
2174
2175 // If the function is in an extern "C" linkage specification and is
2176 // not marked "overloadable", it's the real function.
2177 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002178 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregor3c385e52009-02-14 18:57:46 +00002179 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002180 !getAttr<OverloadableAttr>())
Douglas Gregor3c385e52009-02-14 18:57:46 +00002181 return BuiltinID;
2182
2183 // Not a builtin
Douglas Gregor3e41d602009-02-13 23:20:09 +00002184 return 0;
2185}
2186
2187
Chris Lattner1ad9b282009-04-25 06:03:53 +00002188/// getNumParams - Return the number of parameters this function must have
Bob Wilson8dbfbf42011-01-10 18:23:55 +00002189/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner1ad9b282009-04-25 06:03:53 +00002190/// after it has been created.
2191unsigned FunctionDecl::getNumParams() const {
Eli Friedman482466b2012-08-30 22:22:09 +00002192 const FunctionType *FT = getType()->castAs<FunctionType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002193 if (isa<FunctionNoProtoType>(FT))
Chris Lattnerd3b90652008-03-15 05:43:15 +00002194 return 0;
Douglas Gregor72564e72009-02-26 23:50:07 +00002195 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Reid Spencer5f016e22007-07-11 17:01:13 +00002197}
2198
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002199void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002200 ArrayRef<ParmVarDecl *> NewParamInfo) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002201 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie4278c652011-09-21 18:16:56 +00002202 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +00002203
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00002205 if (!NewParamInfo.empty()) {
2206 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2207 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 }
2209}
2210
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002211void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy16f1f712012-02-29 10:24:19 +00002212 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2213
2214 if (!NewDecls.empty()) {
2215 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2216 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002217 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy16f1f712012-02-29 10:24:19 +00002218 }
2219}
2220
Chris Lattner8123a952008-04-10 02:22:51 +00002221/// getMinRequiredArguments - Returns the minimum number of arguments
2222/// needed to call this function. This may be fewer than the number of
2223/// function parameters, if some of the parameters have default
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002224/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner8123a952008-04-10 02:22:51 +00002225unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikie4e4d0842012-03-11 07:00:24 +00002226 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002227 return getNumParams();
2228
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002229 unsigned NumRequiredArgs = getNumParams();
2230
2231 // If the last parameter is a parameter pack, we don't need an argument for
2232 // it.
2233 if (NumRequiredArgs > 0 &&
2234 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2235 --NumRequiredArgs;
2236
2237 // If this parameter has a default argument, we don't need an argument for
2238 // it.
2239 while (NumRequiredArgs > 0 &&
2240 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner8123a952008-04-10 02:22:51 +00002241 --NumRequiredArgs;
2242
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002243 // We might have parameter packs before the end. These can't be deduced,
2244 // but they can still handle multiple arguments.
2245 unsigned ArgIdx = NumRequiredArgs;
2246 while (ArgIdx > 0) {
2247 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2248 NumRequiredArgs = ArgIdx;
2249
2250 --ArgIdx;
2251 }
2252
Chris Lattner8123a952008-04-10 02:22:51 +00002253 return NumRequiredArgs;
2254}
2255
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002256static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2257 // Only consider file-scope declarations in this test.
2258 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2259 return false;
2260
2261 // Only consider explicit declarations; the presence of a builtin for a
2262 // libcall shouldn't affect whether a definition is externally visible.
2263 if (Redecl->isImplicit())
2264 return false;
2265
2266 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2267 return true; // Not an inline definition
2268
2269 return false;
2270}
2271
Nick Lewyckydce67a72011-07-18 05:26:13 +00002272/// \brief For a function declaration in C or C++, determine whether this
2273/// declaration causes the definition to be externally visible.
2274///
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002275/// Specifically, this determines if adding the current declaration to the set
2276/// of redeclarations of the given functions causes
2277/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewyckydce67a72011-07-18 05:26:13 +00002278bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2279 assert(!doesThisDeclarationHaveABody() &&
2280 "Must have a declaration without a body.");
2281
2282 ASTContext &Context = getASTContext();
2283
David Blaikie4e4d0842012-03-11 07:00:24 +00002284 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002285 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2286 // an externally visible definition.
2287 //
2288 // FIXME: What happens if gnu_inline gets added on after the first
2289 // declaration?
2290 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
2291 return false;
2292
2293 const FunctionDecl *Prev = this;
2294 bool FoundBody = false;
2295 while ((Prev = Prev->getPreviousDecl())) {
2296 FoundBody |= Prev->Body;
2297
2298 if (Prev->Body) {
2299 // If it's not the case that both 'inline' and 'extern' are
2300 // specified on the definition, then it is always externally visible.
2301 if (!Prev->isInlineSpecified() ||
2302 Prev->getStorageClassAsWritten() != SC_Extern)
2303 return false;
2304 } else if (Prev->isInlineSpecified() &&
2305 Prev->getStorageClassAsWritten() != SC_Extern) {
2306 return false;
2307 }
2308 }
2309 return FoundBody;
2310 }
2311
David Blaikie4e4d0842012-03-11 07:00:24 +00002312 if (Context.getLangOpts().CPlusPlus)
Nick Lewyckydce67a72011-07-18 05:26:13 +00002313 return false;
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002314
2315 // C99 6.7.4p6:
2316 // [...] If all of the file scope declarations for a function in a
2317 // translation unit include the inline function specifier without extern,
2318 // then the definition in that translation unit is an inline definition.
2319 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewyckydce67a72011-07-18 05:26:13 +00002320 return false;
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002321 const FunctionDecl *Prev = this;
2322 bool FoundBody = false;
2323 while ((Prev = Prev->getPreviousDecl())) {
2324 FoundBody |= Prev->Body;
2325 if (RedeclForcesDefC99(Prev))
2326 return false;
2327 }
2328 return FoundBody;
Nick Lewyckydce67a72011-07-18 05:26:13 +00002329}
2330
Richard Smithd4497dd2013-01-25 00:08:28 +00002331/// \brief For an inline function definition in C, or for a gnu_inline function
2332/// in C++, determine whether the definition will be externally visible.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002333///
2334/// Inline function definitions are always available for inlining optimizations.
2335/// However, depending on the language dialect, declaration specifiers, and
2336/// attributes, the definition of an inline function may or may not be
2337/// "externally" visible to other translation units in the program.
2338///
2339/// In C99, inline definitions are not externally visible by default. However,
Mike Stump1e5fd7f2010-01-06 02:05:39 +00002340/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002341/// inline definition becomes externally visible (C99 6.7.4p6).
2342///
2343/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2344/// definition, we use the GNU semantics for inline, which are nearly the
2345/// opposite of C99 semantics. In particular, "inline" by itself will create
2346/// an externally visible symbol, but "extern inline" will not create an
2347/// externally visible symbol.
2348bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Sean Hunt10620eb2011-05-06 20:44:56 +00002349 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002350 assert(isInlined() && "Function must be inline");
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00002351 ASTContext &Context = getASTContext();
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002352
David Blaikie4e4d0842012-03-11 07:00:24 +00002353 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002354 // Note: If you change the logic here, please change
2355 // doesDeclarationForceExternallyVisibleDefinition as well.
2356 //
Douglas Gregor8f150942010-12-09 16:59:22 +00002357 // If it's not the case that both 'inline' and 'extern' are
2358 // specified on the definition, then this inline definition is
2359 // externally visible.
2360 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2361 return true;
2362
2363 // If any declaration is 'inline' but not 'extern', then this definition
2364 // is externally visible.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002365 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2366 Redecl != RedeclEnd;
2367 ++Redecl) {
Douglas Gregor8f150942010-12-09 16:59:22 +00002368 if (Redecl->isInlineSpecified() &&
2369 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002370 return true;
Douglas Gregor8f150942010-12-09 16:59:22 +00002371 }
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002372
Douglas Gregor9f9bf252009-04-28 06:37:30 +00002373 return false;
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002374 }
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002375
Richard Smithd4497dd2013-01-25 00:08:28 +00002376 // The rest of this function is C-only.
2377 assert(!Context.getLangOpts().CPlusPlus &&
2378 "should not use C inline rules in C++");
2379
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002380 // C99 6.7.4p6:
2381 // [...] If all of the file scope declarations for a function in a
2382 // translation unit include the inline function specifier without extern,
2383 // then the definition in that translation unit is an inline definition.
2384 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2385 Redecl != RedeclEnd;
2386 ++Redecl) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002387 if (RedeclForcesDefC99(*Redecl))
2388 return true;
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002389 }
2390
2391 // C99 6.7.4p6:
2392 // An inline definition does not provide an external definition for the
2393 // function, and does not forbid an external definition in another
2394 // translation unit.
Douglas Gregor9f9bf252009-04-28 06:37:30 +00002395 return false;
2396}
2397
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002398/// getOverloadedOperator - Which C++ overloaded operator this
2399/// function represents, if any.
2400OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregore94ca9e42008-11-18 14:39:36 +00002401 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2402 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002403 else
2404 return OO_None;
2405}
2406
Sean Hunta6c058d2010-01-13 09:01:02 +00002407/// getLiteralIdentifier - The literal suffix identifier this function
2408/// represents, if any.
2409const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2410 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2411 return getDeclName().getCXXLiteralIdentifier();
2412 else
2413 return 0;
2414}
2415
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002416FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2417 if (TemplateOrSpecialization.isNull())
2418 return TK_NonTemplate;
2419 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2420 return TK_FunctionTemplate;
2421 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2422 return TK_MemberSpecialization;
2423 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2424 return TK_FunctionTemplateSpecialization;
2425 if (TemplateOrSpecialization.is
2426 <DependentFunctionTemplateSpecializationInfo*>())
2427 return TK_DependentFunctionTemplateSpecialization;
2428
David Blaikieb219cfc2011-09-23 05:06:16 +00002429 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002430}
2431
Douglas Gregor2db32322009-10-07 23:56:10 +00002432FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002433 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregor2db32322009-10-07 23:56:10 +00002434 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2435
2436 return 0;
2437}
2438
2439void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002440FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2441 FunctionDecl *FD,
Douglas Gregor2db32322009-10-07 23:56:10 +00002442 TemplateSpecializationKind TSK) {
2443 assert(TemplateOrSpecialization.isNull() &&
2444 "Member function is already a specialization");
2445 MemberSpecializationInfo *Info
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002446 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregor2db32322009-10-07 23:56:10 +00002447 TemplateOrSpecialization = Info;
2448}
2449
Douglas Gregor3b846b62009-10-27 20:53:28 +00002450bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002451 // If the function is invalid, it can't be implicitly instantiated.
2452 if (isInvalidDecl())
Douglas Gregor3b846b62009-10-27 20:53:28 +00002453 return false;
2454
2455 switch (getTemplateSpecializationKind()) {
2456 case TSK_Undeclared:
Douglas Gregor3b846b62009-10-27 20:53:28 +00002457 case TSK_ExplicitInstantiationDefinition:
2458 return false;
2459
2460 case TSK_ImplicitInstantiation:
2461 return true;
2462
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002463 // It is possible to instantiate TSK_ExplicitSpecialization kind
2464 // if the FunctionDecl has a class scope specialization pattern.
2465 case TSK_ExplicitSpecialization:
2466 return getClassScopeSpecializationPattern() != 0;
2467
Douglas Gregor3b846b62009-10-27 20:53:28 +00002468 case TSK_ExplicitInstantiationDeclaration:
2469 // Handled below.
2470 break;
2471 }
2472
2473 // Find the actual template from which we will instantiate.
2474 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002475 bool HasPattern = false;
Douglas Gregor3b846b62009-10-27 20:53:28 +00002476 if (PatternDecl)
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002477 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregor3b846b62009-10-27 20:53:28 +00002478
2479 // C++0x [temp.explicit]p9:
2480 // Except for inline functions, other explicit instantiation declarations
2481 // have the effect of suppressing the implicit instantiation of the entity
2482 // to which they refer.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002483 if (!HasPattern || !PatternDecl)
Douglas Gregor3b846b62009-10-27 20:53:28 +00002484 return true;
2485
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002486 return PatternDecl->isInlined();
Ted Kremenek75df4ee2011-12-01 00:59:17 +00002487}
2488
2489bool FunctionDecl::isTemplateInstantiation() const {
2490 switch (getTemplateSpecializationKind()) {
2491 case TSK_Undeclared:
2492 case TSK_ExplicitSpecialization:
2493 return false;
2494 case TSK_ImplicitInstantiation:
2495 case TSK_ExplicitInstantiationDeclaration:
2496 case TSK_ExplicitInstantiationDefinition:
2497 return true;
2498 }
2499 llvm_unreachable("All TSK values handled.");
2500}
Douglas Gregor3b846b62009-10-27 20:53:28 +00002501
2502FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002503 // Handle class scope explicit specialization special case.
2504 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2505 return getClassScopeSpecializationPattern();
2506
Douglas Gregor3b846b62009-10-27 20:53:28 +00002507 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2508 while (Primary->getInstantiatedFromMemberTemplate()) {
2509 // If we have hit a point where the user provided a specialization of
2510 // this template, we're done looking.
2511 if (Primary->isMemberSpecialization())
2512 break;
2513
2514 Primary = Primary->getInstantiatedFromMemberTemplate();
2515 }
2516
2517 return Primary->getTemplatedDecl();
2518 }
2519
2520 return getInstantiatedFromMemberFunction();
2521}
2522
Douglas Gregor16e8be22009-06-29 17:30:29 +00002523FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002524 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00002525 = TemplateOrSpecialization
2526 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002527 return Info->Template.getPointer();
Douglas Gregor16e8be22009-06-29 17:30:29 +00002528 }
2529 return 0;
2530}
2531
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002532FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2533 return getASTContext().getClassScopeSpecializationPattern(this);
2534}
2535
Douglas Gregor16e8be22009-06-29 17:30:29 +00002536const TemplateArgumentList *
2537FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002538 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002539 = TemplateOrSpecialization
2540 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor16e8be22009-06-29 17:30:29 +00002541 return Info->TemplateArguments;
2542 }
2543 return 0;
2544}
2545
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00002546const ASTTemplateArgumentListInfo *
Abramo Bagnarae03db982010-05-20 15:32:11 +00002547FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2548 if (FunctionTemplateSpecializationInfo *Info
2549 = TemplateOrSpecialization
2550 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2551 return Info->TemplateArgumentsAsWritten;
2552 }
2553 return 0;
2554}
2555
Mike Stump1eb44332009-09-09 15:08:12 +00002556void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002557FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2558 FunctionTemplateDecl *Template,
Douglas Gregor127102b2009-06-29 20:59:39 +00002559 const TemplateArgumentList *TemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002560 void *InsertPos,
Abramo Bagnarae03db982010-05-20 15:32:11 +00002561 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis7b081c82010-07-05 10:37:55 +00002562 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2563 SourceLocation PointOfInstantiation) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00002564 assert(TSK != TSK_Undeclared &&
2565 "Must specify the type of function template specialization");
Mike Stump1eb44332009-09-09 15:08:12 +00002566 FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00002567 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor1637be72009-06-26 00:10:03 +00002568 if (!Info)
Argyrios Kyrtzidisa626a3d2010-09-09 11:28:23 +00002569 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2570 TemplateArgs,
2571 TemplateArgsAsWritten,
2572 PointOfInstantiation);
Douglas Gregor1637be72009-06-26 00:10:03 +00002573 TemplateOrSpecialization = Info;
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002574 Template->addSpecialization(Info, InsertPos);
Douglas Gregor1637be72009-06-26 00:10:03 +00002575}
2576
John McCallaf2094e2010-04-08 09:05:18 +00002577void
2578FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2579 const UnresolvedSetImpl &Templates,
2580 const TemplateArgumentListInfo &TemplateArgs) {
2581 assert(TemplateOrSpecialization.isNull());
2582 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2583 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall21c01602010-04-13 22:18:28 +00002584 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallaf2094e2010-04-08 09:05:18 +00002585 void *Buffer = Context.Allocate(Size);
2586 DependentFunctionTemplateSpecializationInfo *Info =
2587 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2588 TemplateArgs);
2589 TemplateOrSpecialization = Info;
2590}
2591
2592DependentFunctionTemplateSpecializationInfo::
2593DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2594 const TemplateArgumentListInfo &TArgs)
2595 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2596
2597 d.NumTemplates = Ts.size();
2598 d.NumArgs = TArgs.size();
2599
2600 FunctionTemplateDecl **TsArray =
2601 const_cast<FunctionTemplateDecl**>(getTemplates());
2602 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2603 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2604
2605 TemplateArgumentLoc *ArgsArray =
2606 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2607 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2608 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2609}
2610
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002611TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump1eb44332009-09-09 15:08:12 +00002612 // For a function template specialization, query the specialization
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002613 // information object.
Douglas Gregor2db32322009-10-07 23:56:10 +00002614 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002615 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor2db32322009-10-07 23:56:10 +00002616 if (FTSInfo)
2617 return FTSInfo->getTemplateSpecializationKind();
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Douglas Gregor2db32322009-10-07 23:56:10 +00002619 MemberSpecializationInfo *MSInfo
2620 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2621 if (MSInfo)
2622 return MSInfo->getTemplateSpecializationKind();
2623
2624 return TSK_Undeclared;
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002625}
2626
Mike Stump1eb44332009-09-09 15:08:12 +00002627void
Douglas Gregor0a897e32009-10-15 17:21:20 +00002628FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2629 SourceLocation PointOfInstantiation) {
2630 if (FunctionTemplateSpecializationInfo *FTSInfo
2631 = TemplateOrSpecialization.dyn_cast<
2632 FunctionTemplateSpecializationInfo*>()) {
2633 FTSInfo->setTemplateSpecializationKind(TSK);
2634 if (TSK != TSK_ExplicitSpecialization &&
2635 PointOfInstantiation.isValid() &&
2636 FTSInfo->getPointOfInstantiation().isInvalid())
2637 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2638 } else if (MemberSpecializationInfo *MSInfo
2639 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2640 MSInfo->setTemplateSpecializationKind(TSK);
2641 if (TSK != TSK_ExplicitSpecialization &&
2642 PointOfInstantiation.isValid() &&
2643 MSInfo->getPointOfInstantiation().isInvalid())
2644 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2645 } else
David Blaikieb219cfc2011-09-23 05:06:16 +00002646 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor0a897e32009-10-15 17:21:20 +00002647}
2648
2649SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregor2db32322009-10-07 23:56:10 +00002650 if (FunctionTemplateSpecializationInfo *FTSInfo
2651 = TemplateOrSpecialization.dyn_cast<
2652 FunctionTemplateSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00002653 return FTSInfo->getPointOfInstantiation();
Douglas Gregor2db32322009-10-07 23:56:10 +00002654 else if (MemberSpecializationInfo *MSInfo
2655 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00002656 return MSInfo->getPointOfInstantiation();
2657
2658 return SourceLocation();
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00002659}
2660
Douglas Gregor9f185072009-09-11 20:15:17 +00002661bool FunctionDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00002662 if (Decl::isOutOfLine())
Douglas Gregor9f185072009-09-11 20:15:17 +00002663 return true;
2664
2665 // If this function was instantiated from a member function of a
2666 // class template, check whether that member function was defined out-of-line.
2667 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2668 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002669 if (FD->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00002670 return Definition->isOutOfLine();
2671 }
2672
2673 // If this function was instantiated from a function template,
2674 // check whether that function template was defined out-of-line.
2675 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2676 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002677 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00002678 return Definition->isOutOfLine();
2679 }
2680
2681 return false;
2682}
2683
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002684SourceRange FunctionDecl::getSourceRange() const {
2685 return SourceRange(getOuterLocStart(), EndRangeLoc);
2686}
2687
Anna Zaks9392d4e2012-01-18 02:45:01 +00002688unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaksd9b859a2012-01-13 21:52:01 +00002689 IdentifierInfo *FnInfo = getIdentifier();
2690
2691 if (!FnInfo)
Anna Zaks0a151a12012-01-17 00:37:07 +00002692 return 0;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002693
2694 // Builtin handling.
2695 switch (getBuiltinID()) {
2696 case Builtin::BI__builtin_memset:
2697 case Builtin::BI__builtin___memset_chk:
2698 case Builtin::BImemset:
Anna Zaks0a151a12012-01-17 00:37:07 +00002699 return Builtin::BImemset;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002700
2701 case Builtin::BI__builtin_memcpy:
2702 case Builtin::BI__builtin___memcpy_chk:
2703 case Builtin::BImemcpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002704 return Builtin::BImemcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002705
2706 case Builtin::BI__builtin_memmove:
2707 case Builtin::BI__builtin___memmove_chk:
2708 case Builtin::BImemmove:
Anna Zaks0a151a12012-01-17 00:37:07 +00002709 return Builtin::BImemmove;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002710
2711 case Builtin::BIstrlcpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002712 return Builtin::BIstrlcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002713 case Builtin::BIstrlcat:
Anna Zaks0a151a12012-01-17 00:37:07 +00002714 return Builtin::BIstrlcat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002715
2716 case Builtin::BI__builtin_memcmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002717 case Builtin::BImemcmp:
2718 return Builtin::BImemcmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002719
2720 case Builtin::BI__builtin_strncpy:
2721 case Builtin::BI__builtin___strncpy_chk:
2722 case Builtin::BIstrncpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00002723 return Builtin::BIstrncpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002724
2725 case Builtin::BI__builtin_strncmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002726 case Builtin::BIstrncmp:
2727 return Builtin::BIstrncmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002728
2729 case Builtin::BI__builtin_strncasecmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00002730 case Builtin::BIstrncasecmp:
2731 return Builtin::BIstrncasecmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002732
2733 case Builtin::BI__builtin_strncat:
Anna Zaksc36bedc2012-02-01 19:08:57 +00002734 case Builtin::BI__builtin___strncat_chk:
Anna Zaksd9b859a2012-01-13 21:52:01 +00002735 case Builtin::BIstrncat:
Anna Zaks0a151a12012-01-17 00:37:07 +00002736 return Builtin::BIstrncat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002737
2738 case Builtin::BI__builtin_strndup:
2739 case Builtin::BIstrndup:
Anna Zaks0a151a12012-01-17 00:37:07 +00002740 return Builtin::BIstrndup;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002741
Anna Zaksc36bedc2012-02-01 19:08:57 +00002742 case Builtin::BI__builtin_strlen:
2743 case Builtin::BIstrlen:
2744 return Builtin::BIstrlen;
2745
Anna Zaksd9b859a2012-01-13 21:52:01 +00002746 default:
Rafael Espindolad2fdd422013-02-14 01:47:04 +00002747 if (isExternC()) {
Anna Zaksd9b859a2012-01-13 21:52:01 +00002748 if (FnInfo->isStr("memset"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002749 return Builtin::BImemset;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002750 else if (FnInfo->isStr("memcpy"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002751 return Builtin::BImemcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002752 else if (FnInfo->isStr("memmove"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002753 return Builtin::BImemmove;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002754 else if (FnInfo->isStr("memcmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002755 return Builtin::BImemcmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002756 else if (FnInfo->isStr("strncpy"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002757 return Builtin::BIstrncpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002758 else if (FnInfo->isStr("strncmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002759 return Builtin::BIstrncmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002760 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002761 return Builtin::BIstrncasecmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002762 else if (FnInfo->isStr("strncat"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002763 return Builtin::BIstrncat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002764 else if (FnInfo->isStr("strndup"))
Anna Zaks0a151a12012-01-17 00:37:07 +00002765 return Builtin::BIstrndup;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002766 else if (FnInfo->isStr("strlen"))
2767 return Builtin::BIstrlen;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002768 }
2769 break;
2770 }
Anna Zaks0a151a12012-01-17 00:37:07 +00002771 return 0;
Anna Zaksd9b859a2012-01-13 21:52:01 +00002772}
2773
Chris Lattner8a934232008-03-31 00:36:02 +00002774//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002775// FieldDecl Implementation
2776//===----------------------------------------------------------------------===//
2777
Jay Foad4ba2a172011-01-12 09:06:06 +00002778FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002779 SourceLocation StartLoc, SourceLocation IdLoc,
2780 IdentifierInfo *Id, QualType T,
Richard Smith7a614d82011-06-11 17:19:42 +00002781 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smithca523302012-06-10 03:12:00 +00002782 InClassInitStyle InitStyle) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002783 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithca523302012-06-10 03:12:00 +00002784 BW, Mutable, InitStyle);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002785}
2786
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002787FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2788 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2789 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
Richard Smithca523302012-06-10 03:12:00 +00002790 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002791}
2792
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002793bool FieldDecl::isAnonymousStructOrUnion() const {
2794 if (!isImplicit() || getDeclName())
2795 return false;
2796
2797 if (const RecordType *Record = getType()->getAs<RecordType>())
2798 return Record->getDecl()->isAnonymousStructOrUnion();
2799
2800 return false;
2801}
2802
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002803unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2804 assert(isBitField() && "not a bitfield");
2805 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2806 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2807}
2808
John McCallba4f5d52011-01-20 07:57:12 +00002809unsigned FieldDecl::getFieldIndex() const {
2810 if (CachedFieldIndex) return CachedFieldIndex - 1;
2811
Richard Smith180f4792011-11-10 06:34:14 +00002812 unsigned Index = 0;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002813 const RecordDecl *RD = getParent();
2814 const FieldDecl *LastFD = 0;
Eli Friedman5f608ae2012-10-12 23:29:20 +00002815 bool IsMsStruct = RD->isMsStruct(getASTContext());
Richard Smith180f4792011-11-10 06:34:14 +00002816
2817 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2818 I != E; ++I, ++Index) {
David Blaikie262bc182012-04-30 02:36:29 +00002819 I->CachedFieldIndex = Index + 1;
John McCallba4f5d52011-01-20 07:57:12 +00002820
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002821 if (IsMsStruct) {
2822 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie581deb32012-06-06 20:45:41 +00002823 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
Richard Smith180f4792011-11-10 06:34:14 +00002824 --Index;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002825 continue;
2826 }
David Blaikie581deb32012-06-06 20:45:41 +00002827 LastFD = *I;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00002828 }
John McCallba4f5d52011-01-20 07:57:12 +00002829 }
2830
Richard Smith180f4792011-11-10 06:34:14 +00002831 assert(CachedFieldIndex && "failed to find field in parent");
2832 return CachedFieldIndex - 1;
John McCallba4f5d52011-01-20 07:57:12 +00002833}
2834
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00002835SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnarad330e232011-08-05 08:02:55 +00002836 if (const Expr *E = InitializerOrBitWidth.getPointer())
2837 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00002838 return DeclaratorDecl::getSourceRange();
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00002839}
2840
Abramo Bagnaraa5335762012-07-02 20:35:48 +00002841void FieldDecl::setBitWidth(Expr *Width) {
2842 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2843 "bit width or initializer already set");
2844 InitializerOrBitWidth.setPointer(Width);
2845}
2846
Richard Smith7a614d82011-06-11 17:19:42 +00002847void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smithca523302012-06-10 03:12:00 +00002848 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith7a614d82011-06-11 17:19:42 +00002849 "bit width or initializer already set");
2850 InitializerOrBitWidth.setPointer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002851}
2852
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002853//===----------------------------------------------------------------------===//
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002854// TagDecl Implementation
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002855//===----------------------------------------------------------------------===//
2856
Douglas Gregor1693e152010-07-06 18:42:40 +00002857SourceLocation TagDecl::getOuterLocStart() const {
2858 return getTemplateOrInnerLocStart(this);
2859}
2860
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00002861SourceRange TagDecl::getSourceRange() const {
2862 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregor1693e152010-07-06 18:42:40 +00002863 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00002864}
2865
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00002866TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002867 return getFirstDeclaration();
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00002868}
2869
Richard Smith162e1c12011-04-15 14:24:37 +00002870void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2871 TypedefNameDeclOrQualifier = TDD;
Douglas Gregor60e70642010-05-19 18:39:18 +00002872 if (TypeForDecl)
Rafael Espindola838dc592013-01-12 06:42:30 +00002873 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2874 ClearLinkageCache();
Douglas Gregor60e70642010-05-19 18:39:18 +00002875}
2876
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002877void TagDecl::startDefinition() {
Sebastian Redled48a8f2010-08-02 18:27:05 +00002878 IsBeingDefined = true;
John McCall86ff3082010-02-04 22:26:26 +00002879
David Blaikie66cff722012-11-14 01:52:05 +00002880 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall86ff3082010-02-04 22:26:26 +00002881 struct CXXRecordDecl::DefinitionData *Data =
2882 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall22432882010-03-26 21:56:38 +00002883 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2884 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall86ff3082010-02-04 22:26:26 +00002885 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002886}
2887
2888void TagDecl::completeDefinition() {
John McCall5cfa0112010-02-05 01:33:36 +00002889 assert((!isa<CXXRecordDecl>(this) ||
2890 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2891 "definition completed but not started");
2892
John McCall5e1cdac2011-10-07 06:10:15 +00002893 IsCompleteDefinition = true;
Sebastian Redled48a8f2010-08-02 18:27:05 +00002894 IsBeingDefined = false;
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00002895
2896 if (ASTMutationListener *L = getASTMutationListener())
2897 L->CompletedTagDefinition(this);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002898}
2899
John McCall5e1cdac2011-10-07 06:10:15 +00002900TagDecl *TagDecl::getDefinition() const {
2901 if (isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002902 return const_cast<TagDecl *>(this);
Douglas Gregor6bd99292013-02-09 01:35:03 +00002903
2904 // If it's possible for us to have an out-of-date definition, check now.
2905 if (MayHaveOutOfDateDef) {
2906 if (IdentifierInfo *II = getIdentifier()) {
2907 if (II->isOutOfDate()) {
2908 updateOutOfDate(*II);
2909 }
2910 }
2911 }
2912
Andrew Trick220a9c82010-10-19 21:54:32 +00002913 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2914 return CXXRD->getDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002915
2916 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002917 R != REnd; ++R)
John McCall5e1cdac2011-10-07 06:10:15 +00002918 if (R->isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002919 return *R;
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00002921 return 0;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002922}
2923
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002924void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2925 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00002926 // Make sure the extended qualifier info is allocated.
2927 if (!hasExtInfo())
Richard Smith162e1c12011-04-15 14:24:37 +00002928 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCallb6217662010-03-15 10:12:16 +00002929 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002930 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00002931 } else {
John McCallb6217662010-03-15 10:12:16 +00002932 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00002933 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002934 if (getExtInfo()->NumTemplParamLists == 0) {
2935 getASTContext().Deallocate(getExtInfo());
Richard Smith162e1c12011-04-15 14:24:37 +00002936 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002937 }
2938 else
2939 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00002940 }
2941 }
2942}
2943
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002944void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2945 unsigned NumTPLists,
2946 TemplateParameterList **TPLists) {
2947 assert(NumTPLists > 0);
2948 // Make sure the extended decl info is allocated.
2949 if (!hasExtInfo())
2950 // Allocate external info struct.
Richard Smith162e1c12011-04-15 14:24:37 +00002951 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00002952 // Set the template parameter lists info.
2953 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2954}
2955
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002956//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002957// EnumDecl Implementation
2958//===----------------------------------------------------------------------===//
2959
David Blaikie99ba9e32011-12-20 02:48:34 +00002960void EnumDecl::anchor() { }
2961
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002962EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2963 SourceLocation StartLoc, SourceLocation IdLoc,
2964 IdentifierInfo *Id,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00002965 EnumDecl *PrevDecl, bool IsScoped,
2966 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002967 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00002968 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor6bd99292013-02-09 01:35:03 +00002969 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002970 C.getTypeDeclType(Enum, PrevDecl);
2971 return Enum;
2972}
2973
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002974EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2975 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
Douglas Gregor6bd99292013-02-09 01:35:03 +00002976 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2977 0, 0, false, false, false);
2978 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2979 return Enum;
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00002980}
2981
Douglas Gregor838db382010-02-11 01:19:42 +00002982void EnumDecl::completeDefinition(QualType NewType,
John McCall1b5a6182010-05-06 08:49:23 +00002983 QualType NewPromotionType,
2984 unsigned NumPositiveBits,
2985 unsigned NumNegativeBits) {
John McCall5e1cdac2011-10-07 06:10:15 +00002986 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor1274ccd2010-10-08 23:50:27 +00002987 if (!IntegerType)
2988 IntegerType = NewType.getTypePtr();
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002989 PromotionType = NewPromotionType;
John McCall1b5a6182010-05-06 08:49:23 +00002990 setNumPositiveBits(NumPositiveBits);
2991 setNumNegativeBits(NumNegativeBits);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002992 TagDecl::completeDefinition();
2993}
2994
Richard Smith1af83c42012-03-23 03:33:32 +00002995TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2996 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2997 return MSI->getTemplateSpecializationKind();
2998
2999 return TSK_Undeclared;
3000}
3001
3002void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3003 SourceLocation PointOfInstantiation) {
3004 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3005 assert(MSI && "Not an instantiated member enumeration?");
3006 MSI->setTemplateSpecializationKind(TSK);
3007 if (TSK != TSK_ExplicitSpecialization &&
3008 PointOfInstantiation.isValid() &&
3009 MSI->getPointOfInstantiation().isInvalid())
3010 MSI->setPointOfInstantiation(PointOfInstantiation);
3011}
3012
Richard Smithf1c66b42012-03-14 23:13:10 +00003013EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3014 if (SpecializationInfo)
3015 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3016
3017 return 0;
3018}
3019
3020void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3021 TemplateSpecializationKind TSK) {
3022 assert(!SpecializationInfo && "Member enum is already a specialization");
3023 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3024}
3025
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003026//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00003027// RecordDecl Implementation
3028//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00003029
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003030RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3031 SourceLocation StartLoc, SourceLocation IdLoc,
3032 IdentifierInfo *Id, RecordDecl *PrevDecl)
3033 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek63597922008-09-02 21:12:32 +00003034 HasFlexibleArrayMember = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003035 AnonymousStructOrUnion = false;
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00003036 HasObjectMember = false;
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +00003037 HasVolatileMember = false;
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003038 LoadedFieldsFromExternalStorage = false;
Ted Kremenek63597922008-09-02 21:12:32 +00003039 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek63597922008-09-02 21:12:32 +00003040}
3041
Jay Foad4ba2a172011-01-12 09:06:06 +00003042RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003043 SourceLocation StartLoc, SourceLocation IdLoc,
3044 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3045 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3046 PrevDecl);
Douglas Gregor6bd99292013-02-09 01:35:03 +00003047 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3048
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003049 C.getTypeDeclType(R, PrevDecl);
3050 return R;
Ted Kremenek63597922008-09-02 21:12:32 +00003051}
3052
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003053RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3054 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
Douglas Gregor6bd99292013-02-09 01:35:03 +00003055 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3056 SourceLocation(), 0, 0);
3057 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3058 return R;
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00003059}
3060
Douglas Gregorc9b5b402009-03-25 15:59:44 +00003061bool RecordDecl::isInjectedClassName() const {
Mike Stump1eb44332009-09-09 15:08:12 +00003062 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregorc9b5b402009-03-25 15:59:44 +00003063 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3064}
3065
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003066RecordDecl::field_iterator RecordDecl::field_begin() const {
3067 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3068 LoadFieldsFromExternalStorage();
3069
3070 return field_iterator(decl_iterator(FirstDecl));
3071}
3072
Douglas Gregorda2142f2011-02-19 18:51:44 +00003073/// completeDefinition - Notes that the definition of this type is now
3074/// complete.
3075void RecordDecl::completeDefinition() {
John McCall5e1cdac2011-10-07 06:10:15 +00003076 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorda2142f2011-02-19 18:51:44 +00003077 TagDecl::completeDefinition();
3078}
3079
Eli Friedman5f608ae2012-10-12 23:29:20 +00003080/// isMsStruct - Get whether or not this record uses ms_struct layout.
3081/// This which can be turned on with an attribute, pragma, or the
3082/// -mms-bitfields command-line option.
3083bool RecordDecl::isMsStruct(const ASTContext &C) const {
3084 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3085}
3086
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00003087static bool isFieldOrIndirectField(Decl::Kind K) {
3088 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3089}
3090
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003091void RecordDecl::LoadFieldsFromExternalStorage() const {
3092 ExternalASTSource *Source = getASTContext().getExternalSource();
3093 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3094
3095 // Notify that we have a RecordDecl doing some initialization.
3096 ExternalASTSource::Deserializing TheFields(Source);
3097
Chris Lattner5f9e2722011-07-23 10:55:15 +00003098 SmallVector<Decl*, 64> Decls;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003099 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00003100 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3101 Decls)) {
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003102 case ELR_Success:
3103 break;
3104
3105 case ELR_AlreadyLoaded:
3106 case ELR_Failure:
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003107 return;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003108 }
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003109
3110#ifndef NDEBUG
3111 // Check that all decls we got were FieldDecls.
3112 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00003113 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003114#endif
3115
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003116 if (Decls.empty())
3117 return;
3118
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +00003119 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3120 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003121}
3122
Steve Naroff56ee6892008-10-08 17:01:13 +00003123//===----------------------------------------------------------------------===//
3124// BlockDecl Implementation
3125//===----------------------------------------------------------------------===//
3126
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003127void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffe78b8092009-03-13 16:56:44 +00003128 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Steve Naroffe78b8092009-03-13 16:56:44 +00003130 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00003131 if (!NewParamInfo.empty()) {
3132 NumParams = NewParamInfo.size();
3133 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3134 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffe78b8092009-03-13 16:56:44 +00003135 }
3136}
3137
John McCall6b5a61b2011-02-07 10:33:21 +00003138void BlockDecl::setCaptures(ASTContext &Context,
3139 const Capture *begin,
3140 const Capture *end,
3141 bool capturesCXXThis) {
John McCall469a1eb2011-02-02 13:00:07 +00003142 CapturesCXXThis = capturesCXXThis;
3143
3144 if (begin == end) {
John McCall6b5a61b2011-02-07 10:33:21 +00003145 NumCaptures = 0;
3146 Captures = 0;
John McCall469a1eb2011-02-02 13:00:07 +00003147 return;
3148 }
3149
John McCall6b5a61b2011-02-07 10:33:21 +00003150 NumCaptures = end - begin;
3151
3152 // Avoid new Capture[] because we don't want to provide a default
3153 // constructor.
3154 size_t allocationSize = NumCaptures * sizeof(Capture);
3155 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3156 memcpy(buffer, begin, allocationSize);
3157 Captures = static_cast<Capture*>(buffer);
Steve Naroffe78b8092009-03-13 16:56:44 +00003158}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003159
John McCall204e1332011-06-15 22:51:16 +00003160bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3161 for (capture_const_iterator
3162 i = capture_begin(), e = capture_end(); i != e; ++i)
3163 // Only auto vars can be captured, so no redeclaration worries.
3164 if (i->getVariable() == variable)
3165 return true;
3166
3167 return false;
3168}
3169
Douglas Gregor2fcbcef2010-12-21 16:27:07 +00003170SourceRange BlockDecl::getSourceRange() const {
3171 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3172}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003173
3174//===----------------------------------------------------------------------===//
3175// Other Decl Allocation/Deallocation Method Implementations
3176//===----------------------------------------------------------------------===//
3177
David Blaikie99ba9e32011-12-20 02:48:34 +00003178void TranslationUnitDecl::anchor() { }
3179
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003180TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3181 return new (C) TranslationUnitDecl(C);
3182}
3183
David Blaikie99ba9e32011-12-20 02:48:34 +00003184void LabelDecl::anchor() { }
3185
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003186LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara67843042011-03-05 18:21:20 +00003187 SourceLocation IdentL, IdentifierInfo *II) {
3188 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3189}
3190
3191LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3192 SourceLocation IdentL, IdentifierInfo *II,
3193 SourceLocation GnuLabelL) {
3194 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3195 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003196}
3197
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003198LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3199 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3200 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor06c91932010-10-27 19:49:05 +00003201}
3202
David Blaikie99ba9e32011-12-20 02:48:34 +00003203void ValueDecl::anchor() { }
3204
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +00003205bool ValueDecl::isWeak() const {
3206 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3207 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3208 return true;
3209
3210 return isWeakImported();
3211}
3212
David Blaikie99ba9e32011-12-20 02:48:34 +00003213void ImplicitParamDecl::anchor() { }
3214
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003215ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003216 SourceLocation IdLoc,
3217 IdentifierInfo *Id,
3218 QualType Type) {
3219 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003220}
3221
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003222ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3223 unsigned ID) {
3224 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3225 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3226}
3227
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003228FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003229 SourceLocation StartLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00003230 const DeclarationNameInfo &NameInfo,
3231 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003232 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregor8f150942010-12-09 16:59:22 +00003233 bool isInlineSpecified,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003234 bool hasWrittenPrototype,
3235 bool isConstexprSpecified) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003236 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3237 T, TInfo, SC, SCAsWritten,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003238 isInlineSpecified,
3239 isConstexprSpecified);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003240 New->HasWrittenPrototype = hasWrittenPrototype;
3241 return New;
3242}
3243
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003244FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3245 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3246 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3247 DeclarationNameInfo(), QualType(), 0,
3248 SC_None, SC_None, false, false);
3249}
3250
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003251BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3252 return new (C) BlockDecl(DC, L);
3253}
3254
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003255BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3256 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3257 return new (Mem) BlockDecl(0, SourceLocation());
3258}
3259
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003260EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3261 SourceLocation L,
3262 IdentifierInfo *Id, QualType T,
3263 Expr *E, const llvm::APSInt &V) {
3264 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3265}
3266
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003267EnumConstantDecl *
3268EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3269 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3270 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3271 llvm::APSInt());
3272}
3273
David Blaikie99ba9e32011-12-20 02:48:34 +00003274void IndirectFieldDecl::anchor() { }
3275
Benjamin Kramerd9811462010-11-21 14:11:41 +00003276IndirectFieldDecl *
3277IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3278 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3279 unsigned CHS) {
Francois Pichet87c2e122010-11-21 06:08:52 +00003280 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3281}
3282
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003283IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3284 unsigned ID) {
3285 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3286 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3287 QualType(), 0, 0);
3288}
3289
Douglas Gregor8e7139c2010-09-01 20:41:53 +00003290SourceRange EnumConstantDecl::getSourceRange() const {
3291 SourceLocation End = getLocation();
3292 if (Init)
3293 End = Init->getLocEnd();
3294 return SourceRange(getLocation(), End);
3295}
3296
David Blaikie99ba9e32011-12-20 02:48:34 +00003297void TypeDecl::anchor() { }
3298
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003299TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003300 SourceLocation StartLoc, SourceLocation IdLoc,
3301 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3302 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003303}
3304
David Blaikie99ba9e32011-12-20 02:48:34 +00003305void TypedefNameDecl::anchor() { }
3306
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003307TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3308 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3309 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3310}
3311
Richard Smith162e1c12011-04-15 14:24:37 +00003312TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3313 SourceLocation StartLoc,
3314 SourceLocation IdLoc, IdentifierInfo *Id,
3315 TypeSourceInfo *TInfo) {
3316 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3317}
3318
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003319TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3320 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3321 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3322}
3323
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00003324SourceRange TypedefDecl::getSourceRange() const {
3325 SourceLocation RangeEnd = getLocation();
3326 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3327 if (typeIsPostfix(TInfo->getType()))
3328 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3329 }
3330 return SourceRange(getLocStart(), RangeEnd);
3331}
3332
Richard Smith162e1c12011-04-15 14:24:37 +00003333SourceRange TypeAliasDecl::getSourceRange() const {
3334 SourceLocation RangeEnd = getLocStart();
3335 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3336 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3337 return SourceRange(getLocStart(), RangeEnd);
3338}
3339
David Blaikie99ba9e32011-12-20 02:48:34 +00003340void FileScopeAsmDecl::anchor() { }
3341
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003342FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara21e006e2011-03-03 14:20:18 +00003343 StringLiteral *Str,
3344 SourceLocation AsmLoc,
3345 SourceLocation RParenLoc) {
3346 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003347}
Douglas Gregor15de72c2011-12-02 23:23:56 +00003348
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003349FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3350 unsigned ID) {
3351 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3352 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3353}
3354
Michael Han684aa732013-02-22 17:15:32 +00003355void EmptyDecl::anchor() {}
3356
3357EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3358 return new (C) EmptyDecl(DC, L);
3359}
3360
3361EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3362 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EmptyDecl));
3363 return new (Mem) EmptyDecl(0, SourceLocation());
3364}
3365
Douglas Gregor15de72c2011-12-02 23:23:56 +00003366//===----------------------------------------------------------------------===//
3367// ImportDecl Implementation
3368//===----------------------------------------------------------------------===//
3369
3370/// \brief Retrieve the number of module identifiers needed to name the given
3371/// module.
3372static unsigned getNumModuleIdentifiers(Module *Mod) {
3373 unsigned Result = 1;
3374 while (Mod->Parent) {
3375 Mod = Mod->Parent;
3376 ++Result;
3377 }
3378 return Result;
3379}
3380
Douglas Gregor5948ae12012-01-03 18:04:46 +00003381ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00003382 Module *Imported,
3383 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor5948ae12012-01-03 18:04:46 +00003384 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregore6649772011-12-03 00:30:27 +00003385 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00003386{
3387 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3388 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3389 memcpy(StoredLocs, IdentifierLocs.data(),
3390 IdentifierLocs.size() * sizeof(SourceLocation));
3391}
3392
Douglas Gregor5948ae12012-01-03 18:04:46 +00003393ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00003394 Module *Imported, SourceLocation EndLoc)
Douglas Gregor5948ae12012-01-03 18:04:46 +00003395 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregore6649772011-12-03 00:30:27 +00003396 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00003397{
3398 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3399}
3400
3401ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00003402 SourceLocation StartLoc, Module *Imported,
Douglas Gregor15de72c2011-12-02 23:23:56 +00003403 ArrayRef<SourceLocation> IdentifierLocs) {
3404 void *Mem = C.Allocate(sizeof(ImportDecl) +
3405 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor5948ae12012-01-03 18:04:46 +00003406 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +00003407}
3408
3409ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00003410 SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00003411 Module *Imported,
3412 SourceLocation EndLoc) {
3413 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor5948ae12012-01-03 18:04:46 +00003414 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregor15de72c2011-12-02 23:23:56 +00003415 Import->setImplicit();
3416 return Import;
3417}
3418
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003419ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3420 unsigned NumLocations) {
3421 void *Mem = AllocateDeserializedDecl(C, ID,
3422 (sizeof(ImportDecl) +
3423 NumLocations * sizeof(SourceLocation)));
Douglas Gregor15de72c2011-12-02 23:23:56 +00003424 return new (Mem) ImportDecl(EmptyShell());
3425}
3426
3427ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3428 if (!ImportedAndComplete.getInt())
3429 return ArrayRef<SourceLocation>();
3430
3431 const SourceLocation *StoredLocs
3432 = reinterpret_cast<const SourceLocation *>(this + 1);
3433 return ArrayRef<SourceLocation>(StoredLocs,
3434 getNumModuleIdentifiers(getImportedModule()));
3435}
3436
3437SourceRange ImportDecl::getSourceRange() const {
3438 if (!ImportedAndComplete.getInt())
3439 return SourceRange(getLocation(),
3440 *reinterpret_cast<const SourceLocation *>(this + 1));
3441
3442 return SourceRange(getLocation(), getIdentifierLocs().back());
3443}