blob: 1a8748ccfd0bf47c04ef93410082019d50c99d9b [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"
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Richard Smith0b87e072013-10-07 08:02:11 +000036Decl *clang::getPrimaryMergedDecl(Decl *D) {
37 return D->getASTContext().getPrimaryMergedDecl(D);
38}
39
Chris Lattner88f70d62008-03-15 05:43:15 +000040//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000041// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000042//===----------------------------------------------------------------------===//
43
John McCalldf25c432013-02-16 00:17:33 +000044// Visibility rules aren't rigorously externally specified, but here
45// are the basic principles behind what we implement:
46//
47// 1. An explicit visibility attribute is generally a direct expression
48// of the user's intent and should be honored. Only the innermost
49// visibility attribute applies. If no visibility attribute applies,
50// global visibility settings are considered.
51//
52// 2. There is one caveat to the above: on or in a template pattern,
53// an explicit visibility attribute is just a default rule, and
54// visibility can be decreased by the visibility of template
55// arguments. But this, too, has an exception: an attribute on an
56// explicit specialization or instantiation causes all the visibility
57// restrictions of the template arguments to be ignored.
58//
59// 3. A variable that does not otherwise have explicit visibility can
60// be restricted by the visibility of its type.
61//
62// 4. A visibility restriction is explicit if it comes from an
63// attribute (or something like it), not a global visibility setting.
64// When emitting a reference to an external symbol, visibility
65// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000066//
67// 5. When computing the visibility of a non-type, including a
68// non-type member of a class, only non-type visibility restrictions
69// are considered: the 'visibility' attribute, global value-visibility
70// settings, and a few special cases like __private_extern.
71//
72// 6. When computing the visibility of a type, including a type member
73// of a class, only type visibility restrictions are considered:
74// the 'type_visibility' attribute and global type-visibility settings.
75// However, a 'visibility' attribute counts as a 'type_visibility'
76// attribute on any declaration that only has the former.
77//
78// The visibility of a "secondary" entity, like a template argument,
79// is computed using the kind of that entity, not the kind of the
80// primary entity for which we are computing visibility. For example,
81// the visibility of a specialization of either of these templates:
82// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
83// template <class T, bool (&compare)(T, X)> class matcher;
84// is restricted according to the type visibility of the argument 'T',
85// the type visibility of 'bool(&)(T,X)', and the value visibility of
86// the argument function 'compare'. That 'has_match' is a value
87// and 'matcher' is a type only matters when looking for attributes
88// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +000089
John McCall5f46c482013-02-21 23:42:58 +000090const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +000091const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +000092
John McCalldf25c432013-02-16 00:17:33 +000093/// Kinds of LV computation. The linkage side of the computation is
94/// always the same, but different things can change how visibility is
95/// computed.
96enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +000097 /// Do an LV computation for, ultimately, a type.
98 /// Visibility may be restricted by type visibility settings and
99 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000100 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000101
John McCall5f46c482013-02-21 23:42:58 +0000102 /// Do an LV computation for, ultimately, a non-type declaration.
103 /// Visibility may be restricted by value visibility settings and
104 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000105 LVForValue = NamedDecl::VisibilityForValue,
106
John McCall5f46c482013-02-21 23:42:58 +0000107 /// Do an LV computation for, ultimately, a type that already has
108 /// some sort of explicit visibility. Visibility may only be
109 /// restricted by the visibility of template arguments.
110 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000111
John McCall5f46c482013-02-21 23:42:58 +0000112 /// Do an LV computation for, ultimately, a non-type declaration
113 /// that already has some sort of explicit visibility. Visibility
114 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000115 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
116
117 /// Do an LV computation when we only care about the linkage.
118 LVForLinkageOnly =
119 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000120};
121
John McCalld041a9b2013-02-20 01:54:26 +0000122/// Does this computation kind permit us to consider additional
123/// visibility settings from attributes and the like?
124static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000125 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000126}
127
128/// Given an LVComputationKind, return one of the same type/value sort
129/// that records that it already has explicit visibility.
130static LVComputationKind
131withExplicitVisibilityAlready(LVComputationKind oldKind) {
132 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000133 static_cast<LVComputationKind>(unsigned(oldKind) |
134 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000135 assert(oldKind != LVForType || newKind == LVForExplicitType);
136 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
137 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
138 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
139 return newKind;
140}
141
David Blaikie05785d12013-02-20 22:23:23 +0000142static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
143 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000144 assert(!hasExplicitVisibilityAlready(kind) &&
145 "asking for explicit visibility when we shouldn't be");
146 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
147}
148
John McCalldf25c432013-02-16 00:17:33 +0000149/// Is the given declaration a "type" or a "value" for the purposes of
150/// visibility computation?
151static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000152 return isa<TypeDecl>(D) ||
153 isa<ClassTemplateDecl>(D) ||
154 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000155}
156
John McCall5f46c482013-02-21 23:42:58 +0000157/// Does the given declaration have member specialization information,
158/// and if so, is it an explicit specialization?
159template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000160std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000161isExplicitMemberSpecialization(const T *D) {
162 if (const MemberSpecializationInfo *member =
163 D->getMemberSpecializationInfo()) {
164 return member->isExplicitSpecialization();
165 }
166 return false;
167}
168
169/// For templates, this question is easier: a member template can't be
170/// explicitly instantiated, so there's a single bit indicating whether
171/// or not this is an explicit member specialization.
172static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
173 return D->isMemberSpecialization();
174}
175
John McCalld041a9b2013-02-20 01:54:26 +0000176/// Given a visibility attribute, return the explicit visibility
177/// associated with it.
178template <class T>
179static Visibility getVisibilityFromAttr(const T *attr) {
180 switch (attr->getVisibility()) {
181 case T::Default:
182 return DefaultVisibility;
183 case T::Hidden:
184 return HiddenVisibility;
185 case T::Protected:
186 return ProtectedVisibility;
187 }
188 llvm_unreachable("bad visibility kind");
189}
190
John McCalldf25c432013-02-16 00:17:33 +0000191/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000192static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000193 NamedDecl::ExplicitVisibilityKind kind) {
194 // If we're ultimately computing the visibility of a type, look for
195 // a 'type_visibility' attribute before looking for 'visibility'.
196 if (kind == NamedDecl::VisibilityForType) {
197 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
198 return getVisibilityFromAttr(A);
199 }
200 }
201
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000202 // If this declaration has an explicit visibility attribute, use it.
203 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000204 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000205 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000206
207 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
208 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000209 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000210 for (specific_attr_iterator<AvailabilityAttr>
211 A = D->specific_attr_begin<AvailabilityAttr>(),
212 AEnd = D->specific_attr_end<AvailabilityAttr>();
213 A != AEnd; ++A)
214 if ((*A)->getPlatform()->getName().equals("macosx"))
215 return DefaultVisibility;
216 }
217
David Blaikie7a30dc52013-02-21 01:47:18 +0000218 return None;
John McCall457a04e2010-10-22 21:05:15 +0000219}
220
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000221static LinkageInfo
222getLVForType(const Type &T, LVComputationKind computation) {
223 if (computation == LVForLinkageOnly)
224 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
225 return T.getLinkageAndVisibility();
226}
227
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000228/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000229/// template parameter list. For visibility purposes, template
230/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000231static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000232getLVForTemplateParameterList(const TemplateParameterList *params,
233 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000234 LinkageInfo LV;
235 for (TemplateParameterList::const_iterator P = params->begin(),
236 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000237 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000238
239 // Template type parameters are the most common and never
240 // contribute to visibility, pack or not.
241 if (isa<TemplateTypeParmDecl>(*P))
242 continue;
243
244 // Non-type template parameters can be restricted by the value type, e.g.
245 // template <enum X> class A { ... };
246 // We have to be careful here, though, because we can be dealing with
247 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000248 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000249 // Handle the non-pack case first.
250 if (!NTTP->isExpandedParameterPack()) {
251 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000252 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000253 }
254 continue;
255 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000256
John McCalldf25c432013-02-16 00:17:33 +0000257 // Look at all the types in an expanded pack.
258 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
259 QualType type = NTTP->getExpansionType(i);
260 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000261 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000262 }
John McCalldf25c432013-02-16 00:17:33 +0000263 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000264 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000265
John McCalldf25c432013-02-16 00:17:33 +0000266 // Template template parameters can be restricted by their
267 // template parameters, recursively.
268 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
269
270 // Handle the non-pack case first.
271 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000272 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
273 computation));
John McCalldf25c432013-02-16 00:17:33 +0000274 continue;
275 }
276
277 // Look at all expansions in an expanded pack.
278 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
279 i != n; ++i) {
280 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000281 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000282 }
283 }
284
John McCall457a04e2010-10-22 21:05:15 +0000285 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000286}
287
Rafael Espindola19de5612013-01-12 06:42:30 +0000288/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000289static LinkageInfo getLVForDecl(const NamedDecl *D,
290 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000291
Eli Friedman7e346a82013-07-01 20:22:57 +0000292static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
293 const Decl *Ret = NULL;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000294 const DeclContext *DC = D->getDeclContext();
295 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000296 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
297 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000298 DC = DC->getParent();
299 }
300 return Ret;
301}
302
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000303/// \brief Get the most restrictive linkage for the types and
304/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000305///
306/// Note that we don't take an LVComputationKind because we always
307/// want to honor the visibility of template arguments in the same way.
308static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000309getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args,
310 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000311 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000312
John McCalldf25c432013-02-16 00:17:33 +0000313 for (unsigned i = 0, e = args.size(); i != e; ++i) {
314 const TemplateArgument &arg = args[i];
315 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000316 case TemplateArgument::Null:
317 case TemplateArgument::Integral:
318 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000319 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000320
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321 case TemplateArgument::Type:
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000322 LV.merge(getLVForType(*arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000323 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000324
325 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000326 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
327 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000328 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000329 }
330 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000331
332 case TemplateArgument::NullPtr:
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000333 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000334 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000335
336 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000337 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000338 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000339 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000340 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000341 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000342
343 case TemplateArgument::Pack:
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000344 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000345 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000346 }
John McCalldf25c432013-02-16 00:17:33 +0000347 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000348 }
349
John McCall457a04e2010-10-22 21:05:15 +0000350 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351}
352
Rafael Espindola2f869a32012-01-14 00:30:36 +0000353static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000354getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
355 LVComputationKind computation) {
356 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000357}
358
John McCall5f46c482013-02-21 23:42:58 +0000359static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
360 const FunctionTemplateSpecializationInfo *specInfo) {
361 // Include visibility from the template parameters and arguments
362 // only if this is not an explicit instantiation or specialization
363 // with direct explicit visibility. (Implicit instantiations won't
364 // have a direct attribute.)
365 if (!specInfo->isExplicitInstantiationOrSpecialization())
366 return true;
367
368 return !fn->hasAttr<VisibilityAttr>();
369}
370
John McCalldf25c432013-02-16 00:17:33 +0000371/// Merge in template-related linkage and visibility for the given
372/// function template specialization.
373///
374/// We don't need a computation kind here because we can assume
375/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000376///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000377/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000378static void
379mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000380 const FunctionTemplateSpecializationInfo *specInfo,
381 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000382 bool considerVisibility =
383 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000384
385 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000386 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000387 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000388 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000389 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
390
391 // Merge information from the template arguments.
392 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000393 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000394 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000395}
396
John McCall5f46c482013-02-21 23:42:58 +0000397/// Does the given declaration have a direct visibility attribute
398/// that would match the given rules?
399static bool hasDirectVisibilityAttribute(const NamedDecl *D,
400 LVComputationKind computation) {
401 switch (computation) {
402 case LVForType:
403 case LVForExplicitType:
404 if (D->hasAttr<TypeVisibilityAttr>())
405 return true;
406 // fallthrough
407 case LVForValue:
408 case LVForExplicitValue:
409 if (D->hasAttr<VisibilityAttr>())
410 return true;
411 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000412 case LVForLinkageOnly:
413 return false;
John McCall5f46c482013-02-21 23:42:58 +0000414 }
415 llvm_unreachable("bad visibility computation kind");
416}
417
John McCalld041a9b2013-02-20 01:54:26 +0000418/// Should we consider visibility associated with the template
419/// arguments and parameters of the given class template specialization?
420static bool shouldConsiderTemplateVisibility(
421 const ClassTemplateSpecializationDecl *spec,
422 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000423 // Include visibility from the template parameters and arguments
424 // only if this is not an explicit instantiation or specialization
425 // with direct explicit visibility (and note that implicit
426 // instantiations won't have a direct attribute).
427 //
428 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000429 // for an explicit specialization when computing the visibility of a
430 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000431 //
432 // This is a bit complex; let's unpack it.
433 //
434 // An explicit class specialization is an independent, top-level
435 // declaration. As such, if it or any of its members has an
436 // explicit visibility attribute, that must directly express the
437 // user's intent, and we should honor it. The same logic applies to
438 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000439
440 // Fast path: if this is not an explicit instantiation or
441 // specialization, we always want to consider template-related
442 // visibility restrictions.
443 if (!spec->isExplicitInstantiationOrSpecialization())
444 return true;
445
446 // This is the 'member thereof' check.
447 if (spec->isExplicitSpecialization() &&
448 hasExplicitVisibilityAlready(computation))
449 return false;
450
John McCall5f46c482013-02-21 23:42:58 +0000451 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000452}
453
454/// Merge in template-related linkage and visibility for the given
455/// class template specialization.
456static void mergeTemplateLV(LinkageInfo &LV,
457 const ClassTemplateSpecializationDecl *spec,
458 LVComputationKind computation) {
459 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000460
461 // Merge information from the template parameters, but ignore
462 // visibility if we're only considering template arguments.
463
John McCalld041a9b2013-02-20 01:54:26 +0000464 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000465 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000466 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000467 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000468 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000469
470 // Merge information from the template arguments. We ignore
471 // template-argument visibility if we've got an explicit
472 // instantiation with a visibility attribute.
473 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000474 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000475 if (considerVisibility)
476 LV.mergeVisibility(argsLV);
477 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000478}
479
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000480static bool useInlineVisibilityHidden(const NamedDecl *D) {
481 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000482 const LangOptions &Opts = D->getASTContext().getLangOpts();
483 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000484 return false;
485
486 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
487 if (!FD)
488 return false;
489
490 TemplateSpecializationKind TSK = TSK_Undeclared;
491 if (FunctionTemplateSpecializationInfo *spec
492 = FD->getTemplateSpecializationInfo()) {
493 TSK = spec->getTemplateSpecializationKind();
494 } else if (MemberSpecializationInfo *MSI =
495 FD->getMemberSpecializationInfo()) {
496 TSK = MSI->getTemplateSpecializationKind();
497 }
498
499 const FunctionDecl *Def = 0;
500 // InlineVisibilityHidden only applies to definitions, and
501 // isInlined() only gives meaningful answers on definitions
502 // anyway.
503 return TSK != TSK_ExplicitInstantiationDeclaration &&
504 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000505 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000506}
507
Rafael Espindola593537a2013-05-05 20:15:21 +0000508template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000509 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000510 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000511}
512
Richard Smith03c05032014-02-17 23:34:47 +0000513static bool isSingleLineLanguageLinkage(const Decl &D) {
Rafael Espindola327be3c2013-04-26 01:30:23 +0000514 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000515 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000516 return true;
517 return false;
518}
519
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000520static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000521 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000522 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000523 "Not a name having namespace scope");
524 ASTContext &Context = D->getASTContext();
525
526 // C++ [basic.link]p3:
527 // A name having namespace scope (3.3.6) has internal linkage if it
528 // is the name of
529 // - an object, reference, function or function template that is
530 // explicitly declared static; or,
531 // (This bullet corresponds to C99 6.2.2p3.)
532 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
533 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000534 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000535 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000536
Richard Smithdc0ef452012-10-19 06:37:48 +0000537 // - a non-volatile object or reference that is explicitly declared const
538 // or constexpr and neither explicitly declared extern nor previously
539 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000540 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000541 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000542 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000543 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000544 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000545 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000546
547 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000548 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000549 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000550 return LinkageInfo::internal();
551 }
552
553 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
554 PrevVar = PrevVar->getPreviousDecl()) {
555 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
556 Var->getStorageClass() == SC_None)
557 return PrevVar->getLinkageAndVisibility();
558 // Explicitly declared static.
559 if (PrevVar->getStorageClass() == SC_Static)
560 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000561 }
Alp Tokera2794f92014-01-22 07:29:52 +0000562 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000563 // C++ [temp]p4:
564 // A non-member function template can have internal linkage; any
565 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000566
567 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000568 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000569 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000570 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000571 // - a data member of an anonymous union.
572 assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
573 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000574
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000575 if (D->isInAnonymousNamespace()) {
576 const VarDecl *Var = dyn_cast<VarDecl>(D);
577 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindola593537a2013-05-05 20:15:21 +0000578 if ((!Var || !isFirstInExternCContext(Var)) &&
579 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000580 return LinkageInfo::uniqueExternal();
581 }
John McCallb7139c42010-10-28 04:18:25 +0000582
John McCall457a04e2010-10-22 21:05:15 +0000583 // Set up the defaults.
584
585 // C99 6.2.2p5:
586 // If the declaration of an identifier for an object has file
587 // scope and no storage-class specifier, its linkage is
588 // external.
John McCallc273f242010-10-30 11:50:40 +0000589 LinkageInfo LV;
590
John McCalld041a9b2013-02-20 01:54:26 +0000591 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000592 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000593 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000594 } else {
595 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000596 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000597 for (const DeclContext *DC = D->getDeclContext();
598 !isa<TranslationUnitDecl>(DC);
599 DC = DC->getParent()) {
600 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
601 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000602 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000603 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000604 break;
605 }
606 }
607 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000608
John McCalldf25c432013-02-16 00:17:33 +0000609 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000610 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000611 // Use global type/value visibility as appropriate.
612 Visibility globalVisibility;
613 if (computation == LVForValue) {
614 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
615 } else {
616 assert(computation == LVForType);
617 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
618 }
619 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000620
621 // If we're paying attention to global visibility, apply
622 // -finline-visibility-hidden if this is an inline method.
623 if (useInlineVisibilityHidden(D))
624 LV.mergeVisibility(HiddenVisibility, true);
625 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000626 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000627
Douglas Gregorf73b2822009-11-25 22:24:25 +0000628 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000629
Douglas Gregorf73b2822009-11-25 22:24:25 +0000630 // A name having namespace scope has external linkage if it is the
631 // name of
632 //
633 // - an object or reference, unless it has internal linkage; or
634 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000635 // GCC applies the following optimization to variables and static
636 // data members, but not to functions:
637 //
John McCall457a04e2010-10-22 21:05:15 +0000638 // Modify the variable's LV by the LV of its type unless this is
639 // C or extern "C". This follows from [basic.link]p9:
640 // A type without linkage shall not be used as the type of a
641 // variable or function with external linkage unless
642 // - the entity has C language linkage, or
643 // - the entity is declared within an unnamed namespace, or
644 // - the entity is not used or is defined in the same
645 // translation unit.
646 // and [basic.link]p10:
647 // ...the types specified by all declarations referring to a
648 // given variable or function shall be identical...
649 // C does not have an equivalent rule.
650 //
John McCall5fe84122010-10-26 04:59:26 +0000651 // Ignore this if we've got an explicit attribute; the user
652 // probably knows what they're doing.
653 //
John McCall457a04e2010-10-22 21:05:15 +0000654 // Note that we don't want to make the variable non-external
655 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000656 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000657 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000658 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000659 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000660 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000661 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000662 }
663
John McCall23032652010-11-02 18:38:13 +0000664 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000665 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000666
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000667 // Note that Sema::MergeVarDecl already takes care of implementing
668 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
669 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000670
Douglas Gregorf73b2822009-11-25 22:24:25 +0000671 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000672 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000673 // In theory, we can modify the function's LV by the LV of its
674 // type unless it has C linkage (see comment above about variables
675 // for justification). In practice, GCC doesn't do this, so it's
676 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000677
John McCall23032652010-11-02 18:38:13 +0000678 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000679 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000680
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000681 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
682 // merging storage classes and visibility attributes, so we don't have to
683 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000684
John McCallf768aa72011-02-10 06:50:24 +0000685 // In C++, then if the type of the function uses a type with
686 // unique-external linkage, it's not legally usable from outside
687 // this translation unit. However, we should use the C linkage
688 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000689 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000690 !Function->isInExternCContext()) {
691 // Only look at the type-as-written. If this function has an auto-deduced
692 // return type, we can't compute the linkage of that type because it could
693 // require looking at the linkage of this function, and we don't need this
694 // for correctness because the type is not part of the function's
695 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000696 // FIXME: This is a hack. We should be able to solve this circularity and
697 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000698 QualType TypeAsWritten = Function->getType();
699 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
700 TypeAsWritten = TSI->getType();
701 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
702 return LinkageInfo::uniqueExternal();
703 }
John McCallf768aa72011-02-10 06:50:24 +0000704
John McCall5f46c482013-02-21 23:42:58 +0000705 // Consider LV from the template and the template arguments.
706 // We're at file scope, so we do not need to worry about nested
707 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000708 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000709 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000710 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000711 }
712
Douglas Gregorf73b2822009-11-25 22:24:25 +0000713 // - a named class (Clause 9), or an unnamed class defined in a
714 // typedef declaration in which the class has the typedef name
715 // for linkage purposes (7.1.3); or
716 // - a named enumeration (7.2), or an unnamed enumeration
717 // defined in a typedef declaration in which the enumeration
718 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000719 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
720 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000721 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000722 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000723
John McCall457a04e2010-10-22 21:05:15 +0000724 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000725 // linkage of the template and template arguments. We're at file
726 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000727 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000728 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000729 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000730 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000731
732 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000733 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000734 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000735 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000736 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000737 return LinkageInfo::none();
738 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000739
740 // - a template, unless it is a function template that has
741 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000742 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000743 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000744 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000745 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000746 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
747
Douglas Gregorf73b2822009-11-25 22:24:25 +0000748 // - a namespace (7.3), unless it is declared within an unnamed
749 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000750 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
751 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000752
John McCall457a04e2010-10-22 21:05:15 +0000753 // By extension, we assign external linkage to Objective-C
754 // interfaces.
755 } else if (isa<ObjCInterfaceDecl>(D)) {
756 // fallout
757
758 // Everything not covered here has no linkage.
759 } else {
John McCallc273f242010-10-30 11:50:40 +0000760 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000761 }
762
763 // If we ended up with non-external linkage, visibility should
764 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000765 if (LV.getLinkage() != ExternalLinkage)
766 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000767
John McCall457a04e2010-10-22 21:05:15 +0000768 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000769}
770
John McCalldf25c432013-02-16 00:17:33 +0000771static LinkageInfo getLVForClassMember(const NamedDecl *D,
772 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000773 // Only certain class members have linkage. Note that fields don't
774 // really have linkage, but it's convenient to say they do for the
775 // purposes of calculating linkage of pointer-to-data-member
776 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000777 //
778 // Templates also don't officially have linkage, but since we ignore
779 // the C++ standard and look at template arguments when determining
780 // linkage and visibility of a template specialization, we might hit
781 // a template template argument that way. If we do, we need to
782 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000783 if (!(isa<CXXMethodDecl>(D) ||
784 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000785 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000786 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000787 isa<TagDecl>(D) ||
788 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000789 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000790
John McCall07072662010-11-02 01:45:15 +0000791 LinkageInfo LV;
792
John McCall07072662010-11-02 01:45:15 +0000793 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000794 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000795 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000796 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000797 // If we're paying attention to global visibility, apply
798 // -finline-visibility-hidden if this is an inline method.
799 //
800 // Note that we do this before merging information about
801 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000802 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000803 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000804 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000805
806 // If this class member has an explicit visibility attribute, the only
807 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000808 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000809 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000810 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000811 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000812
John McCall5f46c482013-02-21 23:42:58 +0000813 LinkageInfo classLV =
814 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000815 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000816 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000817 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000818
Rafael Espindolae6190db2013-05-28 02:22:10 +0000819 if (!isExternallyVisible(classLV.getLinkage()))
820 return LinkageInfo::none();
821
822
John McCall5f46c482013-02-21 23:42:58 +0000823 // Otherwise, don't merge in classLV yet, because in certain cases
824 // we need to completely ignore the visibility from it.
825
826 // Specifically, if this decl exists and has an explicit attribute.
827 const NamedDecl *explicitSpecSuppressor = 0;
828
John McCall8823c652010-08-13 08:35:10 +0000829 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000830 // If the type of the function uses a type with unique-external
831 // linkage, it's not legally usable from outside this translation unit.
Faisal Valid2598e92013-10-08 04:15:04 +0000832 // But only look at the type-as-written. If this function has an auto-deduced
833 // return type, we can't compute the linkage of that type because it could
834 // require looking at the linkage of this function, and we don't need this
835 // for correctness because the type is not part of the function's
836 // signature.
837 // FIXME: This is a hack. We should be able to solve this circularity and the
838 // one in getLVForNamespaceScopeDecl for Functions some other way.
839 {
840 QualType TypeAsWritten = MD->getType();
841 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
842 TypeAsWritten = TSI->getType();
843 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
844 return LinkageInfo::uniqueExternal();
845 }
John McCall457a04e2010-10-22 21:05:15 +0000846 // If this is a method template specialization, use the linkage for
847 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000848 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000849 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000850 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000851 if (spec->isExplicitSpecialization()) {
852 explicitSpecSuppressor = MD;
853 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
854 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
855 }
856 } else if (isExplicitMemberSpecialization(MD)) {
857 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000858 }
John McCall457a04e2010-10-22 21:05:15 +0000859
John McCall37bb6c92010-10-29 22:22:43 +0000860 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000861 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000862 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000863 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000864 if (spec->isExplicitSpecialization()) {
865 explicitSpecSuppressor = spec;
866 } else {
867 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
868 if (isExplicitMemberSpecialization(temp)) {
869 explicitSpecSuppressor = temp->getTemplatedDecl();
870 }
871 }
872 } else if (isExplicitMemberSpecialization(RD)) {
873 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000874 }
875
John McCall37bb6c92010-10-29 22:22:43 +0000876 // Static data members.
877 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000878 // Modify the variable's linkage by its type, but ignore the
879 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000880 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000881 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
882 LV.mergeVisibility(typeLV);
883 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000884
885 if (isExplicitMemberSpecialization(VD)) {
886 explicitSpecSuppressor = VD;
887 }
John McCalldf25c432013-02-16 00:17:33 +0000888
889 // Template members.
890 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
891 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000892 (!LV.isVisibilityExplicit() &&
893 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000894 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000895 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000896 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000897 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000898
899 if (const RedeclarableTemplateDecl *redeclTemp =
900 dyn_cast<RedeclarableTemplateDecl>(temp)) {
901 if (isExplicitMemberSpecialization(redeclTemp)) {
902 explicitSpecSuppressor = temp->getTemplatedDecl();
903 }
904 }
John McCall37bb6c92010-10-29 22:22:43 +0000905 }
906
John McCall5f46c482013-02-21 23:42:58 +0000907 // We should never be looking for an attribute directly on a template.
908 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
909
910 // If this member is an explicit member specialization, and it has
911 // an explicit attribute, ignore visibility from the parent.
912 bool considerClassVisibility = true;
913 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000914 // optimization: hasDVA() is true only with explicit visibility.
915 LV.isVisibilityExplicit() &&
916 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000917 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
918 considerClassVisibility = false;
919 }
920
921 // Finally, merge in information from the class.
922 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000923 return LV;
John McCall8823c652010-08-13 08:35:10 +0000924}
925
David Blaikie68e081d2011-12-20 02:48:34 +0000926void NamedDecl::anchor() { }
927
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000928static LinkageInfo computeLVForDecl(const NamedDecl *D,
929 LVComputationKind computation);
930
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000931bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +0000932 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000933 return true;
John McCalld396b972011-02-08 19:01:05 +0000934
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000935 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +0000936 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +0000937}
938
Rafael Espindola3ae00052013-05-13 00:12:11 +0000939Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +0000940 // We don't care about visibility here, so ask for the cheapest
941 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000942 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +0000943}
944
John McCallc273f242010-10-30 11:50:40 +0000945LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000946 LVComputationKind computation =
947 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000948 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +0000949}
Ted Kremenek926d8602010-04-20 23:15:35 +0000950
Rafael Espindola9ad61122013-11-26 16:09:08 +0000951static Optional<Visibility>
952getExplicitVisibilityAux(const NamedDecl *ND,
953 NamedDecl::ExplicitVisibilityKind kind,
954 bool IsMostRecent) {
955 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
956
Rafael Espindola3a52c442013-02-26 19:33:14 +0000957 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000958 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +0000959 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000960
Rafael Espindola3a52c442013-02-26 19:33:14 +0000961 // If this is a member class of a specialization of a class template
962 // and the corresponding decl has explicit visibility, use that.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000963 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +0000964 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
965 if (InstantiatedFrom)
966 return getVisibilityOf(InstantiatedFrom, kind);
967 }
968
969 // If there wasn't explicit visibility there, and this is a
970 // specialization of a class template, check for visibility
971 // on the pattern.
972 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindola9ad61122013-11-26 16:09:08 +0000973 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +0000974 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
975 kind);
976
977 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +0000978 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +0000979 const NamedDecl *MostRecent = ND->getMostRecentDecl();
980 if (MostRecent != ND)
981 return getExplicitVisibilityAux(MostRecent, kind, true);
982 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000983
Rafael Espindola9ad61122013-11-26 16:09:08 +0000984 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +0000985 if (Var->isStaticDataMember()) {
986 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
987 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000988 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000989 }
990
David Blaikie7a30dc52013-02-21 01:47:18 +0000991 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +0000992 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000993 // Also handle function template specializations.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000994 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000995 // If the function is a specialization of a template with an
996 // explicit visibility attribute, use that.
997 if (FunctionTemplateSpecializationInfo *templateInfo
998 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +0000999 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1000 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001001
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001002 // If the function is a member of a specialization of a class template
1003 // and the corresponding decl has explicit visibility, use that.
1004 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1005 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001006 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001007
David Blaikie7a30dc52013-02-21 01:47:18 +00001008 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001009 }
1010
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001011 // The visibility of a template is stored in the templated decl.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001012 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001013 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001014
David Blaikie7a30dc52013-02-21 01:47:18 +00001015 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001016}
1017
Rafael Espindola9ad61122013-11-26 16:09:08 +00001018Optional<Visibility>
1019NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1020 return getExplicitVisibilityAux(this, kind, false);
1021}
1022
Eli Friedman7e346a82013-07-01 20:22:57 +00001023static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1024 LVComputationKind computation) {
1025 // This lambda has its linkage/visibility determined by its owner.
1026 if (ContextDecl) {
1027 if (isa<ParmVarDecl>(ContextDecl))
1028 DC = ContextDecl->getDeclContext()->getRedeclContext();
1029 else
1030 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1031 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001032
Eli Friedman7e346a82013-07-01 20:22:57 +00001033 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1034 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001035
Eli Friedman7e346a82013-07-01 20:22:57 +00001036 return LinkageInfo::external();
1037}
1038
John McCalldf25c432013-02-16 00:17:33 +00001039static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1040 LVComputationKind computation) {
1041 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1042 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001043 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001044 return LinkageInfo::uniqueExternal();
1045
1046 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001047 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001048 return LinkageInfo::internal();
1049
1050 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001051 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001052 if (Optional<Visibility> Vis =
1053 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001054 LV.mergeVisibility(*Vis, true);
1055 }
1056
1057 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1058 // merging storage classes and visibility attributes, so we don't have to
1059 // look at previous decls in here.
1060
1061 return LV;
1062 }
1063
1064 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001065 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001066 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001067 return LinkageInfo::uniqueExternal();
1068
John McCalldf25c432013-02-16 00:17:33 +00001069 LinkageInfo LV;
1070 if (Var->getStorageClass() == SC_PrivateExtern)
1071 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001072 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001073 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001074 LV.mergeVisibility(*Vis, true);
1075 }
1076
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001077 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1078 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1079 if (PrevLV.getLinkage())
1080 LV.setLinkage(PrevLV.getLinkage());
1081 LV.mergeVisibility(PrevLV);
1082 }
1083
John McCalldf25c432013-02-16 00:17:33 +00001084 return LV;
1085 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001086
1087 if (!Var->isStaticLocal())
1088 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001089 }
1090
Rafael Espindolaa4184182013-06-17 20:04:51 +00001091 ASTContext &Context = D->getASTContext();
1092 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001093 return LinkageInfo::none();
1094
Eli Friedman7e346a82013-07-01 20:22:57 +00001095 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1096 if (!OuterD)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001097 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001098
Eli Friedman7e346a82013-07-01 20:22:57 +00001099 LinkageInfo LV;
1100 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1101 if (!BD->getBlockManglingNumber())
1102 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001103
Eli Friedman7e346a82013-07-01 20:22:57 +00001104 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1105 BD->getBlockManglingContextDecl(), computation);
1106 } else {
1107 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1108 if (!FD->isInlined() &&
1109 FD->getTemplateSpecializationKind() == TSK_Undeclared)
1110 return LinkageInfo::none();
1111
1112 LV = getLVForDecl(FD, computation);
1113 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001114 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001115 return LinkageInfo::none();
1116 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1117 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001118}
1119
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001120static inline const CXXRecordDecl*
1121getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1122 const CXXRecordDecl *Ret = Record;
1123 while (Record && Record->isLambda()) {
1124 Ret = Record;
1125 if (!Record->getParent()) break;
1126 // Get the Containing Class of this Lambda Class
1127 Record = dyn_cast_or_null<CXXRecordDecl>(
1128 Record->getParent()->getParent());
1129 }
1130 return Ret;
1131}
1132
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001133static LinkageInfo computeLVForDecl(const NamedDecl *D,
1134 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001135 // Objective-C: treat all Objective-C declarations as having external
1136 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001137 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001138 default:
1139 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001140 case Decl::ParmVar:
1141 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001142 case Decl::TemplateTemplateParm: // count these as external
1143 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001144 case Decl::ObjCAtDefsField:
1145 case Decl::ObjCCategory:
1146 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001147 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001148 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001149 case Decl::ObjCMethod:
1150 case Decl::ObjCProperty:
1151 case Decl::ObjCPropertyImpl:
1152 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001153 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001154
1155 case Decl::CXXRecord: {
1156 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1157 if (Record->isLambda()) {
1158 if (!Record->getLambdaManglingNumber()) {
1159 // This lambda has no mangling number, so it's internal.
1160 return LinkageInfo::internal();
1161 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001162
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001163 // This lambda has its linkage/visibility determined:
1164 // - either by the outermost lambda if that lambda has no mangling
1165 // number.
1166 // - or by the parent of the outer most lambda
1167 // This prevents infinite recursion in settings such as nested lambdas
1168 // used in NSDMI's, for e.g.
1169 // struct L {
1170 // int t{};
1171 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1172 // };
1173 const CXXRecordDecl *OuterMostLambda =
1174 getOutermostEnclosingLambda(Record);
1175 if (!OuterMostLambda->getLambdaManglingNumber())
1176 return LinkageInfo::internal();
1177
1178 return getLVForClosure(
1179 OuterMostLambda->getDeclContext()->getRedeclContext(),
1180 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001181 }
1182
1183 break;
1184 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001185 }
1186
Douglas Gregorf73b2822009-11-25 22:24:25 +00001187 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001188 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001189 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001190
1191 // C++ [basic.link]p5:
1192 // In addition, a member function, static data member, a named
1193 // class or enumeration of class scope, or an unnamed class or
1194 // enumeration defined in a class-scope typedef declaration such
1195 // that the class or enumeration has the typedef name for linkage
1196 // purposes (7.1.3), has external linkage if the name of the class
1197 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001198 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001199 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001200
1201 // C++ [basic.link]p6:
1202 // The name of a function declared in block scope and the name of
1203 // an object declared by a block scope extern declaration have
1204 // linkage. If there is a visible declaration of an entity with
1205 // linkage having the same name and type, ignoring entities
1206 // declared outside the innermost enclosing namespace scope, the
1207 // block scope declaration declares that same entity and receives
1208 // the linkage of the previous declaration. If there is more than
1209 // one such matching entity, the program is ill-formed. Otherwise,
1210 // if no matching entity is found, the block scope entity receives
1211 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001212 if (D->getDeclContext()->isFunctionOrMethod())
1213 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001214
1215 // C++ [basic.link]p6:
1216 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001217 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001218}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001219
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001220namespace clang {
1221class LinkageComputer {
1222public:
1223 static LinkageInfo getLVForDecl(const NamedDecl *D,
1224 LVComputationKind computation) {
1225 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1226 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1227
1228 LinkageInfo LV = computeLVForDecl(D, computation);
1229 if (D->hasCachedLinkage())
1230 assert(D->getCachedLinkage() == LV.getLinkage());
1231
1232 D->setCachedLinkage(LV.getLinkage());
1233
1234#ifndef NDEBUG
1235 // In C (because of gnu inline) and in c++ with microsoft extensions an
1236 // static can follow an extern, so we can have two decls with different
1237 // linkages.
1238 const LangOptions &Opts = D->getASTContext().getLangOpts();
1239 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1240 return LV;
1241
1242 // We have just computed the linkage for this decl. By induction we know
1243 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001244 // computed also does.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001245 NamedDecl *Old = NULL;
Aaron Ballman86c93902014-03-06 23:45:36 +00001246 for (auto I : D->redecls()) {
1247 NamedDecl *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001248 if (T == D)
1249 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001250 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001251 Old = T;
1252 break;
1253 }
1254 }
1255 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1256#endif
1257
1258 return LV;
1259 }
1260};
1261}
1262
1263static LinkageInfo getLVForDecl(const NamedDecl *D,
1264 LVComputationKind computation) {
1265 return clang::LinkageComputer::getLVForDecl(D, computation);
1266}
1267
Douglas Gregor2ada0482009-02-04 17:27:36 +00001268std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001269 std::string QualName;
1270 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001271 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001272 return OS.str();
1273}
1274
1275void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1276 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1277}
1278
1279void NamedDecl::printQualifiedName(raw_ostream &OS,
1280 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001281 const DeclContext *Ctx = getDeclContext();
1282
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001283 if (Ctx->isFunctionOrMethod()) {
1284 printName(OS);
1285 return;
1286 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001287
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001288 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001289 ContextsTy Contexts;
1290
1291 // Collect contexts.
1292 while (Ctx && isa<NamedDecl>(Ctx)) {
1293 Contexts.push_back(Ctx);
1294 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001295 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001296
1297 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1298 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001299 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001300 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001301 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001302 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001303 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1304 TemplateArgs.data(),
1305 TemplateArgs.size(),
1306 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001307 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001308 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001309 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001310 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001311 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001312 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1313 if (!RD->getIdentifier())
1314 OS << "<anonymous " << RD->getKindName() << '>';
1315 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001316 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001317 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001318 const FunctionProtoType *FT = 0;
1319 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001320 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001321
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001322 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001323 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001324 unsigned NumParams = FD->getNumParams();
1325 for (unsigned i = 0; i < NumParams; ++i) {
1326 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001327 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001328 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001329 }
1330
1331 if (FT->isVariadic()) {
1332 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001333 OS << ", ";
1334 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001335 }
1336 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001337 OS << ')';
1338 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001339 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001340 }
1341 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001342 }
1343
John McCalla2a3f7d2010-03-16 21:48:18 +00001344 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001345 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001346 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001347 OS << "<anonymous>";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001348}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001349
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001350void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1351 const PrintingPolicy &Policy,
1352 bool Qualified) const {
1353 if (Qualified)
1354 printQualifiedName(OS, Policy);
1355 else
1356 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001357}
1358
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001359bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001360 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1361
Douglas Gregor889ceb72009-02-03 19:21:40 +00001362 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1363 // We want to keep it, unless it nominates same namespace.
1364 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001365 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1366 ->getOriginalNamespace() ==
1367 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1368 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001371 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1372 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001373 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001374
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001375 // For function templates, the underlying function declarations are linked.
1376 if (const FunctionTemplateDecl *FunctionTemplate
1377 = dyn_cast<FunctionTemplateDecl>(this))
1378 if (const FunctionTemplateDecl *OldFunctionTemplate
1379 = dyn_cast<FunctionTemplateDecl>(OldD))
1380 return FunctionTemplate->getTemplatedDecl()
1381 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001382
Steve Naroffc4173fa2009-02-22 19:35:57 +00001383 // For method declarations, we keep track of redeclarations.
1384 if (isa<ObjCMethodDecl>(this))
1385 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001386
John McCall9f3059a2009-10-09 21:13:30 +00001387 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1388 return true;
1389
John McCall3f746822009-11-17 05:59:44 +00001390 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1391 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1392 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1393
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001394 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1395 ASTContext &Context = getASTContext();
1396 return Context.getCanonicalNestedNameSpecifier(
1397 cast<UsingDecl>(this)->getQualifier()) ==
1398 Context.getCanonicalNestedNameSpecifier(
1399 cast<UsingDecl>(OldD)->getQualifier());
1400 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001401
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001402 if (isa<UnresolvedUsingValueDecl>(this) &&
1403 isa<UnresolvedUsingValueDecl>(OldD)) {
1404 ASTContext &Context = getASTContext();
1405 return Context.getCanonicalNestedNameSpecifier(
1406 cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1407 Context.getCanonicalNestedNameSpecifier(
1408 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1409 }
1410
Douglas Gregorb59643b2012-01-03 23:26:26 +00001411 // A typedef of an Objective-C class type can replace an Objective-C class
1412 // declaration or definition, and vice versa.
1413 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1414 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1415 return true;
1416
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001417 // For non-function declarations, if the declarations are of the
1418 // same kind then this must be a redeclaration, or semantic analysis
1419 // would not have given us the new declaration.
1420 return this->getKind() == OldD->getKind();
1421}
1422
Douglas Gregoreddf4332009-02-24 20:03:32 +00001423bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001424 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001425}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001426
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001427NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001428 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001429 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1430 ND = UD->getTargetDecl();
1431
1432 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1433 return AD->getClassInterface();
1434
1435 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001436}
1437
John McCalla8ae2222010-04-06 21:38:20 +00001438bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001439 if (!isCXXClassMember())
1440 return false;
1441
John McCalla8ae2222010-04-06 21:38:20 +00001442 const NamedDecl *D = this;
1443 if (isa<UsingShadowDecl>(D))
1444 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1445
John McCall5e77d762013-04-16 07:28:30 +00001446 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001447 return true;
Alp Tokera2794f92014-01-22 07:29:52 +00001448 if (const CXXMethodDecl *MD =
1449 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1450 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001451 return false;
1452}
1453
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001454//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001455// DeclaratorDecl Implementation
1456//===----------------------------------------------------------------------===//
1457
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001458template <typename DeclT>
1459static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1460 if (decl->getNumTemplateParameterLists() > 0)
1461 return decl->getTemplateParameterList(0)->getTemplateLoc();
1462 else
1463 return decl->getInnerLocStart();
1464}
1465
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001466SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001467 TypeSourceInfo *TSI = getTypeSourceInfo();
1468 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001469 return SourceLocation();
1470}
1471
Douglas Gregor14454802011-02-25 02:25:35 +00001472void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1473 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001474 // Make sure the extended decl info is allocated.
1475 if (!hasExtInfo()) {
1476 // Save (non-extended) type source info pointer.
1477 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1478 // Allocate external info struct.
1479 DeclInfo = new (getASTContext()) ExtInfo;
1480 // Restore savedTInfo into (extended) decl info.
1481 getExtInfo()->TInfo = savedTInfo;
1482 }
1483 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001484 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001485 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001486 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001487 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001488 if (getExtInfo()->NumTemplParamLists == 0) {
1489 // Save type source info pointer.
1490 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1491 // Deallocate the extended decl info.
1492 getASTContext().Deallocate(getExtInfo());
1493 // Restore savedTInfo into (non-extended) decl info.
1494 DeclInfo = savedTInfo;
1495 }
1496 else
1497 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001498 }
1499 }
1500}
1501
Abramo Bagnara60804e12011-03-18 15:16:37 +00001502void
1503DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1504 unsigned NumTPLists,
1505 TemplateParameterList **TPLists) {
1506 assert(NumTPLists > 0);
1507 // Make sure the extended decl info is allocated.
1508 if (!hasExtInfo()) {
1509 // Save (non-extended) type source info pointer.
1510 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1511 // Allocate external info struct.
1512 DeclInfo = new (getASTContext()) ExtInfo;
1513 // Restore savedTInfo into (extended) decl info.
1514 getExtInfo()->TInfo = savedTInfo;
1515 }
1516 // Set the template parameter lists info.
1517 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1518}
1519
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001520SourceLocation DeclaratorDecl::getOuterLocStart() const {
1521 return getTemplateOrInnerLocStart(this);
1522}
1523
Abramo Bagnaraea947882011-03-08 16:41:52 +00001524namespace {
1525
1526// Helper function: returns true if QT is or contains a type
1527// having a postfix component.
1528bool typeIsPostfix(clang::QualType QT) {
1529 while (true) {
1530 const Type* T = QT.getTypePtr();
1531 switch (T->getTypeClass()) {
1532 default:
1533 return false;
1534 case Type::Pointer:
1535 QT = cast<PointerType>(T)->getPointeeType();
1536 break;
1537 case Type::BlockPointer:
1538 QT = cast<BlockPointerType>(T)->getPointeeType();
1539 break;
1540 case Type::MemberPointer:
1541 QT = cast<MemberPointerType>(T)->getPointeeType();
1542 break;
1543 case Type::LValueReference:
1544 case Type::RValueReference:
1545 QT = cast<ReferenceType>(T)->getPointeeType();
1546 break;
1547 case Type::PackExpansion:
1548 QT = cast<PackExpansionType>(T)->getPattern();
1549 break;
1550 case Type::Paren:
1551 case Type::ConstantArray:
1552 case Type::DependentSizedArray:
1553 case Type::IncompleteArray:
1554 case Type::VariableArray:
1555 case Type::FunctionProto:
1556 case Type::FunctionNoProto:
1557 return true;
1558 }
1559 }
1560}
1561
1562} // namespace
1563
1564SourceRange DeclaratorDecl::getSourceRange() const {
1565 SourceLocation RangeEnd = getLocation();
1566 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001567 // If the declaration has no name or the type extends past the name take the
1568 // end location of the type.
1569 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001570 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1571 }
1572 return SourceRange(getOuterLocStart(), RangeEnd);
1573}
1574
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001575void
Douglas Gregor20527e22010-06-15 17:44:38 +00001576QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1577 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001578 TemplateParameterList **TPLists) {
1579 assert((NumTPLists == 0 || TPLists != 0) &&
1580 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001581
1582 // Free previous template parameters (if any).
1583 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001584 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001585 TemplParamLists = 0;
1586 NumTemplParamLists = 0;
1587 }
1588 // Set info on matched template parameter lists (if any).
1589 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001590 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001591 NumTemplParamLists = NumTPLists;
1592 for (unsigned i = NumTPLists; i-- > 0; )
1593 TemplParamLists[i] = TPLists[i];
1594 }
1595}
1596
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001597//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001598// VarDecl Implementation
1599//===----------------------------------------------------------------------===//
1600
Sebastian Redl833ef452010-01-26 22:01:41 +00001601const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1602 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001603 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001604 case SC_Auto: return "auto";
1605 case SC_Extern: return "extern";
1606 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1607 case SC_PrivateExtern: return "__private_extern__";
1608 case SC_Register: return "register";
1609 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001610 }
1611
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001612 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001613}
1614
Larisse Voufo39a1e502013-08-06 01:03:05 +00001615VarDecl::VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1616 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1617 TypeSourceInfo *TInfo, StorageClass SC)
1618 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
1619 assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
1620 assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
1621 AllBits = 0;
1622 VarDeclBits.SClass = SC;
1623 // Everything else is implicitly initialized to false.
1624}
1625
Abramo Bagnaradff19302011-03-08 08:55:46 +00001626VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1627 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001628 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001629 StorageClass S) {
Richard Smithf7981722013-11-22 09:01:48 +00001630 return new (C, DC) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001631}
1632
Douglas Gregor72172e92012-01-05 21:55:30 +00001633VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00001634 return new (C, ID) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1635 QualType(), 0, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001636}
1637
Douglas Gregorbf62d642010-12-06 18:36:25 +00001638void VarDecl::setStorageClass(StorageClass SC) {
1639 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001640 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001641}
1642
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001643SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001644 if (const Expr *Init = getInit()) {
1645 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001646 // If Init is implicit, ignore its source range and fallback on
1647 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1648 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001649 return SourceRange(getOuterLocStart(), InitEnd);
1650 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001651 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001652}
1653
Rafael Espindola88510672013-01-04 21:18:45 +00001654template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001655static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001656 // C++ [dcl.link]p1: All function types, function names with external linkage,
1657 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001658 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001659 return NoLanguageLinkage;
1660
1661 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001662 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001663 ASTContext &Context = D.getASTContext();
1664 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001665 return CLanguageLinkage;
1666
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001667 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1668 // language linkage of the names of class members and the function type of
1669 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001670 const DeclContext *DC = D.getDeclContext();
1671 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001672 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001673
1674 // If the first decl is in an extern "C" context, any other redeclaration
1675 // will have C language linkage. If the first one is not in an extern "C"
1676 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001677 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001678 return CLanguageLinkage;
1679 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001680}
1681
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001682template<typename T>
1683static bool isExternCTemplate(const T &D) {
1684 // Since the context is ignored for class members, they can only have C++
1685 // language linkage or no language linkage.
1686 const DeclContext *DC = D.getDeclContext();
1687 if (DC->isRecord()) {
1688 assert(D.getASTContext().getLangOpts().CPlusPlus);
1689 return false;
1690 }
1691
1692 return D.getLanguageLinkage() == CLanguageLinkage;
1693}
1694
Rafael Espindolaf4187652013-02-14 01:18:37 +00001695LanguageLinkage VarDecl::getLanguageLinkage() const {
1696 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001697}
1698
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001699bool VarDecl::isExternC() const {
1700 return isExternCTemplate(*this);
1701}
1702
Rafael Espindola593537a2013-05-05 20:15:21 +00001703bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001704 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001705}
1706
1707bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001708 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001709}
1710
Rafael Espindola8db352d2013-10-17 15:37:26 +00001711VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001712
Daniel Dunbar9d355812012-03-09 01:51:51 +00001713VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1714 ASTContext &C) const
1715{
Sebastian Redl35351a92010-01-31 22:27:38 +00001716 // C++ [basic.def]p2:
1717 // A declaration is a definition unless [...] it contains the 'extern'
1718 // specifier or a linkage-specification and neither an initializer [...],
1719 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001720 // C++1y [temp.expl.spec]p15:
1721 // An explicit specialization of a static data member or an explicit
1722 // specialization of a static data member template is a definition if the
1723 // declaration includes an initializer; otherwise, it is a declaration.
1724 //
1725 // FIXME: How do you declare (but not define) a partial specialization of
1726 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001727 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001728 if (isOutOfLine() &&
1729 (hasInit() ||
1730 // If the first declaration is out-of-line, this may be an
1731 // instantiation of an out-of-line partial specialization of a variable
1732 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001733 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001734 ? getTemplateSpecializationKind() == TSK_Undeclared
1735 : getTemplateSpecializationKind() !=
1736 TSK_ExplicitSpecialization) ||
1737 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001738 return Definition;
1739 else
1740 return DeclarationOnly;
1741 }
1742 // C99 6.7p5:
1743 // A definition of an identifier is a declaration for that identifier that
1744 // [...] causes storage to be reserved for that object.
1745 // Note: that applies for all non-file-scope objects.
1746 // C99 6.9.2p1:
1747 // If the declaration of an identifier for an object has file scope and an
1748 // initializer, the declaration is an external definition for the identifier
1749 if (hasInit())
1750 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001751
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001752 if (hasAttr<AliasAttr>())
1753 return Definition;
1754
Richard Smith8809a0c2013-09-27 20:14:12 +00001755 // A variable template specialization (other than a static data member
1756 // template or an explicit specialization) is a declaration until we
1757 // instantiate its initializer.
1758 if (isa<VarTemplateSpecializationDecl>(this) &&
1759 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1760 return DeclarationOnly;
1761
Sebastian Redl35351a92010-01-31 22:27:38 +00001762 if (hasExternalStorage())
1763 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001764
Rafael Espindolabff59562013-04-25 12:11:36 +00001765 // [dcl.link] p7:
1766 // A declaration directly contained in a linkage-specification is treated
1767 // as if it contains the extern specifier for the purpose of determining
1768 // the linkage of the declared name and whether it is a definition.
Richard Smith03c05032014-02-17 23:34:47 +00001769 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001770 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001771
Sebastian Redl35351a92010-01-31 22:27:38 +00001772 // C99 6.9.2p2:
1773 // A declaration of an object that has file scope without an initializer,
1774 // and without a storage class specifier or the scs 'static', constitutes
1775 // a tentative definition.
1776 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001777 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001778 return TentativeDefinition;
1779
1780 // What's left is (in C, block-scope) declarations without initializers or
1781 // external storage. These are definitions.
1782 return Definition;
1783}
1784
Sebastian Redl35351a92010-01-31 22:27:38 +00001785VarDecl *VarDecl::getActingDefinition() {
1786 DefinitionKind Kind = isThisDeclarationADefinition();
1787 if (Kind != TentativeDefinition)
1788 return 0;
1789
Chris Lattner48eb14d2010-06-14 18:31:46 +00001790 VarDecl *LastTentative = 0;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001791 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001792 for (auto I : First->redecls()) {
1793 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001794 if (Kind == Definition)
1795 return 0;
1796 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001797 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001798 }
1799 return LastTentative;
1800}
1801
Daniel Dunbar9d355812012-03-09 01:51:51 +00001802VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001803 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001804 for (auto I : First->redecls()) {
1805 if (I->isThisDeclarationADefinition(C) == Definition)
1806 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001807 }
1808 return 0;
1809}
1810
Daniel Dunbar9d355812012-03-09 01:51:51 +00001811VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001812 DefinitionKind Kind = DeclarationOnly;
1813
Rafael Espindola8db352d2013-10-17 15:37:26 +00001814 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001815 for (auto I : First->redecls()) {
1816 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001817 if (Kind == Definition)
1818 break;
1819 }
John McCall37bb6c92010-10-29 22:22:43 +00001820
1821 return Kind;
1822}
1823
Sebastian Redl5ca79842010-02-01 20:16:42 +00001824const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00001825 for (auto I : redecls()) {
1826 if (auto Expr = I->getInit()) {
1827 D = I;
1828 return Expr;
1829 }
Sebastian Redl833ef452010-01-26 22:01:41 +00001830 }
1831 return 0;
1832}
1833
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001834bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001835 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001836 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001837
1838 if (!isStaticDataMember())
1839 return false;
1840
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001841 // If this static data member was instantiated from a static data member of
1842 // a class template, check whether that static data member was defined
1843 // out-of-line.
1844 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1845 return VD->isOutOfLine();
1846
1847 return false;
1848}
1849
Douglas Gregor1d957a32009-10-27 18:42:08 +00001850VarDecl *VarDecl::getOutOfLineDefinition() {
1851 if (!isStaticDataMember())
1852 return 0;
1853
Aaron Ballman86c93902014-03-06 23:45:36 +00001854 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001855 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00001856 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00001857 }
1858
1859 return 0;
1860}
1861
Douglas Gregord5058122010-02-11 01:19:42 +00001862void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001863 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1864 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001865 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001866 }
1867
1868 Init = I;
1869}
1870
Daniel Dunbar9d355812012-03-09 01:51:51 +00001871bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001872 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001873
Richard Smith35ecb362012-03-02 04:14:40 +00001874 if (!Lang.CPlusPlus)
1875 return false;
1876
1877 // In C++11, any variable of reference type can be used in a constant
1878 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001879 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001880 return true;
1881
1882 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001883 // not require the variable to be non-volatile, but we consider this to be a
1884 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001885 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001886 return false;
1887
1888 // In C++, const, non-volatile variables of integral or enumeration types
1889 // can be used in constant expressions.
1890 if (getType()->isIntegralOrEnumerationType())
1891 return true;
1892
Richard Smith35ecb362012-03-02 04:14:40 +00001893 // Additionally, in C++11, non-volatile constexpr variables can be used in
1894 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001895 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001896}
1897
Richard Smithd0b4dd62011-12-19 06:19:21 +00001898/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1899/// form, which contains extra information on the evaluated value of the
1900/// initializer.
1901EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1902 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1903 if (!Eval) {
1904 Stmt *S = Init.get<Stmt *>();
Manuel Klimeka7328992013-06-03 13:51:33 +00001905 // Note: EvaluatedStmt contains an APValue, which usually holds
1906 // resources not allocated from the ASTContext. We need to do some
1907 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
1908 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00001909 Eval = new (getASTContext()) EvaluatedStmt;
1910 Eval->Value = S;
1911 Init = Eval;
1912 }
1913 return Eval;
1914}
1915
Richard Smithdafff942012-01-14 04:30:29 +00001916APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001917 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001918 return evaluateValue(Notes);
1919}
1920
Manuel Klimeka7328992013-06-03 13:51:33 +00001921namespace {
1922// Destroy an APValue that was allocated in an ASTContext.
1923void DestroyAPValue(void* UntypedValue) {
1924 static_cast<APValue*>(UntypedValue)->~APValue();
1925}
1926} // namespace
1927
Richard Smithdafff942012-01-14 04:30:29 +00001928APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001929 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001930 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1931
1932 // We only produce notes indicating why an initializer is non-constant the
1933 // first time it is evaluated. FIXME: The notes won't always be emitted the
1934 // first time we try evaluation, so might not be produced at all.
1935 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001936 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001937
1938 const Expr *Init = cast<Expr>(Eval->Value);
1939 assert(!Init->isValueDependent());
1940
1941 if (Eval->IsEvaluating) {
1942 // FIXME: Produce a diagnostic for self-initialization.
1943 Eval->CheckedICE = true;
1944 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001945 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001946 }
1947
1948 Eval->IsEvaluating = true;
1949
1950 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1951 this, Notes);
1952
Manuel Klimeka7328992013-06-03 13:51:33 +00001953 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
1954 // or that it's empty (so that there's nothing to clean up) if evaluation
1955 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00001956 if (!Result)
1957 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00001958 else if (Eval->Evaluated.needsCleanup())
1959 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001960
1961 Eval->IsEvaluating = false;
1962 Eval->WasEvaluated = true;
1963
1964 // In C++11, we have determined whether the initializer was a constant
1965 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001966 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001967 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001968 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001969 }
1970
Richard Smithdafff942012-01-14 04:30:29 +00001971 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001972}
1973
1974bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001975 // Initializers of weak variables are never ICEs.
1976 if (isWeak())
1977 return false;
1978
Richard Smithd0b4dd62011-12-19 06:19:21 +00001979 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1980 if (Eval->CheckedICE)
1981 // We have already checked whether this subexpression is an
1982 // integral constant expression.
1983 return Eval->IsICE;
1984
1985 const Expr *Init = cast<Expr>(Eval->Value);
1986 assert(!Init->isValueDependent());
1987
1988 // In C++11, evaluate the initializer to check whether it's a constant
1989 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001990 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001991 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001992 evaluateValue(Notes);
1993 return Eval->IsICE;
1994 }
1995
1996 // It's an ICE whether or not the definition we found is
1997 // out-of-line. See DR 721 and the discussion in Clang PR
1998 // 6206 for details.
1999
2000 if (Eval->CheckingICE)
2001 return false;
2002 Eval->CheckingICE = true;
2003
2004 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2005 Eval->CheckingICE = false;
2006 Eval->CheckedICE = true;
2007 return Eval->IsICE;
2008}
2009
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002010VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002011 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002012 return cast<VarDecl>(MSI->getInstantiatedFrom());
2013
2014 return 0;
2015}
2016
Douglas Gregor3c74d412009-10-14 20:14:33 +00002017TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002018 if (const VarTemplateSpecializationDecl *Spec =
2019 dyn_cast<VarTemplateSpecializationDecl>(this))
2020 return Spec->getSpecializationKind();
2021
Sebastian Redl35351a92010-01-31 22:27:38 +00002022 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002023 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002024
Douglas Gregor86d142a2009-10-08 07:24:58 +00002025 return TSK_Undeclared;
2026}
2027
Richard Smith8809a0c2013-09-27 20:14:12 +00002028SourceLocation VarDecl::getPointOfInstantiation() const {
2029 if (const VarTemplateSpecializationDecl *Spec =
2030 dyn_cast<VarTemplateSpecializationDecl>(this))
2031 return Spec->getPointOfInstantiation();
2032
2033 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2034 return MSI->getPointOfInstantiation();
2035
2036 return SourceLocation();
2037}
2038
Larisse Voufo39a1e502013-08-06 01:03:05 +00002039VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2040 return getASTContext().getTemplateOrSpecializationInfo(this)
2041 .dyn_cast<VarTemplateDecl *>();
2042}
2043
2044void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2045 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2046}
2047
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002048MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002049 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002050 // FIXME: Remove ?
2051 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2052 return getASTContext().getTemplateOrSpecializationInfo(this)
2053 .dyn_cast<MemberSpecializationInfo *>();
Richard Smithb71782b2013-08-01 04:12:04 +00002054 return 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002055}
2056
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002057void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2058 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002059 assert((isa<VarTemplateSpecializationDecl>(this) ||
2060 getMemberSpecializationInfo()) &&
2061 "not a variable or static data member template specialization");
2062
Larisse Voufo39a1e502013-08-06 01:03:05 +00002063 if (VarTemplateSpecializationDecl *Spec =
2064 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2065 Spec->setSpecializationKind(TSK);
2066 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2067 Spec->getPointOfInstantiation().isInvalid())
2068 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002069 }
2070
2071 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2072 MSI->setTemplateSpecializationKind(TSK);
2073 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2074 MSI->getPointOfInstantiation().isInvalid())
2075 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002076 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002077}
2078
2079void
2080VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2081 TemplateSpecializationKind TSK) {
2082 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2083 "Previous template or instantiation?");
2084 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002085}
2086
Sebastian Redl833ef452010-01-26 22:01:41 +00002087//===----------------------------------------------------------------------===//
2088// ParmVarDecl Implementation
2089//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002090
Sebastian Redl833ef452010-01-26 22:01:41 +00002091ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002092 SourceLocation StartLoc,
2093 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002094 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002095 StorageClass S, Expr *DefArg) {
Richard Smithf7981722013-11-22 09:01:48 +00002096 return new (C, DC) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
2097 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002098}
2099
Reid Kleckner8a365022013-06-24 17:51:48 +00002100QualType ParmVarDecl::getOriginalType() const {
2101 TypeSourceInfo *TSI = getTypeSourceInfo();
2102 QualType T = TSI ? TSI->getType() : getType();
2103 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2104 return DT->getOriginalType();
2105 return T;
2106}
2107
Douglas Gregor72172e92012-01-05 21:55:30 +00002108ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00002109 return new (C, ID) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
2110 0, QualType(), 0, SC_None, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00002111}
2112
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002113SourceRange ParmVarDecl::getSourceRange() const {
2114 if (!hasInheritedDefaultArg()) {
2115 SourceRange ArgRange = getDefaultArgRange();
2116 if (ArgRange.isValid())
2117 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2118 }
2119
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002120 // DeclaratorDecl considers the range of postfix types as overlapping with the
2121 // declaration name, but this is not the case with parameters in ObjC methods.
2122 if (isa<ObjCMethodDecl>(getDeclContext()))
2123 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2124
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002125 return DeclaratorDecl::getSourceRange();
2126}
2127
Sebastian Redl833ef452010-01-26 22:01:41 +00002128Expr *ParmVarDecl::getDefaultArg() {
2129 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2130 assert(!hasUninstantiatedDefaultArg() &&
2131 "Default argument is not yet instantiated!");
2132
2133 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00002134 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002135 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002136
Sebastian Redl833ef452010-01-26 22:01:41 +00002137 return Arg;
2138}
2139
Sebastian Redl833ef452010-01-26 22:01:41 +00002140SourceRange ParmVarDecl::getDefaultArgRange() const {
2141 if (const Expr *E = getInit())
2142 return E->getSourceRange();
2143
2144 if (hasUninstantiatedDefaultArg())
2145 return getUninstantiatedDefaultArg()->getSourceRange();
2146
2147 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002148}
2149
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002150bool ParmVarDecl::isParameterPack() const {
2151 return isa<PackExpansionType>(getType());
2152}
2153
Ted Kremenek540017e2011-10-06 05:00:56 +00002154void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2155 getASTContext().setParameterIndex(this, parameterIndex);
2156 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2157}
2158
2159unsigned ParmVarDecl::getParameterIndexLarge() const {
2160 return getASTContext().getParameterIndex(this);
2161}
2162
Nuno Lopes394ec982008-12-17 23:39:55 +00002163//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002164// FunctionDecl Implementation
2165//===----------------------------------------------------------------------===//
2166
Benjamin Kramer9170e912013-02-22 15:46:01 +00002167void FunctionDecl::getNameForDiagnostic(
2168 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2169 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002170 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2171 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002172 TemplateSpecializationType::PrintTemplateArgumentList(
2173 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002174}
2175
Ted Kremenek186a0742010-04-29 16:49:01 +00002176bool FunctionDecl::isVariadic() const {
2177 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2178 return FT->isVariadic();
2179 return false;
2180}
2181
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002182bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002183 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002184 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002185 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002186 return true;
2187 }
2188 }
2189
2190 return false;
2191}
2192
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002193bool FunctionDecl::hasTrivialBody() const
2194{
2195 Stmt *S = getBody();
2196 if (!S) {
2197 // Since we don't have a body for this function, we don't know if it's
2198 // trivial or not.
2199 return false;
2200 }
2201
2202 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2203 return true;
2204 return false;
2205}
2206
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002207bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002208 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002209 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2210 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002211 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002212 return true;
2213 }
2214 }
2215
2216 return false;
2217}
2218
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002219Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002220 if (!hasBody(Definition))
2221 return 0;
2222
2223 if (Definition->Body)
2224 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002225
2226 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002227}
2228
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002229void FunctionDecl::setBody(Stmt *B) {
2230 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002231 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002232 EndRangeLoc = B->getLocEnd();
2233}
2234
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002235void FunctionDecl::setPure(bool P) {
2236 IsPure = P;
2237 if (P)
2238 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2239 Parent->markedVirtualFunctionPure();
2240}
2241
Richard Smith8d0dc312013-07-21 23:12:18 +00002242template<std::size_t Len>
2243static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2244 IdentifierInfo *II = ND->getIdentifier();
2245 return II && II->isStr(Str);
2246}
2247
Douglas Gregor16618f22009-09-12 00:17:51 +00002248bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002249 const TranslationUnitDecl *tunit =
2250 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2251 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002252 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002253 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002254}
2255
David Majnemerc729b0b2013-09-16 22:44:20 +00002256bool FunctionDecl::isMSVCRTEntryPoint() const {
2257 const TranslationUnitDecl *TUnit =
2258 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2259 if (!TUnit)
2260 return false;
2261
2262 // Even though we aren't really targeting MSVCRT if we are freestanding,
2263 // semantic analysis for these functions remains the same.
2264
2265 // MSVCRT entry points only exist on MSVCRT targets.
2266 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2267 return false;
2268
2269 // Nameless functions like constructors cannot be entry points.
2270 if (!getIdentifier())
2271 return false;
2272
2273 return llvm::StringSwitch<bool>(getName())
2274 .Cases("main", // an ANSI console app
2275 "wmain", // a Unicode console App
2276 "WinMain", // an ANSI GUI app
2277 "wWinMain", // a Unicode GUI app
2278 "DllMain", // a DLL
2279 true)
2280 .Default(false);
2281}
2282
John McCall53ffd372011-05-15 17:49:20 +00002283bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2284 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2285 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2286 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2287 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2288 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2289
Richard Smithf6004412014-01-19 23:25:37 +00002290 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2291 return false;
John McCall53ffd372011-05-15 17:49:20 +00002292
2293 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002294 if (proto->getNumParams() != 2 || proto->isVariadic())
2295 return false;
John McCall53ffd372011-05-15 17:49:20 +00002296
2297 ASTContext &Context =
2298 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2299 ->getASTContext();
2300
2301 // The result type and first argument type are constant across all
2302 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002303 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002304}
2305
Richard Smith8d0dc312013-07-21 23:12:18 +00002306static bool isNamespaceStd(const DeclContext *DC) {
2307 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC->getRedeclContext());
2308 return ND && isNamed(ND, "std") &&
2309 ND->getParent()->getRedeclContext()->isTranslationUnit();
2310}
2311
2312bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2313 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2314 return false;
2315 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2316 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2317 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2318 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2319 return false;
2320
2321 if (isa<CXXRecordDecl>(getDeclContext()))
2322 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002323
2324 // This can only fail for an invalid 'operator new' declaration.
2325 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2326 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002327
2328 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002329 if (FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002330 return false;
2331
2332 // If this is a single-parameter function, it must be a replaceable global
2333 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002334 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002335 return true;
2336
2337 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002338 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002339 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002340 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002341 if (Ctx.getLangOpts().SizedDeallocation &&
2342 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002343 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002344 if (!Ty->isReferenceType())
2345 return false;
2346 Ty = Ty->getPointeeType();
2347 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2348 return false;
2349 // FIXME: Recognise nothrow_t in an inline namespace inside std?
2350 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2351 return RD && isNamed(RD, "nothrow_t") && isNamespaceStd(RD->getDeclContext());
2352}
2353
Richard Smithb47c36f2013-11-05 09:12:18 +00002354FunctionDecl *
2355FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2356 ASTContext &Ctx = getASTContext();
2357 if (!Ctx.getLangOpts().SizedDeallocation)
2358 return 0;
2359
2360 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2361 return 0;
2362 if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2363 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2364 return 0;
2365 if (isa<CXXRecordDecl>(getDeclContext()))
2366 return 0;
Richard Smithf6004412014-01-19 23:25:37 +00002367
2368 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2369 return 0;
Richard Smithb47c36f2013-11-05 09:12:18 +00002370
2371 if (getNumParams() != 2 || isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00002372 !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
Richard Smithb47c36f2013-11-05 09:12:18 +00002373 Ctx.getSizeType()))
2374 return 0;
2375
2376 // This is a sized deallocation function. Find the corresponding unsized
2377 // deallocation function.
2378 lookup_const_result R = getDeclContext()->lookup(getDeclName());
2379 for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2380 ++RI)
2381 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2382 if (FD->getNumParams() == 1 && !FD->isVariadic())
2383 return FD;
2384 return 0;
2385}
2386
Rafael Espindolaf4187652013-02-14 01:18:37 +00002387LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002388 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002389}
2390
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002391bool FunctionDecl::isExternC() const {
2392 return isExternCTemplate(*this);
2393}
2394
Rafael Espindola593537a2013-05-05 20:15:21 +00002395bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002396 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002397}
2398
2399bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002400 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002401}
2402
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002403bool FunctionDecl::isGlobal() const {
2404 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2405 return Method->isStatic();
2406
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002407 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002408 return false;
2409
Mike Stump11289f42009-09-09 15:08:12 +00002410 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002411 DC->isNamespace();
2412 DC = DC->getParent()) {
2413 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2414 if (!Namespace->getDeclName())
2415 return false;
2416 break;
2417 }
2418 }
2419
2420 return true;
2421}
2422
Richard Smith10876ef2013-01-17 01:30:42 +00002423bool FunctionDecl::isNoReturn() const {
2424 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002425 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002426 getType()->getAs<FunctionType>()->getNoReturnAttr();
2427}
2428
Sebastian Redl833ef452010-01-26 22:01:41 +00002429void
2430FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002431 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002432
2433 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2434 FunctionTemplateDecl *PrevFunTmpl
2435 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2436 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002437 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002438 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002439
Axel Naumannfbc7b982011-11-08 18:21:06 +00002440 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002441 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002442}
2443
2444const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002445 return getFirstDecl();
Sebastian Redl833ef452010-01-26 22:01:41 +00002446}
2447
Rafael Espindola8db352d2013-10-17 15:37:26 +00002448FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002449
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002450/// \brief Returns a value indicating whether this function
2451/// corresponds to a builtin function.
2452///
2453/// The function corresponds to a built-in function if it is
2454/// declared at translation scope or within an extern "C" block and
2455/// its name matches with the name of a builtin. The returned value
2456/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002457/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002458/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002459unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002460 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002461 return 0;
2462
2463 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002464 if (!BuiltinID)
2465 return 0;
2466
2467 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002468 if (Context.getLangOpts().CPlusPlus) {
2469 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2470 getFirstDecl()->getDeclContext());
2471 // In C++, the first declaration of a builtin is always inside an implicit
2472 // extern "C".
2473 // FIXME: A recognised library function may not be directly in an extern "C"
2474 // declaration, for instance "extern "C" { namespace std { decl } }".
2475 if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2476 return 0;
2477 }
2478
2479 // If the function is marked "overloadable", it has a different mangled name
2480 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002481 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002482 return 0;
2483
Douglas Gregore711f702009-02-14 18:57:46 +00002484 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2485 return BuiltinID;
2486
2487 // This function has the name of a known C library
2488 // function. Determine whether it actually refers to the C library
2489 // function or whether it just has the same name.
2490
Douglas Gregora908e7f2009-02-17 03:23:10 +00002491 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002492 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002493 return 0;
2494
Warren Hunt445d83e2013-11-01 23:46:51 +00002495 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002496}
2497
2498
Chris Lattner47c0d002009-04-25 06:03:53 +00002499/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002500/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002501/// after it has been created.
2502unsigned FunctionDecl::getNumParams() const {
Reid Kleckner0503a872013-12-05 01:23:43 +00002503 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002504 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002505}
2506
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002507void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002508 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002509 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002510 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002511
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002512 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002513 if (!NewParamInfo.empty()) {
2514 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2515 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002516 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002517}
Chris Lattner41943152007-01-25 04:52:46 +00002518
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002519void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002520 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2521
2522 if (!NewDecls.empty()) {
2523 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2524 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002525 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002526 }
2527}
2528
Chris Lattner58258242008-04-10 02:22:51 +00002529/// getMinRequiredArguments - Returns the minimum number of arguments
2530/// needed to call this function. This may be fewer than the number of
2531/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002532/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002533unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002534 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002535 return getNumParams();
2536
Douglas Gregor7825bf32011-01-06 22:09:01 +00002537 unsigned NumRequiredArgs = getNumParams();
2538
2539 // If the last parameter is a parameter pack, we don't need an argument for
2540 // it.
2541 if (NumRequiredArgs > 0 &&
2542 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2543 --NumRequiredArgs;
2544
2545 // If this parameter has a default argument, we don't need an argument for
2546 // it.
2547 while (NumRequiredArgs > 0 &&
2548 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002549 --NumRequiredArgs;
2550
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002551 // We might have parameter packs before the end. These can't be deduced,
2552 // but they can still handle multiple arguments.
2553 unsigned ArgIdx = NumRequiredArgs;
2554 while (ArgIdx > 0) {
2555 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2556 NumRequiredArgs = ArgIdx;
2557
2558 --ArgIdx;
2559 }
2560
Chris Lattner58258242008-04-10 02:22:51 +00002561 return NumRequiredArgs;
2562}
2563
Eli Friedman1b125c32012-02-07 03:50:18 +00002564static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2565 // Only consider file-scope declarations in this test.
2566 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2567 return false;
2568
2569 // Only consider explicit declarations; the presence of a builtin for a
2570 // libcall shouldn't affect whether a definition is externally visible.
2571 if (Redecl->isImplicit())
2572 return false;
2573
2574 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2575 return true; // Not an inline definition
2576
2577 return false;
2578}
2579
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002580/// \brief For a function declaration in C or C++, determine whether this
2581/// declaration causes the definition to be externally visible.
2582///
Eli Friedman1b125c32012-02-07 03:50:18 +00002583/// Specifically, this determines if adding the current declaration to the set
2584/// of redeclarations of the given functions causes
2585/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002586bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2587 assert(!doesThisDeclarationHaveABody() &&
2588 "Must have a declaration without a body.");
2589
2590 ASTContext &Context = getASTContext();
2591
David Blaikiebbafb8a2012-03-11 07:00:24 +00002592 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002593 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2594 // an externally visible definition.
2595 //
2596 // FIXME: What happens if gnu_inline gets added on after the first
2597 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002598 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002599 return false;
2600
2601 const FunctionDecl *Prev = this;
2602 bool FoundBody = false;
2603 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002604 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002605
2606 if (Prev->Body) {
2607 // If it's not the case that both 'inline' and 'extern' are
2608 // specified on the definition, then it is always externally visible.
2609 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002610 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002611 return false;
2612 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002613 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002614 return false;
2615 }
2616 }
2617 return FoundBody;
2618 }
2619
David Blaikiebbafb8a2012-03-11 07:00:24 +00002620 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002621 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002622
2623 // C99 6.7.4p6:
2624 // [...] If all of the file scope declarations for a function in a
2625 // translation unit include the inline function specifier without extern,
2626 // then the definition in that translation unit is an inline definition.
2627 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002628 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002629 const FunctionDecl *Prev = this;
2630 bool FoundBody = false;
2631 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002632 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002633 if (RedeclForcesDefC99(Prev))
2634 return false;
2635 }
2636 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002637}
2638
Richard Smithf3814ad2013-01-25 00:08:28 +00002639/// \brief For an inline function definition in C, or for a gnu_inline function
2640/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002641///
2642/// Inline function definitions are always available for inlining optimizations.
2643/// However, depending on the language dialect, declaration specifiers, and
2644/// attributes, the definition of an inline function may or may not be
2645/// "externally" visible to other translation units in the program.
2646///
2647/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002648/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002649/// inline definition becomes externally visible (C99 6.7.4p6).
2650///
2651/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2652/// definition, we use the GNU semantics for inline, which are nearly the
2653/// opposite of C99 semantics. In particular, "inline" by itself will create
2654/// an externally visible symbol, but "extern inline" will not create an
2655/// externally visible symbol.
2656bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002657 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002658 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002659 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002660
David Blaikiebbafb8a2012-03-11 07:00:24 +00002661 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002662 // Note: If you change the logic here, please change
2663 // doesDeclarationForceExternallyVisibleDefinition as well.
2664 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002665 // If it's not the case that both 'inline' and 'extern' are
2666 // specified on the definition, then this inline definition is
2667 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002668 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002669 return true;
2670
2671 // If any declaration is 'inline' but not 'extern', then this definition
2672 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002673 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002674 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002675 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002676 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002677 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002678
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002679 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002680 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002681
Richard Smithf3814ad2013-01-25 00:08:28 +00002682 // The rest of this function is C-only.
2683 assert(!Context.getLangOpts().CPlusPlus &&
2684 "should not use C inline rules in C++");
2685
Douglas Gregor299d76e2009-09-13 07:46:26 +00002686 // C99 6.7.4p6:
2687 // [...] If all of the file scope declarations for a function in a
2688 // translation unit include the inline function specifier without extern,
2689 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002690 for (auto Redecl : redecls()) {
2691 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002692 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002693 }
2694
2695 // C99 6.7.4p6:
2696 // An inline definition does not provide an external definition for the
2697 // function, and does not forbid an external definition in another
2698 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002699 return false;
2700}
2701
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002702/// getOverloadedOperator - Which C++ overloaded operator this
2703/// function represents, if any.
2704OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002705 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2706 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002707 else
2708 return OO_None;
2709}
2710
Alexis Huntc88db062010-01-13 09:01:02 +00002711/// getLiteralIdentifier - The literal suffix identifier this function
2712/// represents, if any.
2713const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2714 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2715 return getDeclName().getCXXLiteralIdentifier();
2716 else
2717 return 0;
2718}
2719
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002720FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2721 if (TemplateOrSpecialization.isNull())
2722 return TK_NonTemplate;
2723 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2724 return TK_FunctionTemplate;
2725 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2726 return TK_MemberSpecialization;
2727 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2728 return TK_FunctionTemplateSpecialization;
2729 if (TemplateOrSpecialization.is
2730 <DependentFunctionTemplateSpecializationInfo*>())
2731 return TK_DependentFunctionTemplateSpecialization;
2732
David Blaikie83d382b2011-09-23 05:06:16 +00002733 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002734}
2735
Douglas Gregord801b062009-10-07 23:56:10 +00002736FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002737 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002738 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2739
2740 return 0;
2741}
2742
2743void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002744FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2745 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002746 TemplateSpecializationKind TSK) {
2747 assert(TemplateOrSpecialization.isNull() &&
2748 "Member function is already a specialization");
2749 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002750 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002751 TemplateOrSpecialization = Info;
2752}
2753
Douglas Gregorafca3b42009-10-27 20:53:28 +00002754bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002755 // If the function is invalid, it can't be implicitly instantiated.
2756 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002757 return false;
2758
2759 switch (getTemplateSpecializationKind()) {
2760 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002761 case TSK_ExplicitInstantiationDefinition:
2762 return false;
2763
2764 case TSK_ImplicitInstantiation:
2765 return true;
2766
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002767 // It is possible to instantiate TSK_ExplicitSpecialization kind
2768 // if the FunctionDecl has a class scope specialization pattern.
2769 case TSK_ExplicitSpecialization:
2770 return getClassScopeSpecializationPattern() != 0;
2771
Douglas Gregorafca3b42009-10-27 20:53:28 +00002772 case TSK_ExplicitInstantiationDeclaration:
2773 // Handled below.
2774 break;
2775 }
2776
2777 // Find the actual template from which we will instantiate.
2778 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002779 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002780 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002781 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002782
2783 // C++0x [temp.explicit]p9:
2784 // Except for inline functions, other explicit instantiation declarations
2785 // have the effect of suppressing the implicit instantiation of the entity
2786 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002787 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002788 return true;
2789
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002790 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002791}
2792
2793bool FunctionDecl::isTemplateInstantiation() const {
2794 switch (getTemplateSpecializationKind()) {
2795 case TSK_Undeclared:
2796 case TSK_ExplicitSpecialization:
2797 return false;
2798 case TSK_ImplicitInstantiation:
2799 case TSK_ExplicitInstantiationDeclaration:
2800 case TSK_ExplicitInstantiationDefinition:
2801 return true;
2802 }
2803 llvm_unreachable("All TSK values handled.");
2804}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002805
2806FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002807 // Handle class scope explicit specialization special case.
2808 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2809 return getClassScopeSpecializationPattern();
2810
Douglas Gregorafca3b42009-10-27 20:53:28 +00002811 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2812 while (Primary->getInstantiatedFromMemberTemplate()) {
2813 // If we have hit a point where the user provided a specialization of
2814 // this template, we're done looking.
2815 if (Primary->isMemberSpecialization())
2816 break;
2817
2818 Primary = Primary->getInstantiatedFromMemberTemplate();
2819 }
2820
2821 return Primary->getTemplatedDecl();
2822 }
2823
2824 return getInstantiatedFromMemberFunction();
2825}
2826
Douglas Gregor70d83e22009-06-29 17:30:29 +00002827FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002828 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002829 = TemplateOrSpecialization
2830 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002831 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002832 }
2833 return 0;
2834}
2835
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002836FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2837 return getASTContext().getClassScopeSpecializationPattern(this);
2838}
2839
Douglas Gregor70d83e22009-06-29 17:30:29 +00002840const TemplateArgumentList *
2841FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002842 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002843 = TemplateOrSpecialization
2844 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002845 return Info->TemplateArguments;
2846 }
2847 return 0;
2848}
2849
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002850const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002851FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2852 if (FunctionTemplateSpecializationInfo *Info
2853 = TemplateOrSpecialization
2854 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2855 return Info->TemplateArgumentsAsWritten;
2856 }
2857 return 0;
2858}
2859
Mike Stump11289f42009-09-09 15:08:12 +00002860void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002861FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2862 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002863 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002864 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002865 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002866 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2867 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002868 assert(TSK != TSK_Undeclared &&
2869 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002870 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002871 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002872 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002873 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2874 TemplateArgs,
2875 TemplateArgsAsWritten,
2876 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002877 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002878 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002879}
2880
John McCallb9c78482010-04-08 09:05:18 +00002881void
2882FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2883 const UnresolvedSetImpl &Templates,
2884 const TemplateArgumentListInfo &TemplateArgs) {
2885 assert(TemplateOrSpecialization.isNull());
2886 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2887 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002888 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002889 void *Buffer = Context.Allocate(Size);
2890 DependentFunctionTemplateSpecializationInfo *Info =
2891 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2892 TemplateArgs);
2893 TemplateOrSpecialization = Info;
2894}
2895
2896DependentFunctionTemplateSpecializationInfo::
2897DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2898 const TemplateArgumentListInfo &TArgs)
2899 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2900
2901 d.NumTemplates = Ts.size();
2902 d.NumArgs = TArgs.size();
2903
2904 FunctionTemplateDecl **TsArray =
2905 const_cast<FunctionTemplateDecl**>(getTemplates());
2906 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2907 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2908
2909 TemplateArgumentLoc *ArgsArray =
2910 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2911 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2912 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2913}
2914
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002915TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002916 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002917 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002918 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002919 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002920 if (FTSInfo)
2921 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002922
Douglas Gregord801b062009-10-07 23:56:10 +00002923 MemberSpecializationInfo *MSInfo
2924 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2925 if (MSInfo)
2926 return MSInfo->getTemplateSpecializationKind();
2927
2928 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002929}
2930
Mike Stump11289f42009-09-09 15:08:12 +00002931void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002932FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2933 SourceLocation PointOfInstantiation) {
2934 if (FunctionTemplateSpecializationInfo *FTSInfo
2935 = TemplateOrSpecialization.dyn_cast<
2936 FunctionTemplateSpecializationInfo*>()) {
2937 FTSInfo->setTemplateSpecializationKind(TSK);
2938 if (TSK != TSK_ExplicitSpecialization &&
2939 PointOfInstantiation.isValid() &&
2940 FTSInfo->getPointOfInstantiation().isInvalid())
2941 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2942 } else if (MemberSpecializationInfo *MSInfo
2943 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2944 MSInfo->setTemplateSpecializationKind(TSK);
2945 if (TSK != TSK_ExplicitSpecialization &&
2946 PointOfInstantiation.isValid() &&
2947 MSInfo->getPointOfInstantiation().isInvalid())
2948 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2949 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002950 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002951}
2952
2953SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002954 if (FunctionTemplateSpecializationInfo *FTSInfo
2955 = TemplateOrSpecialization.dyn_cast<
2956 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002957 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002958 else if (MemberSpecializationInfo *MSInfo
2959 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002960 return MSInfo->getPointOfInstantiation();
2961
2962 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002963}
2964
Douglas Gregor6411b922009-09-11 20:15:17 +00002965bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002966 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002967 return true;
2968
2969 // If this function was instantiated from a member function of a
2970 // class template, check whether that member function was defined out-of-line.
2971 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2972 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002973 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002974 return Definition->isOutOfLine();
2975 }
2976
2977 // If this function was instantiated from a function template,
2978 // check whether that function template was defined out-of-line.
2979 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2980 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002981 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002982 return Definition->isOutOfLine();
2983 }
2984
2985 return false;
2986}
2987
Abramo Bagnaraea947882011-03-08 16:41:52 +00002988SourceRange FunctionDecl::getSourceRange() const {
2989 return SourceRange(getOuterLocStart(), EndRangeLoc);
2990}
2991
Anna Zaks28db7ce2012-01-18 02:45:01 +00002992unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002993 IdentifierInfo *FnInfo = getIdentifier();
2994
2995 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002996 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002997
2998 // Builtin handling.
2999 switch (getBuiltinID()) {
3000 case Builtin::BI__builtin_memset:
3001 case Builtin::BI__builtin___memset_chk:
3002 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003003 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003004
3005 case Builtin::BI__builtin_memcpy:
3006 case Builtin::BI__builtin___memcpy_chk:
3007 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003008 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003009
3010 case Builtin::BI__builtin_memmove:
3011 case Builtin::BI__builtin___memmove_chk:
3012 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003013 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003014
3015 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003016 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003017 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00003018 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003019
3020 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003021 case Builtin::BImemcmp:
3022 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003023
3024 case Builtin::BI__builtin_strncpy:
3025 case Builtin::BI__builtin___strncpy_chk:
3026 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003027 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003028
3029 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003030 case Builtin::BIstrncmp:
3031 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003032
3033 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003034 case Builtin::BIstrncasecmp:
3035 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003036
3037 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003038 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003039 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003040 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003041
3042 case Builtin::BI__builtin_strndup:
3043 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003044 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003045
Anna Zaks314cd092012-02-01 19:08:57 +00003046 case Builtin::BI__builtin_strlen:
3047 case Builtin::BIstrlen:
3048 return Builtin::BIstrlen;
3049
Anna Zaks201d4892012-01-13 21:52:01 +00003050 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003051 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003052 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003053 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003054 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003055 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003056 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003057 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003058 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003059 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003060 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003061 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003062 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003063 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003064 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003065 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003066 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003067 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003068 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003069 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003070 else if (FnInfo->isStr("strlen"))
3071 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003072 }
3073 break;
3074 }
Anna Zaks22122702012-01-17 00:37:07 +00003075 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003076}
3077
Chris Lattner59a25942008-03-31 00:36:02 +00003078//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003079// FieldDecl Implementation
3080//===----------------------------------------------------------------------===//
3081
Jay Foad39c79802011-01-12 09:06:06 +00003082FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003083 SourceLocation StartLoc, SourceLocation IdLoc,
3084 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003085 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003086 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003087 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3088 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003089}
3090
Douglas Gregor72172e92012-01-05 21:55:30 +00003091FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003092 return new (C, ID) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
3093 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003094}
3095
Sebastian Redl833ef452010-01-26 22:01:41 +00003096bool FieldDecl::isAnonymousStructOrUnion() const {
3097 if (!isImplicit() || getDeclName())
3098 return false;
3099
3100 if (const RecordType *Record = getType()->getAs<RecordType>())
3101 return Record->getDecl()->isAnonymousStructOrUnion();
3102
3103 return false;
3104}
3105
Richard Smithcaf33902011-10-10 18:28:20 +00003106unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3107 assert(isBitField() && "not a bitfield");
3108 Expr *BitWidth = InitializerOrBitWidth.getPointer();
3109 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3110}
3111
John McCall4e819612011-01-20 07:57:12 +00003112unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003113 const FieldDecl *Canonical = getCanonicalDecl();
3114 if (Canonical != this)
3115 return Canonical->getFieldIndex();
3116
John McCall4e819612011-01-20 07:57:12 +00003117 if (CachedFieldIndex) return CachedFieldIndex - 1;
3118
Richard Smithd62306a2011-11-10 06:34:14 +00003119 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003120 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003121
3122 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
Eli Friedman2782dac2013-06-26 20:50:34 +00003123 I != E; ++I, ++Index)
Richard Smith0b87e072013-10-07 08:02:11 +00003124 I->getCanonicalDecl()->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00003125
Richard Smithd62306a2011-11-10 06:34:14 +00003126 assert(CachedFieldIndex && "failed to find field in parent");
3127 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003128}
3129
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003130SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00003131 if (const Expr *E = InitializerOrBitWidth.getPointer())
3132 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00003133 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003134}
3135
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00003136void FieldDecl::setBitWidth(Expr *Width) {
3137 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3138 "bit width or initializer already set");
3139 InitializerOrBitWidth.setPointer(Width);
3140}
3141
Richard Smith938f40b2011-06-11 17:19:42 +00003142void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00003143 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003144 "bit width or initializer already set");
3145 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003146}
3147
Sebastian Redl833ef452010-01-26 22:01:41 +00003148//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003149// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003150//===----------------------------------------------------------------------===//
3151
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003152SourceLocation TagDecl::getOuterLocStart() const {
3153 return getTemplateOrInnerLocStart(this);
3154}
3155
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003156SourceRange TagDecl::getSourceRange() const {
3157 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003158 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003159}
3160
Rafael Espindola8db352d2013-10-17 15:37:26 +00003161TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003162
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003163void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer50ce8352013-09-17 23:57:10 +00003164 NamedDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00003165 if (TypeForDecl)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003166 assert(TypeForDecl->isLinkageValid());
3167 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003168}
3169
Douglas Gregordee1be82009-01-17 00:42:38 +00003170void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003171 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003172
David Blaikie095deba2012-11-14 01:52:05 +00003173 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00003174 struct CXXRecordDecl::DefinitionData *Data =
3175 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003176 for (auto I : redecls())
3177 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003178 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003179}
3180
3181void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003182 assert((!isa<CXXRecordDecl>(this) ||
3183 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3184 "definition completed but not started");
3185
John McCallf937c022011-10-07 06:10:15 +00003186 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003187 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003188
3189 if (ASTMutationListener *L = getASTMutationListener())
3190 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003191}
3192
John McCallf937c022011-10-07 06:10:15 +00003193TagDecl *TagDecl::getDefinition() const {
3194 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003195 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003196
3197 // If it's possible for us to have an out-of-date definition, check now.
3198 if (MayHaveOutOfDateDef) {
3199 if (IdentifierInfo *II = getIdentifier()) {
3200 if (II->isOutOfDate()) {
3201 updateOutOfDate(*II);
3202 }
3203 }
3204 }
3205
Andrew Trickba266ee2010-10-19 21:54:32 +00003206 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3207 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003208
Aaron Ballman86c93902014-03-06 23:45:36 +00003209 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003210 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003211 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003212
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003213 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00003214}
3215
Douglas Gregor14454802011-02-25 02:25:35 +00003216void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3217 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003218 // Make sure the extended qualifier info is allocated.
3219 if (!hasExtInfo())
David Majnemer50ce8352013-09-17 23:57:10 +00003220 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003221 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003222 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003223 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003224 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003225 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003226 if (getExtInfo()->NumTemplParamLists == 0) {
3227 getASTContext().Deallocate(getExtInfo());
David Majnemer50ce8352013-09-17 23:57:10 +00003228 NamedDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003229 }
3230 else
3231 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003232 }
3233 }
3234}
3235
Abramo Bagnara60804e12011-03-18 15:16:37 +00003236void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3237 unsigned NumTPLists,
3238 TemplateParameterList **TPLists) {
3239 assert(NumTPLists > 0);
3240 // Make sure the extended decl info is allocated.
3241 if (!hasExtInfo())
3242 // Allocate external info struct.
David Majnemer50ce8352013-09-17 23:57:10 +00003243 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003244 // Set the template parameter lists info.
3245 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3246}
3247
Ted Kremenek21475702008-09-05 17:16:31 +00003248//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003249// EnumDecl Implementation
3250//===----------------------------------------------------------------------===//
3251
David Blaikie68e081d2011-12-20 02:48:34 +00003252void EnumDecl::anchor() { }
3253
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003254EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3255 SourceLocation StartLoc, SourceLocation IdLoc,
3256 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003257 EnumDecl *PrevDecl, bool IsScoped,
3258 bool IsScopedUsingClassTag, bool IsFixed) {
Richard Smithf7981722013-11-22 09:01:48 +00003259 EnumDecl *Enum = new (C, DC) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
3260 IsScoped, IsScopedUsingClassTag,
3261 IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003262 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003263 C.getTypeDeclType(Enum, PrevDecl);
3264 return Enum;
3265}
3266
Douglas Gregor72172e92012-01-05 21:55:30 +00003267EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003268 EnumDecl *Enum = new (C, ID) EnumDecl(0, SourceLocation(), SourceLocation(),
3269 0, 0, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003270 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3271 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003272}
3273
Alp Tokerb9fa5122014-01-06 11:31:18 +00003274SourceRange EnumDecl::getIntegerTypeRange() const {
3275 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3276 return TI->getTypeLoc().getSourceRange();
3277 return SourceRange();
3278}
3279
Douglas Gregord5058122010-02-11 01:19:42 +00003280void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003281 QualType NewPromotionType,
3282 unsigned NumPositiveBits,
3283 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003284 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003285 if (!IntegerType)
3286 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003287 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003288 setNumPositiveBits(NumPositiveBits);
3289 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003290 TagDecl::completeDefinition();
3291}
3292
Richard Smith7d137e32012-03-23 03:33:32 +00003293TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3294 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3295 return MSI->getTemplateSpecializationKind();
3296
3297 return TSK_Undeclared;
3298}
3299
3300void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3301 SourceLocation PointOfInstantiation) {
3302 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3303 assert(MSI && "Not an instantiated member enumeration?");
3304 MSI->setTemplateSpecializationKind(TSK);
3305 if (TSK != TSK_ExplicitSpecialization &&
3306 PointOfInstantiation.isValid() &&
3307 MSI->getPointOfInstantiation().isInvalid())
3308 MSI->setPointOfInstantiation(PointOfInstantiation);
3309}
3310
Richard Smith4b38ded2012-03-14 23:13:10 +00003311EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3312 if (SpecializationInfo)
3313 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3314
3315 return 0;
3316}
3317
3318void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3319 TemplateSpecializationKind TSK) {
3320 assert(!SpecializationInfo && "Member enum is already a specialization");
3321 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3322}
3323
Sebastian Redl833ef452010-01-26 22:01:41 +00003324//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003325// RecordDecl Implementation
3326//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003327
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003328RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3329 SourceLocation StartLoc, SourceLocation IdLoc,
3330 IdentifierInfo *Id, RecordDecl *PrevDecl)
3331 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003332 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003333 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003334 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003335 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003336 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003337 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003338}
3339
Jay Foad39c79802011-01-12 09:06:06 +00003340RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003341 SourceLocation StartLoc, SourceLocation IdLoc,
3342 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smithf7981722013-11-22 09:01:48 +00003343 RecordDecl* R = new (C, DC) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3344 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003345 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3346
Ted Kremenek21475702008-09-05 17:16:31 +00003347 C.getTypeDeclType(R, PrevDecl);
3348 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003349}
3350
Douglas Gregor72172e92012-01-05 21:55:30 +00003351RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003352 RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3353 SourceLocation(), 0, 0);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003354 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3355 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003356}
3357
Douglas Gregordfcad112009-03-25 15:59:44 +00003358bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003359 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003360 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3361}
3362
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003363RecordDecl::field_iterator RecordDecl::field_begin() const {
3364 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3365 LoadFieldsFromExternalStorage();
3366
3367 return field_iterator(decl_iterator(FirstDecl));
3368}
3369
Douglas Gregorb11aad82011-02-19 18:51:44 +00003370/// completeDefinition - Notes that the definition of this type is now
3371/// complete.
3372void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003373 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003374 TagDecl::completeDefinition();
3375}
3376
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003377/// isMsStruct - Get whether or not this record uses ms_struct layout.
3378/// This which can be turned on with an attribute, pragma, or the
3379/// -mms-bitfields command-line option.
3380bool RecordDecl::isMsStruct(const ASTContext &C) const {
3381 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3382}
3383
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003384static bool isFieldOrIndirectField(Decl::Kind K) {
3385 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3386}
3387
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003388void RecordDecl::LoadFieldsFromExternalStorage() const {
3389 ExternalASTSource *Source = getASTContext().getExternalSource();
3390 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3391
3392 // Notify that we have a RecordDecl doing some initialization.
3393 ExternalASTSource::Deserializing TheFields(Source);
3394
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003395 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003396 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003397 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3398 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003399 case ELR_Success:
3400 break;
3401
3402 case ELR_AlreadyLoaded:
3403 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003404 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003405 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003406
3407#ifndef NDEBUG
3408 // Check that all decls we got were FieldDecls.
3409 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003410 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003411#endif
3412
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003413 if (Decls.empty())
3414 return;
3415
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003416 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003417 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003418}
3419
Steve Naroff415d3d52008-10-08 17:01:13 +00003420//===----------------------------------------------------------------------===//
3421// BlockDecl Implementation
3422//===----------------------------------------------------------------------===//
3423
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003424void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003425 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003426
Steve Naroffc4b30e52009-03-13 16:56:44 +00003427 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003428 if (!NewParamInfo.empty()) {
3429 NumParams = NewParamInfo.size();
3430 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3431 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003432 }
3433}
3434
John McCall351762c2011-02-07 10:33:21 +00003435void BlockDecl::setCaptures(ASTContext &Context,
3436 const Capture *begin,
3437 const Capture *end,
3438 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003439 CapturesCXXThis = capturesCXXThis;
3440
3441 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003442 NumCaptures = 0;
3443 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003444 return;
3445 }
3446
John McCall351762c2011-02-07 10:33:21 +00003447 NumCaptures = end - begin;
3448
3449 // Avoid new Capture[] because we don't want to provide a default
3450 // constructor.
3451 size_t allocationSize = NumCaptures * sizeof(Capture);
3452 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3453 memcpy(buffer, begin, allocationSize);
3454 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003455}
Sebastian Redl833ef452010-01-26 22:01:41 +00003456
John McCallce45f882011-06-15 22:51:16 +00003457bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3458 for (capture_const_iterator
3459 i = capture_begin(), e = capture_end(); i != e; ++i)
3460 // Only auto vars can be captured, so no redeclaration worries.
3461 if (i->getVariable() == variable)
3462 return true;
3463
3464 return false;
3465}
3466
Douglas Gregor70226da2010-12-21 16:27:07 +00003467SourceRange BlockDecl::getSourceRange() const {
3468 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3469}
Sebastian Redl833ef452010-01-26 22:01:41 +00003470
3471//===----------------------------------------------------------------------===//
3472// Other Decl Allocation/Deallocation Method Implementations
3473//===----------------------------------------------------------------------===//
3474
David Blaikie68e081d2011-12-20 02:48:34 +00003475void TranslationUnitDecl::anchor() { }
3476
Sebastian Redl833ef452010-01-26 22:01:41 +00003477TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Richard Smithf7981722013-11-22 09:01:48 +00003478 return new (C, (DeclContext*)0) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003479}
3480
David Blaikie68e081d2011-12-20 02:48:34 +00003481void LabelDecl::anchor() { }
3482
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003483LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003484 SourceLocation IdentL, IdentifierInfo *II) {
Richard Smithf7981722013-11-22 09:01:48 +00003485 return new (C, DC) LabelDecl(DC, IdentL, II, 0, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003486}
3487
3488LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3489 SourceLocation IdentL, IdentifierInfo *II,
3490 SourceLocation GnuLabelL) {
3491 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Richard Smithf7981722013-11-22 09:01:48 +00003492 return new (C, DC) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003493}
3494
Douglas Gregor72172e92012-01-05 21:55:30 +00003495LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003496 return new (C, ID) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003497}
3498
David Blaikie68e081d2011-12-20 02:48:34 +00003499void ValueDecl::anchor() { }
3500
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003501bool ValueDecl::isWeak() const {
Aaron Ballman7dce1a82014-03-07 13:13:38 +00003502 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3503 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003504 return true;
3505
3506 return isWeakImported();
3507}
3508
David Blaikie68e081d2011-12-20 02:48:34 +00003509void ImplicitParamDecl::anchor() { }
3510
Sebastian Redl833ef452010-01-26 22:01:41 +00003511ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003512 SourceLocation IdLoc,
3513 IdentifierInfo *Id,
3514 QualType Type) {
Richard Smithf7981722013-11-22 09:01:48 +00003515 return new (C, DC) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003516}
3517
Richard Smithf7981722013-11-22 09:01:48 +00003518ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003519 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003520 return new (C, ID) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003521}
3522
Sebastian Redl833ef452010-01-26 22:01:41 +00003523FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003524 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003525 const DeclarationNameInfo &NameInfo,
3526 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003527 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003528 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003529 bool hasWrittenPrototype,
3530 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003531 FunctionDecl *New =
3532 new (C, DC) FunctionDecl(Function, DC, StartLoc, NameInfo, T, TInfo, SC,
3533 isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003534 New->HasWrittenPrototype = hasWrittenPrototype;
3535 return New;
3536}
3537
Douglas Gregor72172e92012-01-05 21:55:30 +00003538FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003539 return new (C, ID) FunctionDecl(Function, 0, SourceLocation(),
3540 DeclarationNameInfo(), QualType(), 0,
3541 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003542}
3543
Sebastian Redl833ef452010-01-26 22:01:41 +00003544BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003545 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003546}
3547
Douglas Gregor72172e92012-01-05 21:55:30 +00003548BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003549 return new (C, ID) BlockDecl(0, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003550}
3551
Ben Langmuir37943a72013-05-03 19:00:33 +00003552CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3553 unsigned NumParams) {
Richard Smithf7981722013-11-22 09:01:48 +00003554 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3555 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003556}
3557
Ben Langmuirce914fc2013-05-03 19:20:19 +00003558CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00003559 unsigned NumParams) {
3560 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3561 CapturedDecl(0, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00003562}
3563
Sebastian Redl833ef452010-01-26 22:01:41 +00003564EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3565 SourceLocation L,
3566 IdentifierInfo *Id, QualType T,
3567 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00003568 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00003569}
3570
Douglas Gregor72172e92012-01-05 21:55:30 +00003571EnumConstantDecl *
3572EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003573 return new (C, ID) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3574 llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00003575}
3576
David Blaikie68e081d2011-12-20 02:48:34 +00003577void IndirectFieldDecl::anchor() { }
3578
Benjamin Kramer39593702010-11-21 14:11:41 +00003579IndirectFieldDecl *
3580IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3581 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3582 unsigned CHS) {
Richard Smithf7981722013-11-22 09:01:48 +00003583 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003584}
3585
Douglas Gregor72172e92012-01-05 21:55:30 +00003586IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3587 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003588 return new (C, ID) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3589 QualType(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003590}
3591
Douglas Gregorbe996932010-09-01 20:41:53 +00003592SourceRange EnumConstantDecl::getSourceRange() const {
3593 SourceLocation End = getLocation();
3594 if (Init)
3595 End = Init->getLocEnd();
3596 return SourceRange(getLocation(), End);
3597}
3598
David Blaikie68e081d2011-12-20 02:48:34 +00003599void TypeDecl::anchor() { }
3600
Sebastian Redl833ef452010-01-26 22:01:41 +00003601TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003602 SourceLocation StartLoc, SourceLocation IdLoc,
3603 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smithf7981722013-11-22 09:01:48 +00003604 return new (C, DC) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003605}
3606
David Blaikie68e081d2011-12-20 02:48:34 +00003607void TypedefNameDecl::anchor() { }
3608
Douglas Gregor72172e92012-01-05 21:55:30 +00003609TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003610 return new (C, ID) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003611}
3612
Richard Smithdda56e42011-04-15 14:24:37 +00003613TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3614 SourceLocation StartLoc,
3615 SourceLocation IdLoc, IdentifierInfo *Id,
3616 TypeSourceInfo *TInfo) {
Richard Smithf7981722013-11-22 09:01:48 +00003617 return new (C, DC) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00003618}
3619
Douglas Gregor72172e92012-01-05 21:55:30 +00003620TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003621 return new (C, ID) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003622}
3623
Abramo Bagnaraea947882011-03-08 16:41:52 +00003624SourceRange TypedefDecl::getSourceRange() const {
3625 SourceLocation RangeEnd = getLocation();
3626 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3627 if (typeIsPostfix(TInfo->getType()))
3628 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3629 }
3630 return SourceRange(getLocStart(), RangeEnd);
3631}
3632
Richard Smithdda56e42011-04-15 14:24:37 +00003633SourceRange TypeAliasDecl::getSourceRange() const {
3634 SourceLocation RangeEnd = getLocStart();
3635 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3636 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3637 return SourceRange(getLocStart(), RangeEnd);
3638}
3639
David Blaikie68e081d2011-12-20 02:48:34 +00003640void FileScopeAsmDecl::anchor() { }
3641
Sebastian Redl833ef452010-01-26 22:01:41 +00003642FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003643 StringLiteral *Str,
3644 SourceLocation AsmLoc,
3645 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003646 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003647}
Douglas Gregorba345522011-12-02 23:23:56 +00003648
Richard Smithf7981722013-11-22 09:01:48 +00003649FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003650 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003651 return new (C, ID) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00003652}
3653
Michael Han84324352013-02-22 17:15:32 +00003654void EmptyDecl::anchor() {}
3655
3656EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003657 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00003658}
3659
3660EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003661 return new (C, ID) EmptyDecl(0, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00003662}
3663
Douglas Gregorba345522011-12-02 23:23:56 +00003664//===----------------------------------------------------------------------===//
3665// ImportDecl Implementation
3666//===----------------------------------------------------------------------===//
3667
3668/// \brief Retrieve the number of module identifiers needed to name the given
3669/// module.
3670static unsigned getNumModuleIdentifiers(Module *Mod) {
3671 unsigned Result = 1;
3672 while (Mod->Parent) {
3673 Mod = Mod->Parent;
3674 ++Result;
3675 }
3676 return Result;
3677}
3678
Douglas Gregor22d09742012-01-03 18:04:46 +00003679ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003680 Module *Imported,
3681 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003682 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003683 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003684{
3685 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3686 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3687 memcpy(StoredLocs, IdentifierLocs.data(),
3688 IdentifierLocs.size() * sizeof(SourceLocation));
3689}
3690
Douglas Gregor22d09742012-01-03 18:04:46 +00003691ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003692 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003693 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003694 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003695{
3696 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3697}
3698
Richard Smithf7981722013-11-22 09:01:48 +00003699ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003700 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003701 ArrayRef<SourceLocation> IdentifierLocs) {
Richard Smithf7981722013-11-22 09:01:48 +00003702 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3703 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003704}
3705
Richard Smithf7981722013-11-22 09:01:48 +00003706ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003707 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00003708 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003709 SourceLocation EndLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003710 ImportDecl *Import =
3711 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3712 Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003713 Import->setImplicit();
3714 return Import;
3715}
3716
Douglas Gregor72172e92012-01-05 21:55:30 +00003717ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3718 unsigned NumLocations) {
Richard Smithf7981722013-11-22 09:01:48 +00003719 return new (C, ID, NumLocations * sizeof(SourceLocation))
3720 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00003721}
3722
3723ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3724 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003725 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00003726
3727 const SourceLocation *StoredLocs
3728 = reinterpret_cast<const SourceLocation *>(this + 1);
3729 return ArrayRef<SourceLocation>(StoredLocs,
3730 getNumModuleIdentifiers(getImportedModule()));
3731}
3732
3733SourceRange ImportDecl::getSourceRange() const {
3734 if (!ImportedAndComplete.getInt())
3735 return SourceRange(getLocation(),
3736 *reinterpret_cast<const SourceLocation *>(this + 1));
3737
3738 return SourceRange(getLocation(), getIdentifierLocs().back());
3739}