blob: 0dbb0d30aa237fe661c9656acf0b5351e025b0e7 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000024#include "clang/AST/Stmt.h"
25#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000027#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000028#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000029#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000030#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000031#include "llvm/Support/ErrorHandling.h"
John McCall5f46c482013-02-21 23:42:58 +000032#include "llvm/Support/type_traits.h"
David Blaikie9c70e042011-09-21 18:16:56 +000033#include <algorithm>
34
Chris Lattner6d9a6852006-10-25 05:11:20 +000035using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000036
Chris Lattner88f70d62008-03-15 05:43:15 +000037//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000038// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000039//===----------------------------------------------------------------------===//
40
John McCalldf25c432013-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 McCalld041a9b2013-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 McCalldf25c432013-02-16 00:17:33 +000086
John McCall5f46c482013-02-21 23:42:58 +000087const unsigned IgnoreExplicitVisibilityBit = 2;
88
John McCalldf25c432013-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 McCall5f46c482013-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 McCalld041a9b2013-02-20 01:54:26 +000096 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +000097
John McCall5f46c482013-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 McCalld041a9b2013-02-20 01:54:26 +0000101 LVForValue = NamedDecl::VisibilityForValue,
102
John McCall5f46c482013-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 McCalld041a9b2013-02-20 01:54:26 +0000107
John McCall5f46c482013-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 McCalldf25c432013-02-16 00:17:33 +0000112};
113
John McCalld041a9b2013-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 McCall5f46c482013-02-21 23:42:58 +0000117 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-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 McCall5f46c482013-02-21 23:42:58 +0000125 static_cast<LVComputationKind>(unsigned(oldKind) |
126 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-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 Blaikie05785d12013-02-20 22:23:23 +0000134static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
135 LVComputationKind kind) {
John McCalld041a9b2013-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 McCalldf25c432013-02-16 00:17:33 +0000141typedef NamedDecl::LinkageInfo LinkageInfo;
142
143/// Is the given declaration a "type" or a "value" for the purposes of
144/// visibility computation?
145static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000146 return isa<TypeDecl>(D) ||
147 isa<ClassTemplateDecl>(D) ||
148 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000149}
150
John McCall5f46c482013-02-21 23:42:58 +0000151/// Does the given declaration have member specialization information,
152/// and if so, is it an explicit specialization?
153template <class T> static typename
154llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value,
155 bool>::type
156isExplicitMemberSpecialization(const T *D) {
157 if (const MemberSpecializationInfo *member =
158 D->getMemberSpecializationInfo()) {
159 return member->isExplicitSpecialization();
160 }
161 return false;
162}
163
164/// For templates, this question is easier: a member template can't be
165/// explicitly instantiated, so there's a single bit indicating whether
166/// or not this is an explicit member specialization.
167static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
168 return D->isMemberSpecialization();
169}
170
John McCalld041a9b2013-02-20 01:54:26 +0000171/// Given a visibility attribute, return the explicit visibility
172/// associated with it.
173template <class T>
174static Visibility getVisibilityFromAttr(const T *attr) {
175 switch (attr->getVisibility()) {
176 case T::Default:
177 return DefaultVisibility;
178 case T::Hidden:
179 return HiddenVisibility;
180 case T::Protected:
181 return ProtectedVisibility;
182 }
183 llvm_unreachable("bad visibility kind");
184}
185
John McCalldf25c432013-02-16 00:17:33 +0000186/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000187static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000188 NamedDecl::ExplicitVisibilityKind kind) {
189 // If we're ultimately computing the visibility of a type, look for
190 // a 'type_visibility' attribute before looking for 'visibility'.
191 if (kind == NamedDecl::VisibilityForType) {
192 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
193 return getVisibilityFromAttr(A);
194 }
195 }
196
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000197 // If this declaration has an explicit visibility attribute, use it.
198 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000199 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000200 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000201
202 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
203 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000204 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000205 for (specific_attr_iterator<AvailabilityAttr>
206 A = D->specific_attr_begin<AvailabilityAttr>(),
207 AEnd = D->specific_attr_end<AvailabilityAttr>();
208 A != AEnd; ++A)
209 if ((*A)->getPlatform()->getName().equals("macosx"))
210 return DefaultVisibility;
211 }
212
David Blaikie7a30dc52013-02-21 01:47:18 +0000213 return None;
John McCall457a04e2010-10-22 21:05:15 +0000214}
215
Rafael Espindola2f869a32012-01-14 00:30:36 +0000216static LinkageInfo getLVForType(QualType T) {
217 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
218 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
219}
220
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000221/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000222/// template parameter list. For visibility purposes, template
223/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000224static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000225getLVForTemplateParameterList(const TemplateParameterList *params) {
226 LinkageInfo LV;
227 for (TemplateParameterList::const_iterator P = params->begin(),
228 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000229 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000230
231 // Template type parameters are the most common and never
232 // contribute to visibility, pack or not.
233 if (isa<TemplateTypeParmDecl>(*P))
234 continue;
235
236 // Non-type template parameters can be restricted by the value type, e.g.
237 // template <enum X> class A { ... };
238 // We have to be careful here, though, because we can be dealing with
239 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000240 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000241 // Handle the non-pack case first.
242 if (!NTTP->isExpandedParameterPack()) {
243 if (!NTTP->getType()->isDependentType()) {
244 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000245 }
246 continue;
247 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000248
John McCalldf25c432013-02-16 00:17:33 +0000249 // Look at all the types in an expanded pack.
250 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
251 QualType type = NTTP->getExpansionType(i);
252 if (!type->isDependentType())
253 LV.merge(getLVForType(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000254 }
John McCalldf25c432013-02-16 00:17:33 +0000255 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000256 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000257
John McCalldf25c432013-02-16 00:17:33 +0000258 // Template template parameters can be restricted by their
259 // template parameters, recursively.
260 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
261
262 // Handle the non-pack case first.
263 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000264 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
John McCalldf25c432013-02-16 00:17:33 +0000265 continue;
266 }
267
268 // Look at all expansions in an expanded pack.
269 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
270 i != n; ++i) {
271 LV.merge(getLVForTemplateParameterList(
272 TTP->getExpansionTemplateParameters(i)));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000273 }
274 }
275
John McCall457a04e2010-10-22 21:05:15 +0000276 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000277}
278
Rafael Espindola19de5612013-01-12 06:42:30 +0000279/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000280static LinkageInfo getLVForDecl(const NamedDecl *D,
281 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000282
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000283/// \brief Get the most restrictive linkage for the types and
284/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000285///
286/// Note that we don't take an LVComputationKind because we always
287/// want to honor the visibility of template arguments in the same way.
288static LinkageInfo
289getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
290 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000291
John McCalldf25c432013-02-16 00:17:33 +0000292 for (unsigned i = 0, e = args.size(); i != e; ++i) {
293 const TemplateArgument &arg = args[i];
294 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000295 case TemplateArgument::Null:
296 case TemplateArgument::Integral:
297 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000298 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000299
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300 case TemplateArgument::Type:
John McCalldf25c432013-02-16 00:17:33 +0000301 LV.merge(getLVForType(arg.getAsType()));
302 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000303
304 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000305 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
306 assert(!usesTypeVisibility(ND));
307 LV.merge(getLVForDecl(ND, LVForValue));
308 }
309 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000310
311 case TemplateArgument::NullPtr:
John McCalldf25c432013-02-16 00:17:33 +0000312 LV.merge(getLVForType(arg.getNullPtrType()));
313 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000314
315 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000316 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000317 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000318 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
319 LV.merge(getLVForDecl(Template, LVForValue));
320 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321
322 case TemplateArgument::Pack:
John McCalldf25c432013-02-16 00:17:33 +0000323 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
324 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325 }
John McCalldf25c432013-02-16 00:17:33 +0000326 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000327 }
328
John McCall457a04e2010-10-22 21:05:15 +0000329 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000330}
331
Rafael Espindola2f869a32012-01-14 00:30:36 +0000332static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000333getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
334 return getLVForTemplateArgumentList(TArgs.asArray());
John McCall8823c652010-08-13 08:35:10 +0000335}
336
John McCall5f46c482013-02-21 23:42:58 +0000337static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
338 const FunctionTemplateSpecializationInfo *specInfo) {
339 // Include visibility from the template parameters and arguments
340 // only if this is not an explicit instantiation or specialization
341 // with direct explicit visibility. (Implicit instantiations won't
342 // have a direct attribute.)
343 if (!specInfo->isExplicitInstantiationOrSpecialization())
344 return true;
345
346 return !fn->hasAttr<VisibilityAttr>();
347}
348
John McCalldf25c432013-02-16 00:17:33 +0000349/// Merge in template-related linkage and visibility for the given
350/// function template specialization.
351///
352/// We don't need a computation kind here because we can assume
353/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000354///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000355/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000356static void
357mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
358 const FunctionTemplateSpecializationInfo *specInfo) {
359 bool considerVisibility =
360 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000361
362 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000363 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000364 LinkageInfo tempLV =
365 getLVForTemplateParameterList(temp->getTemplateParameters());
366 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
367
368 // Merge information from the template arguments.
369 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
370 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
371 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000372}
373
John McCall5f46c482013-02-21 23:42:58 +0000374/// Does the given declaration have a direct visibility attribute
375/// that would match the given rules?
376static bool hasDirectVisibilityAttribute(const NamedDecl *D,
377 LVComputationKind computation) {
378 switch (computation) {
379 case LVForType:
380 case LVForExplicitType:
381 if (D->hasAttr<TypeVisibilityAttr>())
382 return true;
383 // fallthrough
384 case LVForValue:
385 case LVForExplicitValue:
386 if (D->hasAttr<VisibilityAttr>())
387 return true;
388 return false;
389 }
390 llvm_unreachable("bad visibility computation kind");
391}
392
John McCalld041a9b2013-02-20 01:54:26 +0000393/// Should we consider visibility associated with the template
394/// arguments and parameters of the given class template specialization?
395static bool shouldConsiderTemplateVisibility(
396 const ClassTemplateSpecializationDecl *spec,
397 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000398 // Include visibility from the template parameters and arguments
399 // only if this is not an explicit instantiation or specialization
400 // with direct explicit visibility (and note that implicit
401 // instantiations won't have a direct attribute).
402 //
403 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000404 // for an explicit specialization when computing the visibility of a
405 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000406 //
407 // This is a bit complex; let's unpack it.
408 //
409 // An explicit class specialization is an independent, top-level
410 // declaration. As such, if it or any of its members has an
411 // explicit visibility attribute, that must directly express the
412 // user's intent, and we should honor it. The same logic applies to
413 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000414
415 // Fast path: if this is not an explicit instantiation or
416 // specialization, we always want to consider template-related
417 // visibility restrictions.
418 if (!spec->isExplicitInstantiationOrSpecialization())
419 return true;
420
421 // This is the 'member thereof' check.
422 if (spec->isExplicitSpecialization() &&
423 hasExplicitVisibilityAlready(computation))
424 return false;
425
John McCall5f46c482013-02-21 23:42:58 +0000426 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000427}
428
429/// Merge in template-related linkage and visibility for the given
430/// class template specialization.
431static void mergeTemplateLV(LinkageInfo &LV,
432 const ClassTemplateSpecializationDecl *spec,
433 LVComputationKind computation) {
434 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000435
436 // Merge information from the template parameters, but ignore
437 // visibility if we're only considering template arguments.
438
John McCalld041a9b2013-02-20 01:54:26 +0000439 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000440 LinkageInfo tempLV =
441 getLVForTemplateParameterList(temp->getTemplateParameters());
442 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000443 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000444
445 // Merge information from the template arguments. We ignore
446 // template-argument visibility if we've got an explicit
447 // instantiation with a visibility attribute.
448 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
449 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
450 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000451}
452
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000453static bool useInlineVisibilityHidden(const NamedDecl *D) {
454 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000455 const LangOptions &Opts = D->getASTContext().getLangOpts();
456 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000457 return false;
458
459 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
460 if (!FD)
461 return false;
462
463 TemplateSpecializationKind TSK = TSK_Undeclared;
464 if (FunctionTemplateSpecializationInfo *spec
465 = FD->getTemplateSpecializationInfo()) {
466 TSK = spec->getTemplateSpecializationKind();
467 } else if (MemberSpecializationInfo *MSI =
468 FD->getMemberSpecializationInfo()) {
469 TSK = MSI->getTemplateSpecializationKind();
470 }
471
472 const FunctionDecl *Def = 0;
473 // InlineVisibilityHidden only applies to definitions, and
474 // isInlined() only gives meaningful answers on definitions
475 // anyway.
476 return TSK != TSK_ExplicitInstantiationDeclaration &&
477 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000478 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000479}
480
Benjamin Kramer3e350262013-02-15 12:30:38 +0000481template <typename T> static bool isInExternCContext(T *D) {
Rafael Espindolaf4187652013-02-14 01:18:37 +0000482 const T *First = D->getFirstDeclaration();
483 return First->getDeclContext()->isExternCContext();
484}
485
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000486static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000487 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000488 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000489 "Not a name having namespace scope");
490 ASTContext &Context = D->getASTContext();
491
492 // C++ [basic.link]p3:
493 // A name having namespace scope (3.3.6) has internal linkage if it
494 // is the name of
495 // - an object, reference, function or function template that is
496 // explicitly declared static; or,
497 // (This bullet corresponds to C99 6.2.2p3.)
498 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
499 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000500 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000501 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000502
Richard Smithdc0ef452012-10-19 06:37:48 +0000503 // - a non-volatile object or reference that is explicitly declared const
504 // or constexpr and neither explicitly declared extern nor previously
505 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000506 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000507 Var->getType().isConstQualified() &&
508 !Var->getType().isVolatileQualified() &&
John McCall8e7d6562010-08-26 03:08:43 +0000509 Var->getStorageClass() != SC_Extern &&
510 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000511 bool FoundExtern = false;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000512 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000513 PrevVar && !FoundExtern;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000514 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000515 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000516 FoundExtern = true;
517
518 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000519 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000520 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000521 if (Var->getStorageClass() == SC_None) {
Douglas Gregorec9fd132012-01-14 16:38:05 +0000522 const VarDecl *PrevVar = Var->getPreviousDecl();
523 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000524 if (PrevVar->getStorageClass() == SC_PrivateExtern)
525 break;
Eli Friedmana7137bc2012-10-26 23:05:34 +0000526 if (PrevVar)
527 return PrevVar->getLinkageAndVisibility();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000528 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000529 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000530 // C++ [temp]p4:
531 // A non-member function template can have internal linkage; any
532 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000533 const FunctionDecl *Function = 0;
534 if (const FunctionTemplateDecl *FunTmpl
535 = dyn_cast<FunctionTemplateDecl>(D))
536 Function = FunTmpl->getTemplatedDecl();
537 else
538 Function = cast<FunctionDecl>(D);
539
540 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000541 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000542 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000543 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
544 // - a data member of an anonymous union.
545 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000546 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000547 }
548
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000549 if (D->isInAnonymousNamespace()) {
550 const VarDecl *Var = dyn_cast<VarDecl>(D);
551 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindolaf4187652013-02-14 01:18:37 +0000552 if ((!Var || !isInExternCContext(Var)) &&
553 (!Func || !isInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000554 return LinkageInfo::uniqueExternal();
555 }
John McCallb7139c42010-10-28 04:18:25 +0000556
John McCall457a04e2010-10-22 21:05:15 +0000557 // Set up the defaults.
558
559 // C99 6.2.2p5:
560 // If the declaration of an identifier for an object has file
561 // scope and no storage-class specifier, its linkage is
562 // external.
John McCallc273f242010-10-30 11:50:40 +0000563 LinkageInfo LV;
564
John McCalld041a9b2013-02-20 01:54:26 +0000565 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000566 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000567 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000568 } else {
569 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000570 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000571 for (const DeclContext *DC = D->getDeclContext();
572 !isa<TranslationUnitDecl>(DC);
573 DC = DC->getParent()) {
574 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
575 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000576 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000577 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000578 break;
579 }
580 }
581 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000582
John McCalldf25c432013-02-16 00:17:33 +0000583 // Add in global settings if the above didn't give us direct visibility.
584 if (!LV.visibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000585 // Use global type/value visibility as appropriate.
586 Visibility globalVisibility;
587 if (computation == LVForValue) {
588 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
589 } else {
590 assert(computation == LVForType);
591 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
592 }
593 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000594
595 // If we're paying attention to global visibility, apply
596 // -finline-visibility-hidden if this is an inline method.
597 if (useInlineVisibilityHidden(D))
598 LV.mergeVisibility(HiddenVisibility, true);
599 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000600 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000601
Douglas Gregorf73b2822009-11-25 22:24:25 +0000602 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000603
Douglas Gregorf73b2822009-11-25 22:24:25 +0000604 // A name having namespace scope has external linkage if it is the
605 // name of
606 //
607 // - an object or reference, unless it has internal linkage; or
608 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000609 // GCC applies the following optimization to variables and static
610 // data members, but not to functions:
611 //
John McCall457a04e2010-10-22 21:05:15 +0000612 // Modify the variable's LV by the LV of its type unless this is
613 // C or extern "C". This follows from [basic.link]p9:
614 // A type without linkage shall not be used as the type of a
615 // variable or function with external linkage unless
616 // - the entity has C language linkage, or
617 // - the entity is declared within an unnamed namespace, or
618 // - the entity is not used or is defined in the same
619 // translation unit.
620 // and [basic.link]p10:
621 // ...the types specified by all declarations referring to a
622 // given variable or function shall be identical...
623 // C does not have an equivalent rule.
624 //
John McCall5fe84122010-10-26 04:59:26 +0000625 // Ignore this if we've got an explicit attribute; the user
626 // probably knows what they're doing.
627 //
John McCall457a04e2010-10-22 21:05:15 +0000628 // Note that we don't want to make the variable non-external
629 // because of this, but unique-external linkage suits us.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000630 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000631 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000632 LinkageInfo TypeLV = getLVForType(Var->getType());
633 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000634 return LinkageInfo::uniqueExternal();
John McCalldf25c432013-02-16 00:17:33 +0000635 if (!LV.visibilityExplicit())
636 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000637 }
638
John McCall23032652010-11-02 18:38:13 +0000639 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000640 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000641
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000642 // Note that Sema::MergeVarDecl already takes care of implementing
643 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
644 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000645
Douglas Gregorf73b2822009-11-25 22:24:25 +0000646 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000647 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000648 // In theory, we can modify the function's LV by the LV of its
649 // type unless it has C linkage (see comment above about variables
650 // for justification). In practice, GCC doesn't do this, so it's
651 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000652
John McCall23032652010-11-02 18:38:13 +0000653 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000654 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000655
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000656 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
657 // merging storage classes and visibility attributes, so we don't have to
658 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000659
John McCallf768aa72011-02-10 06:50:24 +0000660 // In C++, then if the type of the function uses a type with
661 // unique-external linkage, it's not legally usable from outside
662 // this translation unit. However, we should use the C linkage
663 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000664 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000665 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000666 Function->getType()->getLinkage() == UniqueExternalLinkage)
667 return LinkageInfo::uniqueExternal();
668
John McCall5f46c482013-02-21 23:42:58 +0000669 // Consider LV from the template and the template arguments.
670 // We're at file scope, so we do not need to worry about nested
671 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000672 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000673 = Function->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000674 mergeTemplateLV(LV, Function, specInfo);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000675 }
676
Douglas Gregorf73b2822009-11-25 22:24:25 +0000677 // - a named class (Clause 9), or an unnamed class defined in a
678 // typedef declaration in which the class has the typedef name
679 // for linkage purposes (7.1.3); or
680 // - a named enumeration (7.2), or an unnamed enumeration
681 // defined in a typedef declaration in which the enumeration
682 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000683 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
684 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000685 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000686 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000687
John McCall457a04e2010-10-22 21:05:15 +0000688 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000689 // linkage of the template and template arguments. We're at file
690 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000691 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000692 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000693 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000694 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000695
696 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000697 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000698 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000699 computation);
John McCallc273f242010-10-30 11:50:40 +0000700 if (!isExternalLinkage(EnumLV.linkage()))
701 return LinkageInfo::none();
702 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000703
704 // - a template, unless it is a function template that has
705 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000706 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000707 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000708 LinkageInfo tempLV =
709 getLVForTemplateParameterList(temp->getTemplateParameters());
710 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
711
Douglas Gregorf73b2822009-11-25 22:24:25 +0000712 // - a namespace (7.3), unless it is declared within an unnamed
713 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000714 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
715 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000716
John McCall457a04e2010-10-22 21:05:15 +0000717 // By extension, we assign external linkage to Objective-C
718 // interfaces.
719 } else if (isa<ObjCInterfaceDecl>(D)) {
720 // fallout
721
722 // Everything not covered here has no linkage.
723 } else {
John McCallc273f242010-10-30 11:50:40 +0000724 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000725 }
726
727 // If we ended up with non-external linkage, visibility should
728 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000729 if (LV.linkage() != ExternalLinkage)
730 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000731
John McCall457a04e2010-10-22 21:05:15 +0000732 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000733}
734
John McCalldf25c432013-02-16 00:17:33 +0000735static LinkageInfo getLVForClassMember(const NamedDecl *D,
736 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000737 // Only certain class members have linkage. Note that fields don't
738 // really have linkage, but it's convenient to say they do for the
739 // purposes of calculating linkage of pointer-to-data-member
740 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000741 if (!(isa<CXXMethodDecl>(D) ||
742 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000743 isa<FieldDecl>(D) ||
David Blaikie095deba2012-11-14 01:52:05 +0000744 isa<TagDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000745 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000746
John McCall07072662010-11-02 01:45:15 +0000747 LinkageInfo LV;
748
John McCall07072662010-11-02 01:45:15 +0000749 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000750 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000751 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000752 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000753 // If we're paying attention to global visibility, apply
754 // -finline-visibility-hidden if this is an inline method.
755 //
756 // Note that we do this before merging information about
757 // the class visibility.
758 if (!LV.visibilityExplicit() && useInlineVisibilityHidden(D))
759 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000760 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000761
762 // If this class member has an explicit visibility attribute, the only
763 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000764 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000765 LVComputationKind classComputation = computation;
766 if (LV.visibilityExplicit())
767 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000768
John McCall5f46c482013-02-21 23:42:58 +0000769 LinkageInfo classLV =
770 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
771 if (!isExternalLinkage(classLV.linkage()))
John McCallc273f242010-10-30 11:50:40 +0000772 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000773
774 // If the class already has unique-external linkage, we can't improve.
John McCall5f46c482013-02-21 23:42:58 +0000775 if (classLV.linkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000776 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000777
John McCall5f46c482013-02-21 23:42:58 +0000778 // Otherwise, don't merge in classLV yet, because in certain cases
779 // we need to completely ignore the visibility from it.
780
781 // Specifically, if this decl exists and has an explicit attribute.
782 const NamedDecl *explicitSpecSuppressor = 0;
783
John McCall8823c652010-08-13 08:35:10 +0000784 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000785 // If the type of the function uses a type with unique-external
786 // linkage, it's not legally usable from outside this translation unit.
787 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
788 return LinkageInfo::uniqueExternal();
789
John McCall457a04e2010-10-22 21:05:15 +0000790 // If this is a method template specialization, use the linkage for
791 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000792 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000793 = MD->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000794 mergeTemplateLV(LV, MD, spec);
John McCall5f46c482013-02-21 23:42:58 +0000795 if (spec->isExplicitSpecialization()) {
796 explicitSpecSuppressor = MD;
797 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
798 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
799 }
800 } else if (isExplicitMemberSpecialization(MD)) {
801 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000802 }
John McCall457a04e2010-10-22 21:05:15 +0000803
John McCall37bb6c92010-10-29 22:22:43 +0000804 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000805 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000806 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000807 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000808 if (spec->isExplicitSpecialization()) {
809 explicitSpecSuppressor = spec;
810 } else {
811 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
812 if (isExplicitMemberSpecialization(temp)) {
813 explicitSpecSuppressor = temp->getTemplatedDecl();
814 }
815 }
816 } else if (isExplicitMemberSpecialization(RD)) {
817 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000818 }
819
John McCall37bb6c92010-10-29 22:22:43 +0000820 // Static data members.
821 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000822 // Modify the variable's linkage by its type, but ignore the
823 // type's visibility unless it's a definition.
John McCalldf25c432013-02-16 00:17:33 +0000824 LinkageInfo typeLV = getLVForType(VD->getType());
John McCall5f46c482013-02-21 23:42:58 +0000825 LV.mergeMaybeWithVisibility(typeLV,
826 !LV.visibilityExplicit() && !classLV.visibilityExplicit());
827
828 if (isExplicitMemberSpecialization(VD)) {
829 explicitSpecSuppressor = VD;
830 }
John McCalldf25c432013-02-16 00:17:33 +0000831
832 // Template members.
833 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
834 bool considerVisibility =
John McCalld041a9b2013-02-20 01:54:26 +0000835 (!LV.visibilityExplicit() &&
John McCall5f46c482013-02-21 23:42:58 +0000836 !classLV.visibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000837 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000838 LinkageInfo tempLV =
839 getLVForTemplateParameterList(temp->getTemplateParameters());
840 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000841
842 if (const RedeclarableTemplateDecl *redeclTemp =
843 dyn_cast<RedeclarableTemplateDecl>(temp)) {
844 if (isExplicitMemberSpecialization(redeclTemp)) {
845 explicitSpecSuppressor = temp->getTemplatedDecl();
846 }
847 }
John McCall37bb6c92010-10-29 22:22:43 +0000848 }
849
John McCall5f46c482013-02-21 23:42:58 +0000850 // We should never be looking for an attribute directly on a template.
851 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
852
853 // If this member is an explicit member specialization, and it has
854 // an explicit attribute, ignore visibility from the parent.
855 bool considerClassVisibility = true;
856 if (explicitSpecSuppressor &&
857 LV.visibilityExplicit() && // optimization: hasDVA() is true only if this
858 classLV.visibility() != DefaultVisibility &&
859 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
860 considerClassVisibility = false;
861 }
862
863 // Finally, merge in information from the class.
864 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000865 return LV;
John McCall8823c652010-08-13 08:35:10 +0000866}
867
John McCalld396b972011-02-08 19:01:05 +0000868static void clearLinkageForClass(const CXXRecordDecl *record) {
869 for (CXXRecordDecl::decl_iterator
870 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
871 Decl *child = *i;
872 if (isa<NamedDecl>(child))
Rafael Espindola19de5612013-01-12 06:42:30 +0000873 cast<NamedDecl>(child)->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000874 }
875}
876
David Blaikie68e081d2011-12-20 02:48:34 +0000877void NamedDecl::anchor() { }
878
Rafael Espindola19de5612013-01-12 06:42:30 +0000879void NamedDecl::ClearLinkageCache() {
John McCalld396b972011-02-08 19:01:05 +0000880 // Note that we can't skip clearing the linkage of children just
881 // because the parent doesn't have cached linkage: we don't cache
882 // when computing linkage for parent contexts.
883
Rafael Espindola19de5612013-01-12 06:42:30 +0000884 HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000885
886 // If we're changing the linkage of a class, we need to reset the
887 // linkage of child declarations, too.
888 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
889 clearLinkageForClass(record);
890
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000891 if (ClassTemplateDecl *temp = dyn_cast<ClassTemplateDecl>(this)) {
John McCalld396b972011-02-08 19:01:05 +0000892 // Clear linkage for the template pattern.
893 CXXRecordDecl *record = temp->getTemplatedDecl();
Rafael Espindola19de5612013-01-12 06:42:30 +0000894 record->HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000895 clearLinkageForClass(record);
896
John McCall83779672011-02-19 02:53:41 +0000897 // We need to clear linkage for specializations, too.
898 for (ClassTemplateDecl::spec_iterator
899 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000900 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000901 }
John McCall83779672011-02-19 02:53:41 +0000902
903 // Clear cached linkage for function template decls, too.
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000904 if (FunctionTemplateDecl *temp = dyn_cast<FunctionTemplateDecl>(this)) {
Rafael Espindola19de5612013-01-12 06:42:30 +0000905 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000906 for (FunctionTemplateDecl::spec_iterator
907 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000908 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000909 }
John McCall83779672011-02-19 02:53:41 +0000910
John McCalld396b972011-02-08 19:01:05 +0000911}
912
Douglas Gregorbf62d642010-12-06 18:36:25 +0000913Linkage NamedDecl::getLinkage() const {
Richard Smith88581592013-02-12 05:48:23 +0000914 if (HasCachedLinkage)
Rafael Espindola19de5612013-01-12 06:42:30 +0000915 return Linkage(CachedLinkage);
Rafael Espindola19de5612013-01-12 06:42:30 +0000916
John McCalld041a9b2013-02-20 01:54:26 +0000917 // We don't care about visibility here, so ask for the cheapest
918 // possible visibility analysis.
919 CachedLinkage = getLVForDecl(this, LVForExplicitValue).linkage();
Rafael Espindola19de5612013-01-12 06:42:30 +0000920 HasCachedLinkage = 1;
921
922#ifndef NDEBUG
923 verifyLinkage();
924#endif
925
926 return Linkage(CachedLinkage);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000927}
928
John McCallc273f242010-10-30 11:50:40 +0000929LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000930 LVComputationKind computation =
931 (usesTypeVisibility(this) ? LVForType : LVForValue);
932 LinkageInfo LI = getLVForDecl(this, computation);
Rafael Espindola19de5612013-01-12 06:42:30 +0000933 if (HasCachedLinkage) {
934 assert(Linkage(CachedLinkage) == LI.linkage());
935 return LI;
Rafael Espindola54606d52012-12-25 07:31:49 +0000936 }
Rafael Espindola19de5612013-01-12 06:42:30 +0000937 HasCachedLinkage = 1;
938 CachedLinkage = LI.linkage();
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000939
940#ifndef NDEBUG
Rafael Espindola19de5612013-01-12 06:42:30 +0000941 verifyLinkage();
942#endif
943
944 return LI;
945}
946
947void NamedDecl::verifyLinkage() const {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000948 // In C (because of gnu inline) and in c++ with microsoft extensions an
949 // static can follow an extern, so we can have two decls with different
950 // linkages.
951 const LangOptions &Opts = getASTContext().getLangOpts();
952 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
Rafael Espindola19de5612013-01-12 06:42:30 +0000953 return;
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000954
955 // We have just computed the linkage for this decl. By induction we know
956 // that all other computed linkages match, check that the one we just computed
957 // also does.
958 NamedDecl *D = NULL;
959 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
960 NamedDecl *T = cast<NamedDecl>(*I);
961 if (T == this)
962 continue;
Rafael Espindola19de5612013-01-12 06:42:30 +0000963 if (T->HasCachedLinkage != 0) {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000964 D = T;
965 break;
966 }
967 }
968 assert(!D || D->CachedLinkage == CachedLinkage);
John McCall033caa52010-10-29 00:29:13 +0000969}
Ted Kremenek926d8602010-04-20 23:15:35 +0000970
David Blaikie05785d12013-02-20 22:23:23 +0000971Optional<Visibility>
John McCalld041a9b2013-02-20 01:54:26 +0000972NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000973 // Use the most recent declaration of a variable.
Rafael Espindola96e68242012-05-16 02:10:38 +0000974 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
David Blaikie05785d12013-02-20 22:23:23 +0000975 if (Optional<Visibility> V = getVisibilityOf(Var, kind))
Rafael Espindola96e68242012-05-16 02:10:38 +0000976 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000977
Rafael Espindola96e68242012-05-16 02:10:38 +0000978 if (Var->isStaticDataMember()) {
979 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
980 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000981 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000982 }
983
David Blaikie7a30dc52013-02-21 01:47:18 +0000984 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +0000985 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000986 // Use the most recent declaration of a function, and also handle
987 // function template specializations.
988 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
David Blaikie05785d12013-02-20 22:23:23 +0000989 if (Optional<Visibility> V = getVisibilityOf(fn, kind))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000990 return V;
991
992 // If the function is a specialization of a template with an
993 // explicit visibility attribute, use that.
994 if (FunctionTemplateSpecializationInfo *templateInfo
995 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +0000996 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
997 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000998
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000999 // If the function is a member of a specialization of a class template
1000 // and the corresponding decl has explicit visibility, use that.
1001 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1002 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001003 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001004
David Blaikie7a30dc52013-02-21 01:47:18 +00001005 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001006 }
1007
1008 // Otherwise, just check the declaration itself first.
David Blaikie05785d12013-02-20 22:23:23 +00001009 if (Optional<Visibility> V = getVisibilityOf(this, kind))
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001010 return V;
1011
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001012 // The visibility of a template is stored in the templated decl.
1013 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +00001014 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001015
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001016 // If there wasn't explicit visibility there, and this is a
1017 // specialization of a class template, check for visibility
1018 // on the pattern.
1019 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindolaeca5cd22012-07-13 01:19:08 +00001020 = dyn_cast<ClassTemplateSpecializationDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +00001021 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1022 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001023
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001024 // If this is a member class of a specialization of a class template
1025 // and the corresponding decl has explicit visibility, use that.
1026 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
1027 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1028 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001029 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001030 }
1031
David Blaikie7a30dc52013-02-21 01:47:18 +00001032 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001033}
1034
John McCalldf25c432013-02-16 00:17:33 +00001035static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1036 LVComputationKind computation) {
1037 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1038 if (Function->isInAnonymousNamespace() &&
1039 !Function->getDeclContext()->isExternCContext())
1040 return LinkageInfo::uniqueExternal();
1041
1042 // This is a "void f();" which got merged with a file static.
1043 if (Function->getStorageClass() == SC_Static)
1044 return LinkageInfo::internal();
1045
1046 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001047 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001048 if (Optional<Visibility> Vis =
1049 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001050 LV.mergeVisibility(*Vis, true);
1051 }
1052
1053 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1054 // merging storage classes and visibility attributes, so we don't have to
1055 // look at previous decls in here.
1056
1057 return LV;
1058 }
1059
1060 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1061 if (Var->getStorageClassAsWritten() == SC_Extern ||
1062 Var->getStorageClassAsWritten() == SC_PrivateExtern) {
1063 if (Var->isInAnonymousNamespace() &&
1064 !Var->getDeclContext()->isExternCContext())
1065 return LinkageInfo::uniqueExternal();
1066
1067 // This is an "extern int foo;" which got merged with a file static.
1068 if (Var->getStorageClass() == SC_Static)
1069 return LinkageInfo::internal();
1070
1071 LinkageInfo LV;
1072 if (Var->getStorageClass() == SC_PrivateExtern)
1073 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001074 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001075 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001076 LV.mergeVisibility(*Vis, true);
1077 }
1078
1079 // Note that Sema::MergeVarDecl already takes care of implementing
1080 // C99 6.2.2p4 and propagating the visibility attribute, so we don't
1081 // have to do it here.
1082 return LV;
1083 }
1084 }
1085
1086 return LinkageInfo::none();
1087}
1088
1089static LinkageInfo getLVForDecl(const NamedDecl *D,
1090 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001091 // Objective-C: treat all Objective-C declarations as having external
1092 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001093 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001094 default:
1095 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001096 case Decl::ParmVar:
1097 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001098 case Decl::TemplateTemplateParm: // count these as external
1099 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001100 case Decl::ObjCAtDefsField:
1101 case Decl::ObjCCategory:
1102 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001103 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001104 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001105 case Decl::ObjCMethod:
1106 case Decl::ObjCProperty:
1107 case Decl::ObjCPropertyImpl:
1108 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001109 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001110
1111 case Decl::CXXRecord: {
1112 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1113 if (Record->isLambda()) {
1114 if (!Record->getLambdaManglingNumber()) {
1115 // This lambda has no mangling number, so it's internal.
1116 return LinkageInfo::internal();
1117 }
1118
1119 // This lambda has its linkage/visibility determined by its owner.
1120 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1121 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1122 if (isa<ParmVarDecl>(ContextDecl))
1123 DC = ContextDecl->getDeclContext()->getRedeclContext();
1124 else
John McCalldf25c432013-02-16 00:17:33 +00001125 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001126 }
1127
1128 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
John McCalldf25c432013-02-16 00:17:33 +00001129 return getLVForDecl(ND, computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001130
1131 return LinkageInfo::external();
1132 }
1133
1134 break;
1135 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001136 }
1137
Douglas Gregorf73b2822009-11-25 22:24:25 +00001138 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001139 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001140 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001141
1142 // C++ [basic.link]p5:
1143 // In addition, a member function, static data member, a named
1144 // class or enumeration of class scope, or an unnamed class or
1145 // enumeration defined in a class-scope typedef declaration such
1146 // that the class or enumeration has the typedef name for linkage
1147 // purposes (7.1.3), has external linkage if the name of the class
1148 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001149 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001150 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001151
1152 // C++ [basic.link]p6:
1153 // The name of a function declared in block scope and the name of
1154 // an object declared by a block scope extern declaration have
1155 // linkage. If there is a visible declaration of an entity with
1156 // linkage having the same name and type, ignoring entities
1157 // declared outside the innermost enclosing namespace scope, the
1158 // block scope declaration declares that same entity and receives
1159 // the linkage of the previous declaration. If there is more than
1160 // one such matching entity, the program is ill-formed. Otherwise,
1161 // if no matching entity is found, the block scope entity receives
1162 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001163 if (D->getDeclContext()->isFunctionOrMethod())
1164 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001165
1166 // C++ [basic.link]p6:
1167 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001168 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001169}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001170
Douglas Gregor2ada0482009-02-04 17:27:36 +00001171std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregor78254c82012-03-27 23:34:16 +00001172 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson2fb08242009-09-08 18:24:21 +00001173}
1174
1175std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001176 const DeclContext *Ctx = getDeclContext();
1177
1178 if (Ctx->isFunctionOrMethod())
1179 return getNameAsString();
1180
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001181 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001182 ContextsTy Contexts;
1183
1184 // Collect contexts.
1185 while (Ctx && isa<NamedDecl>(Ctx)) {
1186 Contexts.push_back(Ctx);
1187 Ctx = Ctx->getParent();
1188 };
1189
1190 std::string QualName;
1191 llvm::raw_string_ostream OS(QualName);
1192
1193 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1194 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001195 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001196 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001197 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001198 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001199 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1200 TemplateArgs.data(),
1201 TemplateArgs.size(),
1202 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001203 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001204 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001205 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001206 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001207 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001208 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1209 if (!RD->getIdentifier())
1210 OS << "<anonymous " << RD->getKindName() << '>';
1211 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001212 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001213 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001214 const FunctionProtoType *FT = 0;
1215 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001216 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001217
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001218 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001219 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001220 unsigned NumParams = FD->getNumParams();
1221 for (unsigned i = 0; i < NumParams; ++i) {
1222 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001223 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001224 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001225 }
1226
1227 if (FT->isVariadic()) {
1228 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001229 OS << ", ";
1230 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001231 }
1232 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001233 OS << ')';
1234 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001235 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001236 }
1237 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001238 }
1239
John McCalla2a3f7d2010-03-16 21:48:18 +00001240 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001241 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001242 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001243 OS << "<anonymous>";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001244
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001245 return OS.str();
Douglas Gregor2ada0482009-02-04 17:27:36 +00001246}
1247
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001248bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001249 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1250
Douglas Gregor889ceb72009-02-03 19:21:40 +00001251 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1252 // We want to keep it, unless it nominates same namespace.
1253 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001254 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1255 ->getOriginalNamespace() ==
1256 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1257 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001258 }
Mike Stump11289f42009-09-09 15:08:12 +00001259
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001260 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1261 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001262 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001263
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001264 // For function templates, the underlying function declarations are linked.
1265 if (const FunctionTemplateDecl *FunctionTemplate
1266 = dyn_cast<FunctionTemplateDecl>(this))
1267 if (const FunctionTemplateDecl *OldFunctionTemplate
1268 = dyn_cast<FunctionTemplateDecl>(OldD))
1269 return FunctionTemplate->getTemplatedDecl()
1270 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001271
Steve Naroffc4173fa2009-02-22 19:35:57 +00001272 // For method declarations, we keep track of redeclarations.
1273 if (isa<ObjCMethodDecl>(this))
1274 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001275
John McCall9f3059a2009-10-09 21:13:30 +00001276 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1277 return true;
1278
John McCall3f746822009-11-17 05:59:44 +00001279 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1280 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1281 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1282
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001283 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1284 ASTContext &Context = getASTContext();
1285 return Context.getCanonicalNestedNameSpecifier(
1286 cast<UsingDecl>(this)->getQualifier()) ==
1287 Context.getCanonicalNestedNameSpecifier(
1288 cast<UsingDecl>(OldD)->getQualifier());
1289 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001290
Douglas Gregorb59643b2012-01-03 23:26:26 +00001291 // A typedef of an Objective-C class type can replace an Objective-C class
1292 // declaration or definition, and vice versa.
1293 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1294 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1295 return true;
1296
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001297 // For non-function declarations, if the declarations are of the
1298 // same kind then this must be a redeclaration, or semantic analysis
1299 // would not have given us the new declaration.
1300 return this->getKind() == OldD->getKind();
1301}
1302
Douglas Gregoreddf4332009-02-24 20:03:32 +00001303bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +00001304 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001305}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001306
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001307NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001308 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001309 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1310 ND = UD->getTargetDecl();
1311
1312 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1313 return AD->getClassInterface();
1314
1315 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001316}
1317
John McCalla8ae2222010-04-06 21:38:20 +00001318bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001319 if (!isCXXClassMember())
1320 return false;
1321
John McCalla8ae2222010-04-06 21:38:20 +00001322 const NamedDecl *D = this;
1323 if (isa<UsingShadowDecl>(D))
1324 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1325
Francois Pichet783dd6e2010-11-21 06:08:52 +00001326 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001327 return true;
1328 if (isa<CXXMethodDecl>(D))
1329 return cast<CXXMethodDecl>(D)->isInstance();
1330 if (isa<FunctionTemplateDecl>(D))
1331 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1332 ->getTemplatedDecl())->isInstance();
1333 return false;
1334}
1335
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001336//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001337// DeclaratorDecl Implementation
1338//===----------------------------------------------------------------------===//
1339
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001340template <typename DeclT>
1341static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1342 if (decl->getNumTemplateParameterLists() > 0)
1343 return decl->getTemplateParameterList(0)->getTemplateLoc();
1344 else
1345 return decl->getInnerLocStart();
1346}
1347
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001348SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001349 TypeSourceInfo *TSI = getTypeSourceInfo();
1350 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001351 return SourceLocation();
1352}
1353
Douglas Gregor14454802011-02-25 02:25:35 +00001354void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1355 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001356 // Make sure the extended decl info is allocated.
1357 if (!hasExtInfo()) {
1358 // Save (non-extended) type source info pointer.
1359 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1360 // Allocate external info struct.
1361 DeclInfo = new (getASTContext()) ExtInfo;
1362 // Restore savedTInfo into (extended) decl info.
1363 getExtInfo()->TInfo = savedTInfo;
1364 }
1365 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001366 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001367 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001368 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001369 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001370 if (getExtInfo()->NumTemplParamLists == 0) {
1371 // Save type source info pointer.
1372 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1373 // Deallocate the extended decl info.
1374 getASTContext().Deallocate(getExtInfo());
1375 // Restore savedTInfo into (non-extended) decl info.
1376 DeclInfo = savedTInfo;
1377 }
1378 else
1379 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001380 }
1381 }
1382}
1383
Abramo Bagnara60804e12011-03-18 15:16:37 +00001384void
1385DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1386 unsigned NumTPLists,
1387 TemplateParameterList **TPLists) {
1388 assert(NumTPLists > 0);
1389 // Make sure the extended decl info is allocated.
1390 if (!hasExtInfo()) {
1391 // Save (non-extended) type source info pointer.
1392 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1393 // Allocate external info struct.
1394 DeclInfo = new (getASTContext()) ExtInfo;
1395 // Restore savedTInfo into (extended) decl info.
1396 getExtInfo()->TInfo = savedTInfo;
1397 }
1398 // Set the template parameter lists info.
1399 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1400}
1401
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001402SourceLocation DeclaratorDecl::getOuterLocStart() const {
1403 return getTemplateOrInnerLocStart(this);
1404}
1405
Abramo Bagnaraea947882011-03-08 16:41:52 +00001406namespace {
1407
1408// Helper function: returns true if QT is or contains a type
1409// having a postfix component.
1410bool typeIsPostfix(clang::QualType QT) {
1411 while (true) {
1412 const Type* T = QT.getTypePtr();
1413 switch (T->getTypeClass()) {
1414 default:
1415 return false;
1416 case Type::Pointer:
1417 QT = cast<PointerType>(T)->getPointeeType();
1418 break;
1419 case Type::BlockPointer:
1420 QT = cast<BlockPointerType>(T)->getPointeeType();
1421 break;
1422 case Type::MemberPointer:
1423 QT = cast<MemberPointerType>(T)->getPointeeType();
1424 break;
1425 case Type::LValueReference:
1426 case Type::RValueReference:
1427 QT = cast<ReferenceType>(T)->getPointeeType();
1428 break;
1429 case Type::PackExpansion:
1430 QT = cast<PackExpansionType>(T)->getPattern();
1431 break;
1432 case Type::Paren:
1433 case Type::ConstantArray:
1434 case Type::DependentSizedArray:
1435 case Type::IncompleteArray:
1436 case Type::VariableArray:
1437 case Type::FunctionProto:
1438 case Type::FunctionNoProto:
1439 return true;
1440 }
1441 }
1442}
1443
1444} // namespace
1445
1446SourceRange DeclaratorDecl::getSourceRange() const {
1447 SourceLocation RangeEnd = getLocation();
1448 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1449 if (typeIsPostfix(TInfo->getType()))
1450 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1451 }
1452 return SourceRange(getOuterLocStart(), RangeEnd);
1453}
1454
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001455void
Douglas Gregor20527e22010-06-15 17:44:38 +00001456QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1457 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001458 TemplateParameterList **TPLists) {
1459 assert((NumTPLists == 0 || TPLists != 0) &&
1460 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001461
1462 // Free previous template parameters (if any).
1463 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001464 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001465 TemplParamLists = 0;
1466 NumTemplParamLists = 0;
1467 }
1468 // Set info on matched template parameter lists (if any).
1469 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001470 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001471 NumTemplParamLists = NumTPLists;
1472 for (unsigned i = NumTPLists; i-- > 0; )
1473 TemplParamLists[i] = TPLists[i];
1474 }
1475}
1476
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001477//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001478// VarDecl Implementation
1479//===----------------------------------------------------------------------===//
1480
Sebastian Redl833ef452010-01-26 22:01:41 +00001481const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1482 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001483 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001484 case SC_Auto: return "auto";
1485 case SC_Extern: return "extern";
1486 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1487 case SC_PrivateExtern: return "__private_extern__";
1488 case SC_Register: return "register";
1489 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001490 }
1491
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001492 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001493}
1494
Abramo Bagnaradff19302011-03-08 08:55:46 +00001495VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1496 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001497 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001498 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001499 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001500}
1501
Douglas Gregor72172e92012-01-05 21:55:30 +00001502VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1503 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1504 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1505 QualType(), 0, SC_None, SC_None);
1506}
1507
Douglas Gregorbf62d642010-12-06 18:36:25 +00001508void VarDecl::setStorageClass(StorageClass SC) {
1509 assert(isLegalForVariable(SC));
1510 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00001511 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001512
John McCallbeaa11c2011-05-01 02:13:58 +00001513 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001514}
1515
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001516SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001517 if (const Expr *Init = getInit()) {
1518 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001519 // If Init is implicit, ignore its source range and fallback on
1520 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1521 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001522 return SourceRange(getOuterLocStart(), InitEnd);
1523 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001524 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001525}
1526
Rafael Espindola88510672013-01-04 21:18:45 +00001527template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001528static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001529 // C++ [dcl.link]p1: All function types, function names with external linkage,
1530 // and variable names with external linkage have a language linkage.
1531 if (!isExternalLinkage(D.getLinkage()))
1532 return NoLanguageLinkage;
1533
1534 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001535 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001536 ASTContext &Context = D.getASTContext();
1537 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001538 return CLanguageLinkage;
1539
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001540 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1541 // language linkage of the names of class members and the function type of
1542 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001543 const DeclContext *DC = D.getDeclContext();
1544 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001545 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001546
1547 // If the first decl is in an extern "C" context, any other redeclaration
1548 // will have C language linkage. If the first one is not in an extern "C"
1549 // context, we would have reported an error for any other decl being in one.
Rafael Espindola88510672013-01-04 21:18:45 +00001550 const T *First = D.getFirstDeclaration();
Rafael Espindolaf4187652013-02-14 01:18:37 +00001551 if (First->getDeclContext()->isExternCContext())
1552 return CLanguageLinkage;
1553 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001554}
1555
Rafael Espindolaf4187652013-02-14 01:18:37 +00001556LanguageLinkage VarDecl::getLanguageLinkage() const {
1557 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001558}
1559
Sebastian Redl833ef452010-01-26 22:01:41 +00001560VarDecl *VarDecl::getCanonicalDecl() {
1561 return getFirstDeclaration();
1562}
1563
Daniel Dunbar9d355812012-03-09 01:51:51 +00001564VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1565 ASTContext &C) const
1566{
Sebastian Redl35351a92010-01-31 22:27:38 +00001567 // C++ [basic.def]p2:
1568 // A declaration is a definition unless [...] it contains the 'extern'
1569 // specifier or a linkage-specification and neither an initializer [...],
1570 // it declares a static data member in a class declaration [...].
1571 // C++ [temp.expl.spec]p15:
1572 // An explicit specialization of a static data member of a template is a
1573 // definition if the declaration includes an initializer; otherwise, it is
1574 // a declaration.
1575 if (isStaticDataMember()) {
1576 if (isOutOfLine() && (hasInit() ||
1577 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1578 return Definition;
1579 else
1580 return DeclarationOnly;
1581 }
1582 // C99 6.7p5:
1583 // A definition of an identifier is a declaration for that identifier that
1584 // [...] causes storage to be reserved for that object.
1585 // Note: that applies for all non-file-scope objects.
1586 // C99 6.9.2p1:
1587 // If the declaration of an identifier for an object has file scope and an
1588 // initializer, the declaration is an external definition for the identifier
1589 if (hasInit())
1590 return Definition;
1591 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1592 if (hasExternalStorage())
1593 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001594
John McCall8e7d6562010-08-26 03:08:43 +00001595 if (getStorageClassAsWritten() == SC_Extern ||
1596 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001597 for (const VarDecl *PrevVar = getPreviousDecl();
1598 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Rafael Espindola7581f322012-12-17 22:23:47 +00001599 if (PrevVar->getLinkage() == InternalLinkage)
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001600 return DeclarationOnly;
1601 }
1602 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001603 // C99 6.9.2p2:
1604 // A declaration of an object that has file scope without an initializer,
1605 // and without a storage class specifier or the scs 'static', constitutes
1606 // a tentative definition.
1607 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001608 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001609 return TentativeDefinition;
1610
1611 // What's left is (in C, block-scope) declarations without initializers or
1612 // external storage. These are definitions.
1613 return Definition;
1614}
1615
Sebastian Redl35351a92010-01-31 22:27:38 +00001616VarDecl *VarDecl::getActingDefinition() {
1617 DefinitionKind Kind = isThisDeclarationADefinition();
1618 if (Kind != TentativeDefinition)
1619 return 0;
1620
Chris Lattner48eb14d2010-06-14 18:31:46 +00001621 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001622 VarDecl *First = getFirstDeclaration();
1623 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1624 I != E; ++I) {
1625 Kind = (*I)->isThisDeclarationADefinition();
1626 if (Kind == Definition)
1627 return 0;
1628 else if (Kind == TentativeDefinition)
1629 LastTentative = *I;
1630 }
1631 return LastTentative;
1632}
1633
1634bool VarDecl::isTentativeDefinitionNow() const {
1635 DefinitionKind Kind = isThisDeclarationADefinition();
1636 if (Kind != TentativeDefinition)
1637 return false;
1638
1639 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1640 if ((*I)->isThisDeclarationADefinition() == Definition)
1641 return false;
1642 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001643 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001644}
1645
Daniel Dunbar9d355812012-03-09 01:51:51 +00001646VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001647 VarDecl *First = getFirstDeclaration();
1648 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1649 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001650 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl5ca79842010-02-01 20:16:42 +00001651 return *I;
1652 }
1653 return 0;
1654}
1655
Daniel Dunbar9d355812012-03-09 01:51:51 +00001656VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001657 DefinitionKind Kind = DeclarationOnly;
1658
1659 const VarDecl *First = getFirstDeclaration();
1660 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001661 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001662 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001663 if (Kind == Definition)
1664 break;
1665 }
John McCall37bb6c92010-10-29 22:22:43 +00001666
1667 return Kind;
1668}
1669
Sebastian Redl5ca79842010-02-01 20:16:42 +00001670const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001671 redecl_iterator I = redecls_begin(), E = redecls_end();
1672 while (I != E && !I->getInit())
1673 ++I;
1674
1675 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001676 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001677 return I->getInit();
1678 }
1679 return 0;
1680}
1681
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001682bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001683 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001684 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001685
1686 if (!isStaticDataMember())
1687 return false;
1688
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001689 // If this static data member was instantiated from a static data member of
1690 // a class template, check whether that static data member was defined
1691 // out-of-line.
1692 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1693 return VD->isOutOfLine();
1694
1695 return false;
1696}
1697
Douglas Gregor1d957a32009-10-27 18:42:08 +00001698VarDecl *VarDecl::getOutOfLineDefinition() {
1699 if (!isStaticDataMember())
1700 return 0;
1701
1702 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1703 RD != RDEnd; ++RD) {
1704 if (RD->getLexicalDeclContext()->isFileContext())
1705 return *RD;
1706 }
1707
1708 return 0;
1709}
1710
Douglas Gregord5058122010-02-11 01:19:42 +00001711void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001712 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1713 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001714 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001715 }
1716
1717 Init = I;
1718}
1719
Daniel Dunbar9d355812012-03-09 01:51:51 +00001720bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001721 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001722
Richard Smith35ecb362012-03-02 04:14:40 +00001723 if (!Lang.CPlusPlus)
1724 return false;
1725
1726 // In C++11, any variable of reference type can be used in a constant
1727 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001728 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001729 return true;
1730
1731 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001732 // not require the variable to be non-volatile, but we consider this to be a
1733 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001734 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001735 return false;
1736
1737 // In C++, const, non-volatile variables of integral or enumeration types
1738 // can be used in constant expressions.
1739 if (getType()->isIntegralOrEnumerationType())
1740 return true;
1741
Richard Smith35ecb362012-03-02 04:14:40 +00001742 // Additionally, in C++11, non-volatile constexpr variables can be used in
1743 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001744 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001745}
1746
Richard Smithd0b4dd62011-12-19 06:19:21 +00001747/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1748/// form, which contains extra information on the evaluated value of the
1749/// initializer.
1750EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1751 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1752 if (!Eval) {
1753 Stmt *S = Init.get<Stmt *>();
1754 Eval = new (getASTContext()) EvaluatedStmt;
1755 Eval->Value = S;
1756 Init = Eval;
1757 }
1758 return Eval;
1759}
1760
Richard Smithdafff942012-01-14 04:30:29 +00001761APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001762 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001763 return evaluateValue(Notes);
1764}
1765
1766APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001767 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001768 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1769
1770 // We only produce notes indicating why an initializer is non-constant the
1771 // first time it is evaluated. FIXME: The notes won't always be emitted the
1772 // first time we try evaluation, so might not be produced at all.
1773 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001774 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001775
1776 const Expr *Init = cast<Expr>(Eval->Value);
1777 assert(!Init->isValueDependent());
1778
1779 if (Eval->IsEvaluating) {
1780 // FIXME: Produce a diagnostic for self-initialization.
1781 Eval->CheckedICE = true;
1782 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001783 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001784 }
1785
1786 Eval->IsEvaluating = true;
1787
1788 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1789 this, Notes);
1790
1791 // Ensure the result is an uninitialized APValue if evaluation fails.
1792 if (!Result)
1793 Eval->Evaluated = APValue();
1794
1795 Eval->IsEvaluating = false;
1796 Eval->WasEvaluated = true;
1797
1798 // In C++11, we have determined whether the initializer was a constant
1799 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001800 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001801 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001802 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001803 }
1804
Richard Smithdafff942012-01-14 04:30:29 +00001805 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001806}
1807
1808bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001809 // Initializers of weak variables are never ICEs.
1810 if (isWeak())
1811 return false;
1812
Richard Smithd0b4dd62011-12-19 06:19:21 +00001813 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1814 if (Eval->CheckedICE)
1815 // We have already checked whether this subexpression is an
1816 // integral constant expression.
1817 return Eval->IsICE;
1818
1819 const Expr *Init = cast<Expr>(Eval->Value);
1820 assert(!Init->isValueDependent());
1821
1822 // In C++11, evaluate the initializer to check whether it's a constant
1823 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001824 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001825 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001826 evaluateValue(Notes);
1827 return Eval->IsICE;
1828 }
1829
1830 // It's an ICE whether or not the definition we found is
1831 // out-of-line. See DR 721 and the discussion in Clang PR
1832 // 6206 for details.
1833
1834 if (Eval->CheckingICE)
1835 return false;
1836 Eval->CheckingICE = true;
1837
1838 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1839 Eval->CheckingICE = false;
1840 Eval->CheckedICE = true;
1841 return Eval->IsICE;
1842}
1843
Douglas Gregorfe314812011-06-21 17:03:29 +00001844bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001845 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001846
1847 const Expr *E = getInit();
1848 if (!E)
1849 return false;
1850
1851 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1852 E = Cleanups->getSubExpr();
1853
1854 return isa<MaterializeTemporaryExpr>(E);
1855}
1856
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001857VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001858 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001859 return cast<VarDecl>(MSI->getInstantiatedFrom());
1860
1861 return 0;
1862}
1863
Douglas Gregor3c74d412009-10-14 20:14:33 +00001864TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001865 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001866 return MSI->getTemplateSpecializationKind();
1867
1868 return TSK_Undeclared;
1869}
1870
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001871MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001872 return getASTContext().getInstantiatedFromStaticDataMember(this);
1873}
1874
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001875void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1876 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001877 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001878 assert(MSI && "Not an instantiated static data member?");
1879 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001880 if (TSK != TSK_ExplicitSpecialization &&
1881 PointOfInstantiation.isValid() &&
1882 MSI->getPointOfInstantiation().isInvalid())
1883 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001884}
1885
Sebastian Redl833ef452010-01-26 22:01:41 +00001886//===----------------------------------------------------------------------===//
1887// ParmVarDecl Implementation
1888//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001889
Sebastian Redl833ef452010-01-26 22:01:41 +00001890ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001891 SourceLocation StartLoc,
1892 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001893 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001894 StorageClass S, StorageClass SCAsWritten,
1895 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001896 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001897 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001898}
1899
Douglas Gregor72172e92012-01-05 21:55:30 +00001900ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1901 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1902 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1903 0, QualType(), 0, SC_None, SC_None, 0);
1904}
1905
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001906SourceRange ParmVarDecl::getSourceRange() const {
1907 if (!hasInheritedDefaultArg()) {
1908 SourceRange ArgRange = getDefaultArgRange();
1909 if (ArgRange.isValid())
1910 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1911 }
1912
1913 return DeclaratorDecl::getSourceRange();
1914}
1915
Sebastian Redl833ef452010-01-26 22:01:41 +00001916Expr *ParmVarDecl::getDefaultArg() {
1917 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1918 assert(!hasUninstantiatedDefaultArg() &&
1919 "Default argument is not yet instantiated!");
1920
1921 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001922 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001923 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001924
Sebastian Redl833ef452010-01-26 22:01:41 +00001925 return Arg;
1926}
1927
Sebastian Redl833ef452010-01-26 22:01:41 +00001928SourceRange ParmVarDecl::getDefaultArgRange() const {
1929 if (const Expr *E = getInit())
1930 return E->getSourceRange();
1931
1932 if (hasUninstantiatedDefaultArg())
1933 return getUninstantiatedDefaultArg()->getSourceRange();
1934
1935 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001936}
1937
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001938bool ParmVarDecl::isParameterPack() const {
1939 return isa<PackExpansionType>(getType());
1940}
1941
Ted Kremenek540017e2011-10-06 05:00:56 +00001942void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1943 getASTContext().setParameterIndex(this, parameterIndex);
1944 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1945}
1946
1947unsigned ParmVarDecl::getParameterIndexLarge() const {
1948 return getASTContext().getParameterIndex(this);
1949}
1950
Nuno Lopes394ec982008-12-17 23:39:55 +00001951//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001952// FunctionDecl Implementation
1953//===----------------------------------------------------------------------===//
1954
Benjamin Kramer9170e912013-02-22 15:46:01 +00001955void FunctionDecl::getNameForDiagnostic(
1956 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
1957 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00001958 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1959 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00001960 TemplateSpecializationType::PrintTemplateArgumentList(
1961 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00001962}
1963
Ted Kremenek186a0742010-04-29 16:49:01 +00001964bool FunctionDecl::isVariadic() const {
1965 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1966 return FT->isVariadic();
1967 return false;
1968}
1969
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001970bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1971 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001972 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001973 Definition = *I;
1974 return true;
1975 }
1976 }
1977
1978 return false;
1979}
1980
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001981bool FunctionDecl::hasTrivialBody() const
1982{
1983 Stmt *S = getBody();
1984 if (!S) {
1985 // Since we don't have a body for this function, we don't know if it's
1986 // trivial or not.
1987 return false;
1988 }
1989
1990 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1991 return true;
1992 return false;
1993}
1994
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001995bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1996 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001997 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001998 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1999 return true;
2000 }
2001 }
2002
2003 return false;
2004}
2005
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002006Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00002007 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2008 if (I->Body) {
2009 Definition = *I;
2010 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00002011 } else if (I->IsLateTemplateParsed) {
2012 Definition = *I;
2013 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00002014 }
2015 }
2016
2017 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002018}
2019
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002020void FunctionDecl::setBody(Stmt *B) {
2021 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002022 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002023 EndRangeLoc = B->getLocEnd();
2024}
2025
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002026void FunctionDecl::setPure(bool P) {
2027 IsPure = P;
2028 if (P)
2029 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2030 Parent->markedVirtualFunctionPure();
2031}
2032
Douglas Gregor16618f22009-09-12 00:17:51 +00002033bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002034 const TranslationUnitDecl *tunit =
2035 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2036 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002037 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00002038 getIdentifier() &&
2039 getIdentifier()->isStr("main");
2040}
2041
2042bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2043 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2044 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2045 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2046 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2047 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2048
2049 if (isa<CXXRecordDecl>(getDeclContext())) return false;
2050 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
2051
2052 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2053 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
2054
2055 ASTContext &Context =
2056 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2057 ->getASTContext();
2058
2059 // The result type and first argument type are constant across all
2060 // these operators. The second argument must be exactly void*.
2061 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002062}
2063
Rafael Espindolaf4187652013-02-14 01:18:37 +00002064LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindola6239e052013-01-12 15:27:44 +00002065 // Users expect to be able to write
2066 // extern "C" void *__builtin_alloca (size_t);
2067 // so consider builtins as having C language linkage.
Rafael Espindolac48f7342013-01-12 15:27:43 +00002068 if (getBuiltinID())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002069 return CLanguageLinkage;
Rafael Espindolac48f7342013-01-12 15:27:43 +00002070
Rafael Espindolaf4187652013-02-14 01:18:37 +00002071 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002072}
2073
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002074bool FunctionDecl::isGlobal() const {
2075 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2076 return Method->isStatic();
2077
John McCall8e7d6562010-08-26 03:08:43 +00002078 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002079 return false;
2080
Mike Stump11289f42009-09-09 15:08:12 +00002081 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002082 DC->isNamespace();
2083 DC = DC->getParent()) {
2084 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2085 if (!Namespace->getDeclName())
2086 return false;
2087 break;
2088 }
2089 }
2090
2091 return true;
2092}
2093
Richard Smith10876ef2013-01-17 01:30:42 +00002094bool FunctionDecl::isNoReturn() const {
2095 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002096 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002097 getType()->getAs<FunctionType>()->getNoReturnAttr();
2098}
2099
Sebastian Redl833ef452010-01-26 22:01:41 +00002100void
2101FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2102 redeclarable_base::setPreviousDeclaration(PrevDecl);
2103
2104 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2105 FunctionTemplateDecl *PrevFunTmpl
2106 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2107 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2108 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2109 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002110
Axel Naumannfbc7b982011-11-08 18:21:06 +00002111 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002112 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002113}
2114
2115const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2116 return getFirstDeclaration();
2117}
2118
2119FunctionDecl *FunctionDecl::getCanonicalDecl() {
2120 return getFirstDeclaration();
2121}
2122
Douglas Gregorbf62d642010-12-06 18:36:25 +00002123void FunctionDecl::setStorageClass(StorageClass SC) {
2124 assert(isLegalForFunction(SC));
2125 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00002126 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002127
2128 SClass = SC;
2129}
2130
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002131/// \brief Returns a value indicating whether this function
2132/// corresponds to a builtin function.
2133///
2134/// The function corresponds to a built-in function if it is
2135/// declared at translation scope or within an extern "C" block and
2136/// its name matches with the name of a builtin. The returned value
2137/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002138/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002139/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002140unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002141 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002142 return 0;
2143
2144 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002145 if (!BuiltinID)
2146 return 0;
2147
2148 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00002149 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2150 return BuiltinID;
2151
2152 // This function has the name of a known C library
2153 // function. Determine whether it actually refers to the C library
2154 // function or whether it just has the same name.
2155
Douglas Gregora908e7f2009-02-17 03:23:10 +00002156 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002157 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002158 return 0;
2159
Douglas Gregore711f702009-02-14 18:57:46 +00002160 // If this function is at translation-unit scope and we're not in
2161 // C++, it refers to the C library function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002162 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00002163 getDeclContext()->isTranslationUnit())
2164 return BuiltinID;
2165
2166 // If the function is in an extern "C" linkage specification and is
2167 // not marked "overloadable", it's the real function.
2168 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002169 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00002170 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002171 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00002172 return BuiltinID;
2173
2174 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002175 return 0;
2176}
2177
2178
Chris Lattner47c0d002009-04-25 06:03:53 +00002179/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002180/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002181/// after it has been created.
2182unsigned FunctionDecl::getNumParams() const {
Eli Friedman5c27c4c2012-08-30 22:22:09 +00002183 const FunctionType *FT = getType()->castAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002184 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00002185 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002186 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00002187
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002188}
2189
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002190void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002191 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002192 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002193 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002194
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002195 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002196 if (!NewParamInfo.empty()) {
2197 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2198 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002199 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002200}
Chris Lattner41943152007-01-25 04:52:46 +00002201
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002202void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002203 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2204
2205 if (!NewDecls.empty()) {
2206 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2207 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002208 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002209 }
2210}
2211
Chris Lattner58258242008-04-10 02:22:51 +00002212/// getMinRequiredArguments - Returns the minimum number of arguments
2213/// needed to call this function. This may be fewer than the number of
2214/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002215/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002216unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002217 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002218 return getNumParams();
2219
Douglas Gregor7825bf32011-01-06 22:09:01 +00002220 unsigned NumRequiredArgs = getNumParams();
2221
2222 // If the last parameter is a parameter pack, we don't need an argument for
2223 // it.
2224 if (NumRequiredArgs > 0 &&
2225 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2226 --NumRequiredArgs;
2227
2228 // If this parameter has a default argument, we don't need an argument for
2229 // it.
2230 while (NumRequiredArgs > 0 &&
2231 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002232 --NumRequiredArgs;
2233
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002234 // We might have parameter packs before the end. These can't be deduced,
2235 // but they can still handle multiple arguments.
2236 unsigned ArgIdx = NumRequiredArgs;
2237 while (ArgIdx > 0) {
2238 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2239 NumRequiredArgs = ArgIdx;
2240
2241 --ArgIdx;
2242 }
2243
Chris Lattner58258242008-04-10 02:22:51 +00002244 return NumRequiredArgs;
2245}
2246
Eli Friedman1b125c32012-02-07 03:50:18 +00002247static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2248 // Only consider file-scope declarations in this test.
2249 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2250 return false;
2251
2252 // Only consider explicit declarations; the presence of a builtin for a
2253 // libcall shouldn't affect whether a definition is externally visible.
2254 if (Redecl->isImplicit())
2255 return false;
2256
2257 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2258 return true; // Not an inline definition
2259
2260 return false;
2261}
2262
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002263/// \brief For a function declaration in C or C++, determine whether this
2264/// declaration causes the definition to be externally visible.
2265///
Eli Friedman1b125c32012-02-07 03:50:18 +00002266/// Specifically, this determines if adding the current declaration to the set
2267/// of redeclarations of the given functions causes
2268/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002269bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2270 assert(!doesThisDeclarationHaveABody() &&
2271 "Must have a declaration without a body.");
2272
2273 ASTContext &Context = getASTContext();
2274
David Blaikiebbafb8a2012-03-11 07:00:24 +00002275 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002276 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2277 // an externally visible definition.
2278 //
2279 // FIXME: What happens if gnu_inline gets added on after the first
2280 // declaration?
2281 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
2282 return false;
2283
2284 const FunctionDecl *Prev = this;
2285 bool FoundBody = false;
2286 while ((Prev = Prev->getPreviousDecl())) {
2287 FoundBody |= Prev->Body;
2288
2289 if (Prev->Body) {
2290 // If it's not the case that both 'inline' and 'extern' are
2291 // specified on the definition, then it is always externally visible.
2292 if (!Prev->isInlineSpecified() ||
2293 Prev->getStorageClassAsWritten() != SC_Extern)
2294 return false;
2295 } else if (Prev->isInlineSpecified() &&
2296 Prev->getStorageClassAsWritten() != SC_Extern) {
2297 return false;
2298 }
2299 }
2300 return FoundBody;
2301 }
2302
David Blaikiebbafb8a2012-03-11 07:00:24 +00002303 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002304 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002305
2306 // C99 6.7.4p6:
2307 // [...] If all of the file scope declarations for a function in a
2308 // translation unit include the inline function specifier without extern,
2309 // then the definition in that translation unit is an inline definition.
2310 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002311 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002312 const FunctionDecl *Prev = this;
2313 bool FoundBody = false;
2314 while ((Prev = Prev->getPreviousDecl())) {
2315 FoundBody |= Prev->Body;
2316 if (RedeclForcesDefC99(Prev))
2317 return false;
2318 }
2319 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002320}
2321
Richard Smithf3814ad2013-01-25 00:08:28 +00002322/// \brief For an inline function definition in C, or for a gnu_inline function
2323/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002324///
2325/// Inline function definitions are always available for inlining optimizations.
2326/// However, depending on the language dialect, declaration specifiers, and
2327/// attributes, the definition of an inline function may or may not be
2328/// "externally" visible to other translation units in the program.
2329///
2330/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002331/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002332/// inline definition becomes externally visible (C99 6.7.4p6).
2333///
2334/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2335/// definition, we use the GNU semantics for inline, which are nearly the
2336/// opposite of C99 semantics. In particular, "inline" by itself will create
2337/// an externally visible symbol, but "extern inline" will not create an
2338/// externally visible symbol.
2339bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002340 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002341 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002342 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002343
David Blaikiebbafb8a2012-03-11 07:00:24 +00002344 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002345 // Note: If you change the logic here, please change
2346 // doesDeclarationForceExternallyVisibleDefinition as well.
2347 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002348 // If it's not the case that both 'inline' and 'extern' are
2349 // specified on the definition, then this inline definition is
2350 // externally visible.
2351 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2352 return true;
2353
2354 // If any declaration is 'inline' but not 'extern', then this definition
2355 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002356 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2357 Redecl != RedeclEnd;
2358 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002359 if (Redecl->isInlineSpecified() &&
2360 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002361 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002362 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002363
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002364 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002365 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002366
Richard Smithf3814ad2013-01-25 00:08:28 +00002367 // The rest of this function is C-only.
2368 assert(!Context.getLangOpts().CPlusPlus &&
2369 "should not use C inline rules in C++");
2370
Douglas Gregor299d76e2009-09-13 07:46:26 +00002371 // C99 6.7.4p6:
2372 // [...] If all of the file scope declarations for a function in a
2373 // translation unit include the inline function specifier without extern,
2374 // then the definition in that translation unit is an inline definition.
2375 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2376 Redecl != RedeclEnd;
2377 ++Redecl) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002378 if (RedeclForcesDefC99(*Redecl))
2379 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002380 }
2381
2382 // C99 6.7.4p6:
2383 // An inline definition does not provide an external definition for the
2384 // function, and does not forbid an external definition in another
2385 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002386 return false;
2387}
2388
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002389/// getOverloadedOperator - Which C++ overloaded operator this
2390/// function represents, if any.
2391OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002392 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2393 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002394 else
2395 return OO_None;
2396}
2397
Alexis Huntc88db062010-01-13 09:01:02 +00002398/// getLiteralIdentifier - The literal suffix identifier this function
2399/// represents, if any.
2400const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2401 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2402 return getDeclName().getCXXLiteralIdentifier();
2403 else
2404 return 0;
2405}
2406
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002407FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2408 if (TemplateOrSpecialization.isNull())
2409 return TK_NonTemplate;
2410 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2411 return TK_FunctionTemplate;
2412 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2413 return TK_MemberSpecialization;
2414 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2415 return TK_FunctionTemplateSpecialization;
2416 if (TemplateOrSpecialization.is
2417 <DependentFunctionTemplateSpecializationInfo*>())
2418 return TK_DependentFunctionTemplateSpecialization;
2419
David Blaikie83d382b2011-09-23 05:06:16 +00002420 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002421}
2422
Douglas Gregord801b062009-10-07 23:56:10 +00002423FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002424 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002425 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2426
2427 return 0;
2428}
2429
2430void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002431FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2432 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002433 TemplateSpecializationKind TSK) {
2434 assert(TemplateOrSpecialization.isNull() &&
2435 "Member function is already a specialization");
2436 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002437 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002438 TemplateOrSpecialization = Info;
2439}
2440
Douglas Gregorafca3b42009-10-27 20:53:28 +00002441bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002442 // If the function is invalid, it can't be implicitly instantiated.
2443 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002444 return false;
2445
2446 switch (getTemplateSpecializationKind()) {
2447 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002448 case TSK_ExplicitInstantiationDefinition:
2449 return false;
2450
2451 case TSK_ImplicitInstantiation:
2452 return true;
2453
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002454 // It is possible to instantiate TSK_ExplicitSpecialization kind
2455 // if the FunctionDecl has a class scope specialization pattern.
2456 case TSK_ExplicitSpecialization:
2457 return getClassScopeSpecializationPattern() != 0;
2458
Douglas Gregorafca3b42009-10-27 20:53:28 +00002459 case TSK_ExplicitInstantiationDeclaration:
2460 // Handled below.
2461 break;
2462 }
2463
2464 // Find the actual template from which we will instantiate.
2465 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002466 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002467 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002468 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002469
2470 // C++0x [temp.explicit]p9:
2471 // Except for inline functions, other explicit instantiation declarations
2472 // have the effect of suppressing the implicit instantiation of the entity
2473 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002474 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002475 return true;
2476
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002477 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002478}
2479
2480bool FunctionDecl::isTemplateInstantiation() const {
2481 switch (getTemplateSpecializationKind()) {
2482 case TSK_Undeclared:
2483 case TSK_ExplicitSpecialization:
2484 return false;
2485 case TSK_ImplicitInstantiation:
2486 case TSK_ExplicitInstantiationDeclaration:
2487 case TSK_ExplicitInstantiationDefinition:
2488 return true;
2489 }
2490 llvm_unreachable("All TSK values handled.");
2491}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002492
2493FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002494 // Handle class scope explicit specialization special case.
2495 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2496 return getClassScopeSpecializationPattern();
2497
Douglas Gregorafca3b42009-10-27 20:53:28 +00002498 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2499 while (Primary->getInstantiatedFromMemberTemplate()) {
2500 // If we have hit a point where the user provided a specialization of
2501 // this template, we're done looking.
2502 if (Primary->isMemberSpecialization())
2503 break;
2504
2505 Primary = Primary->getInstantiatedFromMemberTemplate();
2506 }
2507
2508 return Primary->getTemplatedDecl();
2509 }
2510
2511 return getInstantiatedFromMemberFunction();
2512}
2513
Douglas Gregor70d83e22009-06-29 17:30:29 +00002514FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002515 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002516 = TemplateOrSpecialization
2517 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002518 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002519 }
2520 return 0;
2521}
2522
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002523FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2524 return getASTContext().getClassScopeSpecializationPattern(this);
2525}
2526
Douglas Gregor70d83e22009-06-29 17:30:29 +00002527const TemplateArgumentList *
2528FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002529 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002530 = TemplateOrSpecialization
2531 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002532 return Info->TemplateArguments;
2533 }
2534 return 0;
2535}
2536
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002537const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002538FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2539 if (FunctionTemplateSpecializationInfo *Info
2540 = TemplateOrSpecialization
2541 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2542 return Info->TemplateArgumentsAsWritten;
2543 }
2544 return 0;
2545}
2546
Mike Stump11289f42009-09-09 15:08:12 +00002547void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002548FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2549 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002550 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002551 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002552 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002553 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2554 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002555 assert(TSK != TSK_Undeclared &&
2556 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002557 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002558 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002559 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002560 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2561 TemplateArgs,
2562 TemplateArgsAsWritten,
2563 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002564 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002565 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002566}
2567
John McCallb9c78482010-04-08 09:05:18 +00002568void
2569FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2570 const UnresolvedSetImpl &Templates,
2571 const TemplateArgumentListInfo &TemplateArgs) {
2572 assert(TemplateOrSpecialization.isNull());
2573 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2574 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002575 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002576 void *Buffer = Context.Allocate(Size);
2577 DependentFunctionTemplateSpecializationInfo *Info =
2578 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2579 TemplateArgs);
2580 TemplateOrSpecialization = Info;
2581}
2582
2583DependentFunctionTemplateSpecializationInfo::
2584DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2585 const TemplateArgumentListInfo &TArgs)
2586 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2587
2588 d.NumTemplates = Ts.size();
2589 d.NumArgs = TArgs.size();
2590
2591 FunctionTemplateDecl **TsArray =
2592 const_cast<FunctionTemplateDecl**>(getTemplates());
2593 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2594 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2595
2596 TemplateArgumentLoc *ArgsArray =
2597 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2598 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2599 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2600}
2601
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002602TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002603 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002604 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002605 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002606 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002607 if (FTSInfo)
2608 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002609
Douglas Gregord801b062009-10-07 23:56:10 +00002610 MemberSpecializationInfo *MSInfo
2611 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2612 if (MSInfo)
2613 return MSInfo->getTemplateSpecializationKind();
2614
2615 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002616}
2617
Mike Stump11289f42009-09-09 15:08:12 +00002618void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002619FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2620 SourceLocation PointOfInstantiation) {
2621 if (FunctionTemplateSpecializationInfo *FTSInfo
2622 = TemplateOrSpecialization.dyn_cast<
2623 FunctionTemplateSpecializationInfo*>()) {
2624 FTSInfo->setTemplateSpecializationKind(TSK);
2625 if (TSK != TSK_ExplicitSpecialization &&
2626 PointOfInstantiation.isValid() &&
2627 FTSInfo->getPointOfInstantiation().isInvalid())
2628 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2629 } else if (MemberSpecializationInfo *MSInfo
2630 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2631 MSInfo->setTemplateSpecializationKind(TSK);
2632 if (TSK != TSK_ExplicitSpecialization &&
2633 PointOfInstantiation.isValid() &&
2634 MSInfo->getPointOfInstantiation().isInvalid())
2635 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2636 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002637 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002638}
2639
2640SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002641 if (FunctionTemplateSpecializationInfo *FTSInfo
2642 = TemplateOrSpecialization.dyn_cast<
2643 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002644 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002645 else if (MemberSpecializationInfo *MSInfo
2646 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002647 return MSInfo->getPointOfInstantiation();
2648
2649 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002650}
2651
Douglas Gregor6411b922009-09-11 20:15:17 +00002652bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002653 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002654 return true;
2655
2656 // If this function was instantiated from a member function of a
2657 // class template, check whether that member function was defined out-of-line.
2658 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2659 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002660 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002661 return Definition->isOutOfLine();
2662 }
2663
2664 // If this function was instantiated from a function template,
2665 // check whether that function template was defined out-of-line.
2666 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2667 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002668 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002669 return Definition->isOutOfLine();
2670 }
2671
2672 return false;
2673}
2674
Abramo Bagnaraea947882011-03-08 16:41:52 +00002675SourceRange FunctionDecl::getSourceRange() const {
2676 return SourceRange(getOuterLocStart(), EndRangeLoc);
2677}
2678
Anna Zaks28db7ce2012-01-18 02:45:01 +00002679unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002680 IdentifierInfo *FnInfo = getIdentifier();
2681
2682 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002683 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002684
2685 // Builtin handling.
2686 switch (getBuiltinID()) {
2687 case Builtin::BI__builtin_memset:
2688 case Builtin::BI__builtin___memset_chk:
2689 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002690 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002691
2692 case Builtin::BI__builtin_memcpy:
2693 case Builtin::BI__builtin___memcpy_chk:
2694 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002695 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002696
2697 case Builtin::BI__builtin_memmove:
2698 case Builtin::BI__builtin___memmove_chk:
2699 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002700 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002701
2702 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002703 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002704 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002705 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002706
2707 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002708 case Builtin::BImemcmp:
2709 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002710
2711 case Builtin::BI__builtin_strncpy:
2712 case Builtin::BI__builtin___strncpy_chk:
2713 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002714 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002715
2716 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002717 case Builtin::BIstrncmp:
2718 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002719
2720 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002721 case Builtin::BIstrncasecmp:
2722 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002723
2724 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002725 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002726 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002727 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002728
2729 case Builtin::BI__builtin_strndup:
2730 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002731 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002732
Anna Zaks314cd092012-02-01 19:08:57 +00002733 case Builtin::BI__builtin_strlen:
2734 case Builtin::BIstrlen:
2735 return Builtin::BIstrlen;
2736
Anna Zaks201d4892012-01-13 21:52:01 +00002737 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002738 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002739 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002740 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002741 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002742 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002743 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002744 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002745 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002746 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002747 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002748 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002749 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002750 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002751 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002752 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002753 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002754 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002755 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002756 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002757 else if (FnInfo->isStr("strlen"))
2758 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002759 }
2760 break;
2761 }
Anna Zaks22122702012-01-17 00:37:07 +00002762 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002763}
2764
Chris Lattner59a25942008-03-31 00:36:02 +00002765//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002766// FieldDecl Implementation
2767//===----------------------------------------------------------------------===//
2768
Jay Foad39c79802011-01-12 09:06:06 +00002769FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002770 SourceLocation StartLoc, SourceLocation IdLoc,
2771 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002772 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00002773 InClassInitStyle InitStyle) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002774 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +00002775 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00002776}
2777
Douglas Gregor72172e92012-01-05 21:55:30 +00002778FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2779 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2780 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
Richard Smith2b013182012-06-10 03:12:00 +00002781 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00002782}
2783
Sebastian Redl833ef452010-01-26 22:01:41 +00002784bool FieldDecl::isAnonymousStructOrUnion() const {
2785 if (!isImplicit() || getDeclName())
2786 return false;
2787
2788 if (const RecordType *Record = getType()->getAs<RecordType>())
2789 return Record->getDecl()->isAnonymousStructOrUnion();
2790
2791 return false;
2792}
2793
Richard Smithcaf33902011-10-10 18:28:20 +00002794unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2795 assert(isBitField() && "not a bitfield");
2796 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2797 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2798}
2799
John McCall4e819612011-01-20 07:57:12 +00002800unsigned FieldDecl::getFieldIndex() const {
2801 if (CachedFieldIndex) return CachedFieldIndex - 1;
2802
Richard Smithd62306a2011-11-10 06:34:14 +00002803 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002804 const RecordDecl *RD = getParent();
2805 const FieldDecl *LastFD = 0;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002806 bool IsMsStruct = RD->isMsStruct(getASTContext());
Richard Smithd62306a2011-11-10 06:34:14 +00002807
2808 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2809 I != E; ++I, ++Index) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00002810 I->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002811
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002812 if (IsMsStruct) {
2813 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie40ed2972012-06-06 20:45:41 +00002814 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002815 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002816 continue;
2817 }
David Blaikie40ed2972012-06-06 20:45:41 +00002818 LastFD = *I;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002819 }
John McCall4e819612011-01-20 07:57:12 +00002820 }
2821
Richard Smithd62306a2011-11-10 06:34:14 +00002822 assert(CachedFieldIndex && "failed to find field in parent");
2823 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002824}
2825
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002826SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002827 if (const Expr *E = InitializerOrBitWidth.getPointer())
2828 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002829 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002830}
2831
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00002832void FieldDecl::setBitWidth(Expr *Width) {
2833 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2834 "bit width or initializer already set");
2835 InitializerOrBitWidth.setPointer(Width);
2836}
2837
Richard Smith938f40b2011-06-11 17:19:42 +00002838void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00002839 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00002840 "bit width or initializer already set");
2841 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002842}
2843
Sebastian Redl833ef452010-01-26 22:01:41 +00002844//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002845// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002846//===----------------------------------------------------------------------===//
2847
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002848SourceLocation TagDecl::getOuterLocStart() const {
2849 return getTemplateOrInnerLocStart(this);
2850}
2851
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002852SourceRange TagDecl::getSourceRange() const {
2853 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002854 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002855}
2856
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002857TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002858 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002859}
2860
Richard Smithdda56e42011-04-15 14:24:37 +00002861void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2862 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002863 if (TypeForDecl)
Rafael Espindola19de5612013-01-12 06:42:30 +00002864 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2865 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002866}
2867
Douglas Gregordee1be82009-01-17 00:42:38 +00002868void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002869 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002870
David Blaikie095deba2012-11-14 01:52:05 +00002871 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00002872 struct CXXRecordDecl::DefinitionData *Data =
2873 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002874 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2875 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002876 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002877}
2878
2879void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002880 assert((!isa<CXXRecordDecl>(this) ||
2881 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2882 "definition completed but not started");
2883
John McCallf937c022011-10-07 06:10:15 +00002884 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002885 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002886
2887 if (ASTMutationListener *L = getASTMutationListener())
2888 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002889}
2890
John McCallf937c022011-10-07 06:10:15 +00002891TagDecl *TagDecl::getDefinition() const {
2892 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002893 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002894
2895 // If it's possible for us to have an out-of-date definition, check now.
2896 if (MayHaveOutOfDateDef) {
2897 if (IdentifierInfo *II = getIdentifier()) {
2898 if (II->isOutOfDate()) {
2899 updateOutOfDate(*II);
2900 }
2901 }
2902 }
2903
Andrew Trickba266ee2010-10-19 21:54:32 +00002904 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2905 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002906
2907 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002908 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002909 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002910 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002911
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002912 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002913}
2914
Douglas Gregor14454802011-02-25 02:25:35 +00002915void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2916 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002917 // Make sure the extended qualifier info is allocated.
2918 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002919 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002920 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002921 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002922 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002923 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002924 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002925 if (getExtInfo()->NumTemplParamLists == 0) {
2926 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002927 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002928 }
2929 else
2930 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002931 }
2932 }
2933}
2934
Abramo Bagnara60804e12011-03-18 15:16:37 +00002935void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2936 unsigned NumTPLists,
2937 TemplateParameterList **TPLists) {
2938 assert(NumTPLists > 0);
2939 // Make sure the extended decl info is allocated.
2940 if (!hasExtInfo())
2941 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002942 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002943 // Set the template parameter lists info.
2944 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2945}
2946
Ted Kremenek21475702008-09-05 17:16:31 +00002947//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002948// EnumDecl Implementation
2949//===----------------------------------------------------------------------===//
2950
David Blaikie68e081d2011-12-20 02:48:34 +00002951void EnumDecl::anchor() { }
2952
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002953EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2954 SourceLocation StartLoc, SourceLocation IdLoc,
2955 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002956 EnumDecl *PrevDecl, bool IsScoped,
2957 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002958 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002959 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002960 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00002961 C.getTypeDeclType(Enum, PrevDecl);
2962 return Enum;
2963}
2964
Douglas Gregor72172e92012-01-05 21:55:30 +00002965EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2966 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002967 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2968 0, 0, false, false, false);
2969 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2970 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002971}
2972
Douglas Gregord5058122010-02-11 01:19:42 +00002973void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002974 QualType NewPromotionType,
2975 unsigned NumPositiveBits,
2976 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002977 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002978 if (!IntegerType)
2979 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002980 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002981 setNumPositiveBits(NumPositiveBits);
2982 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002983 TagDecl::completeDefinition();
2984}
2985
Richard Smith7d137e32012-03-23 03:33:32 +00002986TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2987 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2988 return MSI->getTemplateSpecializationKind();
2989
2990 return TSK_Undeclared;
2991}
2992
2993void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2994 SourceLocation PointOfInstantiation) {
2995 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2996 assert(MSI && "Not an instantiated member enumeration?");
2997 MSI->setTemplateSpecializationKind(TSK);
2998 if (TSK != TSK_ExplicitSpecialization &&
2999 PointOfInstantiation.isValid() &&
3000 MSI->getPointOfInstantiation().isInvalid())
3001 MSI->setPointOfInstantiation(PointOfInstantiation);
3002}
3003
Richard Smith4b38ded2012-03-14 23:13:10 +00003004EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3005 if (SpecializationInfo)
3006 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3007
3008 return 0;
3009}
3010
3011void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3012 TemplateSpecializationKind TSK) {
3013 assert(!SpecializationInfo && "Member enum is already a specialization");
3014 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3015}
3016
Sebastian Redl833ef452010-01-26 22:01:41 +00003017//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003018// RecordDecl Implementation
3019//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003020
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003021RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3022 SourceLocation StartLoc, SourceLocation IdLoc,
3023 IdentifierInfo *Id, RecordDecl *PrevDecl)
3024 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003025 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003026 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003027 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003028 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003029 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003030 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003031}
3032
Jay Foad39c79802011-01-12 09:06:06 +00003033RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003034 SourceLocation StartLoc, SourceLocation IdLoc,
3035 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3036 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3037 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003038 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3039
Ted Kremenek21475702008-09-05 17:16:31 +00003040 C.getTypeDeclType(R, PrevDecl);
3041 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003042}
3043
Douglas Gregor72172e92012-01-05 21:55:30 +00003044RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3045 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003046 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3047 SourceLocation(), 0, 0);
3048 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3049 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003050}
3051
Douglas Gregordfcad112009-03-25 15:59:44 +00003052bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003053 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003054 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3055}
3056
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003057RecordDecl::field_iterator RecordDecl::field_begin() const {
3058 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3059 LoadFieldsFromExternalStorage();
3060
3061 return field_iterator(decl_iterator(FirstDecl));
3062}
3063
Douglas Gregorb11aad82011-02-19 18:51:44 +00003064/// completeDefinition - Notes that the definition of this type is now
3065/// complete.
3066void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003067 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003068 TagDecl::completeDefinition();
3069}
3070
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003071/// isMsStruct - Get whether or not this record uses ms_struct layout.
3072/// This which can be turned on with an attribute, pragma, or the
3073/// -mms-bitfields command-line option.
3074bool RecordDecl::isMsStruct(const ASTContext &C) const {
3075 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3076}
3077
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003078static bool isFieldOrIndirectField(Decl::Kind K) {
3079 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3080}
3081
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003082void RecordDecl::LoadFieldsFromExternalStorage() const {
3083 ExternalASTSource *Source = getASTContext().getExternalSource();
3084 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3085
3086 // Notify that we have a RecordDecl doing some initialization.
3087 ExternalASTSource::Deserializing TheFields(Source);
3088
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003089 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003090 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003091 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3092 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003093 case ELR_Success:
3094 break;
3095
3096 case ELR_AlreadyLoaded:
3097 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003098 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003099 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003100
3101#ifndef NDEBUG
3102 // Check that all decls we got were FieldDecls.
3103 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003104 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003105#endif
3106
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003107 if (Decls.empty())
3108 return;
3109
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003110 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3111 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003112}
3113
Steve Naroff415d3d52008-10-08 17:01:13 +00003114//===----------------------------------------------------------------------===//
3115// BlockDecl Implementation
3116//===----------------------------------------------------------------------===//
3117
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003118void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003119 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003120
Steve Naroffc4b30e52009-03-13 16:56:44 +00003121 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003122 if (!NewParamInfo.empty()) {
3123 NumParams = NewParamInfo.size();
3124 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3125 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003126 }
3127}
3128
John McCall351762c2011-02-07 10:33:21 +00003129void BlockDecl::setCaptures(ASTContext &Context,
3130 const Capture *begin,
3131 const Capture *end,
3132 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003133 CapturesCXXThis = capturesCXXThis;
3134
3135 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003136 NumCaptures = 0;
3137 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003138 return;
3139 }
3140
John McCall351762c2011-02-07 10:33:21 +00003141 NumCaptures = end - begin;
3142
3143 // Avoid new Capture[] because we don't want to provide a default
3144 // constructor.
3145 size_t allocationSize = NumCaptures * sizeof(Capture);
3146 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3147 memcpy(buffer, begin, allocationSize);
3148 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003149}
Sebastian Redl833ef452010-01-26 22:01:41 +00003150
John McCallce45f882011-06-15 22:51:16 +00003151bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3152 for (capture_const_iterator
3153 i = capture_begin(), e = capture_end(); i != e; ++i)
3154 // Only auto vars can be captured, so no redeclaration worries.
3155 if (i->getVariable() == variable)
3156 return true;
3157
3158 return false;
3159}
3160
Douglas Gregor70226da2010-12-21 16:27:07 +00003161SourceRange BlockDecl::getSourceRange() const {
3162 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3163}
Sebastian Redl833ef452010-01-26 22:01:41 +00003164
3165//===----------------------------------------------------------------------===//
3166// Other Decl Allocation/Deallocation Method Implementations
3167//===----------------------------------------------------------------------===//
3168
David Blaikie68e081d2011-12-20 02:48:34 +00003169void TranslationUnitDecl::anchor() { }
3170
Sebastian Redl833ef452010-01-26 22:01:41 +00003171TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3172 return new (C) TranslationUnitDecl(C);
3173}
3174
David Blaikie68e081d2011-12-20 02:48:34 +00003175void LabelDecl::anchor() { }
3176
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003177LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003178 SourceLocation IdentL, IdentifierInfo *II) {
3179 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3180}
3181
3182LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3183 SourceLocation IdentL, IdentifierInfo *II,
3184 SourceLocation GnuLabelL) {
3185 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3186 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003187}
3188
Douglas Gregor72172e92012-01-05 21:55:30 +00003189LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3190 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3191 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003192}
3193
David Blaikie68e081d2011-12-20 02:48:34 +00003194void ValueDecl::anchor() { }
3195
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003196bool ValueDecl::isWeak() const {
3197 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3198 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3199 return true;
3200
3201 return isWeakImported();
3202}
3203
David Blaikie68e081d2011-12-20 02:48:34 +00003204void ImplicitParamDecl::anchor() { }
3205
Sebastian Redl833ef452010-01-26 22:01:41 +00003206ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003207 SourceLocation IdLoc,
3208 IdentifierInfo *Id,
3209 QualType Type) {
3210 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003211}
3212
Douglas Gregor72172e92012-01-05 21:55:30 +00003213ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3214 unsigned ID) {
3215 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3216 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3217}
3218
Sebastian Redl833ef452010-01-26 22:01:41 +00003219FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003220 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003221 const DeclarationNameInfo &NameInfo,
3222 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003223 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00003224 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003225 bool hasWrittenPrototype,
3226 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003227 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3228 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00003229 isInlineSpecified,
3230 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003231 New->HasWrittenPrototype = hasWrittenPrototype;
3232 return New;
3233}
3234
Douglas Gregor72172e92012-01-05 21:55:30 +00003235FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3236 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3237 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3238 DeclarationNameInfo(), QualType(), 0,
3239 SC_None, SC_None, false, false);
3240}
3241
Sebastian Redl833ef452010-01-26 22:01:41 +00003242BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3243 return new (C) BlockDecl(DC, L);
3244}
3245
Douglas Gregor72172e92012-01-05 21:55:30 +00003246BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3247 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3248 return new (Mem) BlockDecl(0, SourceLocation());
3249}
3250
Sebastian Redl833ef452010-01-26 22:01:41 +00003251EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3252 SourceLocation L,
3253 IdentifierInfo *Id, QualType T,
3254 Expr *E, const llvm::APSInt &V) {
3255 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3256}
3257
Douglas Gregor72172e92012-01-05 21:55:30 +00003258EnumConstantDecl *
3259EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3260 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3261 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3262 llvm::APSInt());
3263}
3264
David Blaikie68e081d2011-12-20 02:48:34 +00003265void IndirectFieldDecl::anchor() { }
3266
Benjamin Kramer39593702010-11-21 14:11:41 +00003267IndirectFieldDecl *
3268IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3269 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3270 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00003271 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3272}
3273
Douglas Gregor72172e92012-01-05 21:55:30 +00003274IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3275 unsigned ID) {
3276 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3277 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3278 QualType(), 0, 0);
3279}
3280
Douglas Gregorbe996932010-09-01 20:41:53 +00003281SourceRange EnumConstantDecl::getSourceRange() const {
3282 SourceLocation End = getLocation();
3283 if (Init)
3284 End = Init->getLocEnd();
3285 return SourceRange(getLocation(), End);
3286}
3287
David Blaikie68e081d2011-12-20 02:48:34 +00003288void TypeDecl::anchor() { }
3289
Sebastian Redl833ef452010-01-26 22:01:41 +00003290TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003291 SourceLocation StartLoc, SourceLocation IdLoc,
3292 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3293 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003294}
3295
David Blaikie68e081d2011-12-20 02:48:34 +00003296void TypedefNameDecl::anchor() { }
3297
Douglas Gregor72172e92012-01-05 21:55:30 +00003298TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3299 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3300 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3301}
3302
Richard Smithdda56e42011-04-15 14:24:37 +00003303TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3304 SourceLocation StartLoc,
3305 SourceLocation IdLoc, IdentifierInfo *Id,
3306 TypeSourceInfo *TInfo) {
3307 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3308}
3309
Douglas Gregor72172e92012-01-05 21:55:30 +00003310TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3311 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3312 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3313}
3314
Abramo Bagnaraea947882011-03-08 16:41:52 +00003315SourceRange TypedefDecl::getSourceRange() const {
3316 SourceLocation RangeEnd = getLocation();
3317 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3318 if (typeIsPostfix(TInfo->getType()))
3319 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3320 }
3321 return SourceRange(getLocStart(), RangeEnd);
3322}
3323
Richard Smithdda56e42011-04-15 14:24:37 +00003324SourceRange TypeAliasDecl::getSourceRange() const {
3325 SourceLocation RangeEnd = getLocStart();
3326 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3327 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3328 return SourceRange(getLocStart(), RangeEnd);
3329}
3330
David Blaikie68e081d2011-12-20 02:48:34 +00003331void FileScopeAsmDecl::anchor() { }
3332
Sebastian Redl833ef452010-01-26 22:01:41 +00003333FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003334 StringLiteral *Str,
3335 SourceLocation AsmLoc,
3336 SourceLocation RParenLoc) {
3337 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003338}
Douglas Gregorba345522011-12-02 23:23:56 +00003339
Douglas Gregor72172e92012-01-05 21:55:30 +00003340FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3341 unsigned ID) {
3342 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3343 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3344}
3345
Douglas Gregorba345522011-12-02 23:23:56 +00003346//===----------------------------------------------------------------------===//
3347// ImportDecl Implementation
3348//===----------------------------------------------------------------------===//
3349
3350/// \brief Retrieve the number of module identifiers needed to name the given
3351/// module.
3352static unsigned getNumModuleIdentifiers(Module *Mod) {
3353 unsigned Result = 1;
3354 while (Mod->Parent) {
3355 Mod = Mod->Parent;
3356 ++Result;
3357 }
3358 return Result;
3359}
3360
Douglas Gregor22d09742012-01-03 18:04:46 +00003361ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003362 Module *Imported,
3363 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003364 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003365 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003366{
3367 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3368 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3369 memcpy(StoredLocs, IdentifierLocs.data(),
3370 IdentifierLocs.size() * sizeof(SourceLocation));
3371}
3372
Douglas Gregor22d09742012-01-03 18:04:46 +00003373ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003374 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003375 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003376 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003377{
3378 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3379}
3380
3381ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003382 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003383 ArrayRef<SourceLocation> IdentifierLocs) {
3384 void *Mem = C.Allocate(sizeof(ImportDecl) +
3385 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003386 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003387}
3388
3389ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003390 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003391 Module *Imported,
3392 SourceLocation EndLoc) {
3393 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003394 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003395 Import->setImplicit();
3396 return Import;
3397}
3398
Douglas Gregor72172e92012-01-05 21:55:30 +00003399ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3400 unsigned NumLocations) {
3401 void *Mem = AllocateDeserializedDecl(C, ID,
3402 (sizeof(ImportDecl) +
3403 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00003404 return new (Mem) ImportDecl(EmptyShell());
3405}
3406
3407ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3408 if (!ImportedAndComplete.getInt())
3409 return ArrayRef<SourceLocation>();
3410
3411 const SourceLocation *StoredLocs
3412 = reinterpret_cast<const SourceLocation *>(this + 1);
3413 return ArrayRef<SourceLocation>(StoredLocs,
3414 getNumModuleIdentifiers(getImportedModule()));
3415}
3416
3417SourceRange ImportDecl::getSourceRange() const {
3418 if (!ImportedAndComplete.getInt())
3419 return SourceRange(getLocation(),
3420 *reinterpret_cast<const SourceLocation *>(this + 1));
3421
3422 return SourceRange(getLocation(), getIdentifierLocs().back());
3423}