blob: 628c9b053ea4cb07ea121074c3c837d020307694 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidise184bae2008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Reid Spencer5f016e22007-07-11 17:01:13 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattner6c2b6eb2008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070016#include "clang/AST/ASTLambda.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/Attr.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
Nuno Lopes99f06ba2008-12-17 23:39:55 +000022#include "clang/AST/Expr.h"
Anders Carlsson337cba42009-12-15 19:16:31 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregord249e1d1f2009-05-29 20:38:28 +000024#include "clang/AST/PrettyPrinter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000025#include "clang/AST/Stmt.h"
26#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000028#include "clang/Basic/IdentifierTable.h"
Douglas Gregor15de72c2011-12-02 23:23:56 +000029#include "clang/Basic/Module.h"
Abramo Bagnara465d41b2010-05-11 21:36:43 +000030#include "clang/Basic/Specifiers.h"
Douglas Gregor4421d2b2011-03-26 12:10:19 +000031#include "clang/Basic/TargetInfo.h"
Stephen Hines176edba2014-12-01 14:53:08 -080032#include "clang/Frontend/FrontendDiagnostic.h"
John McCallf1bbbb42009-09-04 01:14:41 +000033#include "llvm/Support/ErrorHandling.h"
David Blaikie4278c652011-09-21 18:16:56 +000034#include <algorithm>
35
Reid Spencer5f016e22007-07-11 17:01:13 +000036using namespace clang;
37
Richard Smith4ed01222013-10-07 08:02:11 +000038Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
40}
41
Stephen Hines176edba2014-12-01 14:53:08 -080042// Defined here so that it can be inlined into its direct callers.
43bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
45}
46
Chris Lattnerd3b90652008-03-15 05:43:15 +000047//===----------------------------------------------------------------------===//
Douglas Gregor4afa39d2009-01-20 01:17:11 +000048// NamedDecl Implementation
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000049//===----------------------------------------------------------------------===//
50
John McCall5a758de2013-02-16 00:17:33 +000051// Visibility rules aren't rigorously externally specified, but here
52// are the basic principles behind what we implement:
53//
54// 1. An explicit visibility attribute is generally a direct expression
55// of the user's intent and should be honored. Only the innermost
56// visibility attribute applies. If no visibility attribute applies,
57// global visibility settings are considered.
58//
59// 2. There is one caveat to the above: on or in a template pattern,
60// an explicit visibility attribute is just a default rule, and
61// visibility can be decreased by the visibility of template
62// arguments. But this, too, has an exception: an attribute on an
63// explicit specialization or instantiation causes all the visibility
64// restrictions of the template arguments to be ignored.
65//
66// 3. A variable that does not otherwise have explicit visibility can
67// be restricted by the visibility of its type.
68//
69// 4. A visibility restriction is explicit if it comes from an
70// attribute (or something like it), not a global visibility setting.
71// When emitting a reference to an external symbol, visibility
72// restrictions are ignored unless they are explicit.
John McCalld4c3d662013-02-20 01:54:26 +000073//
74// 5. When computing the visibility of a non-type, including a
75// non-type member of a class, only non-type visibility restrictions
76// are considered: the 'visibility' attribute, global value-visibility
77// settings, and a few special cases like __private_extern.
78//
79// 6. When computing the visibility of a type, including a type member
80// of a class, only type visibility restrictions are considered:
81// the 'type_visibility' attribute and global type-visibility settings.
82// However, a 'visibility' attribute counts as a 'type_visibility'
83// attribute on any declaration that only has the former.
84//
85// The visibility of a "secondary" entity, like a template argument,
86// is computed using the kind of that entity, not the kind of the
87// primary entity for which we are computing visibility. For example,
88// the visibility of a specialization of either of these templates:
89// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
90// template <class T, bool (&compare)(T, X)> class matcher;
91// is restricted according to the type visibility of the argument 'T',
92// the type visibility of 'bool(&)(T,X)', and the value visibility of
93// the argument function 'compare'. That 'has_match' is a value
94// and 'matcher' is a type only matters when looking for attributes
95// and settings from the immediate context.
John McCall5a758de2013-02-16 00:17:33 +000096
John McCall3892d022013-02-21 23:42:58 +000097const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindoladc070562013-05-28 19:43:11 +000098const unsigned IgnoreAllVisibilityBit = 4;
John McCall3892d022013-02-21 23:42:58 +000099
John McCall5a758de2013-02-16 00:17:33 +0000100/// Kinds of LV computation. The linkage side of the computation is
101/// always the same, but different things can change how visibility is
102/// computed.
103enum LVComputationKind {
John McCall3892d022013-02-21 23:42:58 +0000104 /// Do an LV computation for, ultimately, a type.
105 /// Visibility may be restricted by type visibility settings and
106 /// the visibility of template arguments.
John McCalld4c3d662013-02-20 01:54:26 +0000107 LVForType = NamedDecl::VisibilityForType,
John McCall5a758de2013-02-16 00:17:33 +0000108
John McCall3892d022013-02-21 23:42:58 +0000109 /// Do an LV computation for, ultimately, a non-type declaration.
110 /// Visibility may be restricted by value visibility settings and
111 /// the visibility of template arguments.
John McCalld4c3d662013-02-20 01:54:26 +0000112 LVForValue = NamedDecl::VisibilityForValue,
113
John McCall3892d022013-02-21 23:42:58 +0000114 /// Do an LV computation for, ultimately, a type that already has
115 /// some sort of explicit visibility. Visibility may only be
116 /// restricted by the visibility of template arguments.
117 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld4c3d662013-02-20 01:54:26 +0000118
John McCall3892d022013-02-21 23:42:58 +0000119 /// Do an LV computation for, ultimately, a non-type declaration
120 /// that already has some sort of explicit visibility. Visibility
121 /// may only be restricted by the visibility of template arguments.
Rafael Espindoladc070562013-05-28 19:43:11 +0000122 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
123
124 /// Do an LV computation when we only care about the linkage.
125 LVForLinkageOnly =
126 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCall5a758de2013-02-16 00:17:33 +0000127};
128
John McCalld4c3d662013-02-20 01:54:26 +0000129/// Does this computation kind permit us to consider additional
130/// visibility settings from attributes and the like?
131static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall3892d022013-02-21 23:42:58 +0000132 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld4c3d662013-02-20 01:54:26 +0000133}
134
135/// Given an LVComputationKind, return one of the same type/value sort
136/// that records that it already has explicit visibility.
137static LVComputationKind
138withExplicitVisibilityAlready(LVComputationKind oldKind) {
139 LVComputationKind newKind =
John McCall3892d022013-02-21 23:42:58 +0000140 static_cast<LVComputationKind>(unsigned(oldKind) |
141 IgnoreExplicitVisibilityBit);
John McCalld4c3d662013-02-20 01:54:26 +0000142 assert(oldKind != LVForType || newKind == LVForExplicitType);
143 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
144 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
145 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
146 return newKind;
147}
148
David Blaikiedc84cd52013-02-20 22:23:23 +0000149static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
150 LVComputationKind kind) {
John McCalld4c3d662013-02-20 01:54:26 +0000151 assert(!hasExplicitVisibilityAlready(kind) &&
152 "asking for explicit visibility when we shouldn't be");
153 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
154}
155
John McCall5a758de2013-02-16 00:17:33 +0000156/// Is the given declaration a "type" or a "value" for the purposes of
157/// visibility computation?
158static bool usesTypeVisibility(const NamedDecl *D) {
John McCalla880b192013-02-19 01:57:35 +0000159 return isa<TypeDecl>(D) ||
160 isa<ClassTemplateDecl>(D) ||
161 isa<ObjCInterfaceDecl>(D);
John McCall5a758de2013-02-16 00:17:33 +0000162}
163
John McCall3892d022013-02-21 23:42:58 +0000164/// Does the given declaration have member specialization information,
165/// and if so, is it an explicit specialization?
166template <class T> static typename
Stephen Hines651f13c2014-04-23 16:59:28 -0700167std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall3892d022013-02-21 23:42:58 +0000168isExplicitMemberSpecialization(const T *D) {
169 if (const MemberSpecializationInfo *member =
170 D->getMemberSpecializationInfo()) {
171 return member->isExplicitSpecialization();
172 }
173 return false;
174}
175
176/// For templates, this question is easier: a member template can't be
177/// explicitly instantiated, so there's a single bit indicating whether
178/// or not this is an explicit member specialization.
179static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
180 return D->isMemberSpecialization();
181}
182
John McCalld4c3d662013-02-20 01:54:26 +0000183/// Given a visibility attribute, return the explicit visibility
184/// associated with it.
185template <class T>
186static Visibility getVisibilityFromAttr(const T *attr) {
187 switch (attr->getVisibility()) {
188 case T::Default:
189 return DefaultVisibility;
190 case T::Hidden:
191 return HiddenVisibility;
192 case T::Protected:
193 return ProtectedVisibility;
194 }
195 llvm_unreachable("bad visibility kind");
196}
197
John McCall5a758de2013-02-16 00:17:33 +0000198/// Return the explicit visibility of the given declaration.
David Blaikiedc84cd52013-02-20 22:23:23 +0000199static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld4c3d662013-02-20 01:54:26 +0000200 NamedDecl::ExplicitVisibilityKind kind) {
201 // If we're ultimately computing the visibility of a type, look for
202 // a 'type_visibility' attribute before looking for 'visibility'.
203 if (kind == NamedDecl::VisibilityForType) {
204 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
205 return getVisibilityFromAttr(A);
206 }
207 }
208
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000209 // If this declaration has an explicit visibility attribute, use it.
210 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld4c3d662013-02-20 01:54:26 +0000211 return getVisibilityFromAttr(A);
John McCall1fb0caa2010-10-22 21:05:15 +0000212 }
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000213
214 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
215 // implies visibility(default).
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000216 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700217 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
218 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000219 return DefaultVisibility;
220 }
221
David Blaikie66874fb2013-02-21 01:47:18 +0000222 return None;
John McCall1fb0caa2010-10-22 21:05:15 +0000223}
224
Rafael Espindola74caf012013-05-29 04:55:30 +0000225static LinkageInfo
226getLVForType(const Type &T, LVComputationKind computation) {
227 if (computation == LVForLinkageOnly)
228 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
229 return T.getLinkageAndVisibility();
230}
231
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000232/// \brief Get the most restrictive linkage for the types in the given
John McCall5a758de2013-02-16 00:17:33 +0000233/// template parameter list. For visibility purposes, template
234/// parameters are part of the signature of a template.
Rafael Espindola093ecc92012-01-14 00:30:36 +0000235static LinkageInfo
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700236getLVForTemplateParameterList(const TemplateParameterList *Params,
Rafael Espindola74caf012013-05-29 04:55:30 +0000237 LVComputationKind computation) {
John McCall5a758de2013-02-16 00:17:33 +0000238 LinkageInfo LV;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700239 for (const NamedDecl *P : *Params) {
John McCall5a758de2013-02-16 00:17:33 +0000240 // Template type parameters are the most common and never
241 // contribute to visibility, pack or not.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700242 if (isa<TemplateTypeParmDecl>(P))
John McCall5a758de2013-02-16 00:17:33 +0000243 continue;
244
245 // Non-type template parameters can be restricted by the value type, e.g.
246 // template <enum X> class A { ... };
247 // We have to be careful here, though, because we can be dealing with
248 // dependent types.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700249 if (const NonTypeTemplateParmDecl *NTTP =
250 dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCall5a758de2013-02-16 00:17:33 +0000251 // Handle the non-pack case first.
252 if (!NTTP->isExpandedParameterPack()) {
253 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola74caf012013-05-29 04:55:30 +0000254 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000255 }
256 continue;
257 }
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000258
John McCall5a758de2013-02-16 00:17:33 +0000259 // Look at all the types in an expanded pack.
260 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
261 QualType type = NTTP->getExpansionType(i);
262 if (!type->isDependentType())
Rafael Espindola18895dc2013-02-27 02:27:19 +0000263 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000264 }
John McCall5a758de2013-02-16 00:17:33 +0000265 continue;
Douglas Gregor6952f1e2011-01-19 20:10:05 +0000266 }
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000267
John McCall5a758de2013-02-16 00:17:33 +0000268 // Template template parameters can be restricted by their
269 // template parameters, recursively.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700270 const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
John McCall5a758de2013-02-16 00:17:33 +0000271
272 // Handle the non-pack case first.
273 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola74caf012013-05-29 04:55:30 +0000274 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
275 computation));
John McCall5a758de2013-02-16 00:17:33 +0000276 continue;
277 }
278
279 // Look at all expansions in an expanded pack.
280 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
281 i != n; ++i) {
282 LV.merge(getLVForTemplateParameterList(
Rafael Espindola74caf012013-05-29 04:55:30 +0000283 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000284 }
285 }
286
John McCall1fb0caa2010-10-22 21:05:15 +0000287 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000288}
289
Rafael Espindola838dc592013-01-12 06:42:30 +0000290/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCall5a758de2013-02-16 00:17:33 +0000291static LinkageInfo getLVForDecl(const NamedDecl *D,
292 LVComputationKind computation);
Douglas Gregor381d34e2010-12-06 18:36:25 +0000293
Eli Friedman07369dd2013-07-01 20:22:57 +0000294static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700295 const Decl *Ret = nullptr;
Rafael Espindola1229e202013-05-16 04:30:21 +0000296 const DeclContext *DC = D->getDeclContext();
297 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman07369dd2013-07-01 20:22:57 +0000298 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
299 Ret = cast<Decl>(DC);
Rafael Espindola1229e202013-05-16 04:30:21 +0000300 DC = DC->getParent();
301 }
302 return Ret;
303}
304
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000305/// \brief Get the most restrictive linkage for the types and
306/// declarations in the given template argument list.
John McCall5a758de2013-02-16 00:17:33 +0000307///
308/// Note that we don't take an LVComputationKind because we always
309/// want to honor the visibility of template arguments in the same way.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700310static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
311 LVComputationKind computation) {
John McCall5a758de2013-02-16 00:17:33 +0000312 LinkageInfo LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000313
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700314 for (const TemplateArgument &Arg : Args) {
315 switch (Arg.getKind()) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000316 case TemplateArgument::Null:
317 case TemplateArgument::Integral:
318 case TemplateArgument::Expression:
John McCall5a758de2013-02-16 00:17:33 +0000319 continue;
Rafael Espindolab5d763d2012-01-02 06:26:22 +0000320
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000321 case TemplateArgument::Type:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700322 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCall5a758de2013-02-16 00:17:33 +0000323 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000324
325 case TemplateArgument::Declaration:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700326 if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCall5a758de2013-02-16 00:17:33 +0000327 assert(!usesTypeVisibility(ND));
Rafael Espindola74caf012013-05-29 04:55:30 +0000328 LV.merge(getLVForDecl(ND, computation));
John McCall5a758de2013-02-16 00:17:33 +0000329 }
330 continue;
Eli Friedmand7a6b162012-09-26 02:36:12 +0000331
332 case TemplateArgument::NullPtr:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700333 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
John McCall5a758de2013-02-16 00:17:33 +0000334 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000335
336 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +0000337 case TemplateArgument::TemplateExpansion:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700338 if (TemplateDecl *Template =
339 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindola74caf012013-05-29 04:55:30 +0000340 LV.merge(getLVForDecl(Template, computation));
John McCall5a758de2013-02-16 00:17:33 +0000341 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000342
343 case TemplateArgument::Pack:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700344 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCall5a758de2013-02-16 00:17:33 +0000345 continue;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000346 }
John McCall5a758de2013-02-16 00:17:33 +0000347 llvm_unreachable("bad template argument kind");
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000348 }
349
John McCall1fb0caa2010-10-22 21:05:15 +0000350 return LV;
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000351}
352
Rafael Espindola093ecc92012-01-14 00:30:36 +0000353static LinkageInfo
Rafael Espindola74caf012013-05-29 04:55:30 +0000354getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
355 LVComputationKind computation) {
356 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall3cdfc4d2010-08-13 08:35:10 +0000357}
358
John McCall3892d022013-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 McCall5a758de2013-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 McCall3892d022013-02-21 23:42:58 +0000376///
NAKAMURA Takumid9bd83e2013-02-22 04:06:28 +0000377/// \param[out] LV the computation to use for the parent
John McCall3892d022013-02-21 23:42:58 +0000378static void
379mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindola74caf012013-05-29 04:55:30 +0000380 const FunctionTemplateSpecializationInfo *specInfo,
381 LVComputationKind computation) {
John McCall3892d022013-02-21 23:42:58 +0000382 bool considerVisibility =
383 shouldConsiderTemplateVisibility(fn, specInfo);
John McCall5a758de2013-02-16 00:17:33 +0000384
385 // Merge information from the template parameters.
John McCall3892d022013-02-21 23:42:58 +0000386 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCall5a758de2013-02-16 00:17:33 +0000387 LinkageInfo tempLV =
Rafael Espindola74caf012013-05-29 04:55:30 +0000388 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCall5a758de2013-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 Espindola74caf012013-05-29 04:55:30 +0000393 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCall5a758de2013-02-16 00:17:33 +0000394 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCall6ce51ee2011-06-27 23:06:04 +0000395}
396
John McCall3892d022013-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 Espindoladc070562013-05-28 19:43:11 +0000412 case LVForLinkageOnly:
413 return false;
John McCall3892d022013-02-21 23:42:58 +0000414 }
415 llvm_unreachable("bad visibility computation kind");
416}
417
John McCalld4c3d662013-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 McCall5a758de2013-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 McCalld4c3d662013-02-20 01:54:26 +0000429 // for an explicit specialization when computing the visibility of a
430 // member thereof with explicit visibility.
John McCall5a758de2013-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 McCalld4c3d662013-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 McCall3892d022013-02-21 23:42:58 +0000451 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld4c3d662013-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 McCall5a758de2013-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 McCalld4c3d662013-02-20 01:54:26 +0000464 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCall5a758de2013-02-16 00:17:33 +0000465 LinkageInfo tempLV =
Rafael Espindola74caf012013-05-29 04:55:30 +0000466 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCall5a758de2013-02-16 00:17:33 +0000467 LV.mergeMaybeWithVisibility(tempLV,
John McCalld4c3d662013-02-20 01:54:26 +0000468 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCall5a758de2013-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 Espindola74caf012013-05-29 04:55:30 +0000474 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindolae9808902013-05-30 21:23:15 +0000475 if (considerVisibility)
476 LV.mergeVisibility(argsLV);
477 LV.mergeExternalVisibility(argsLV);
John McCall6ce51ee2011-06-27 23:06:04 +0000478}
479
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700480/// Should we consider visibility associated with the template
481/// arguments and parameters of the given variable template
482/// specialization? As usual, follow class template specialization
483/// logic up to initialization.
484static bool shouldConsiderTemplateVisibility(
485 const VarTemplateSpecializationDecl *spec,
486 LVComputationKind computation) {
487 // Include visibility from the template parameters and arguments
488 // only if this is not an explicit instantiation or specialization
489 // with direct explicit visibility (and note that implicit
490 // instantiations won't have a direct attribute).
491 if (!spec->isExplicitInstantiationOrSpecialization())
492 return true;
493
494 // An explicit variable specialization is an independent, top-level
495 // declaration. As such, if it has an explicit visibility attribute,
496 // that must directly express the user's intent, and we should honor
497 // it.
498 if (spec->isExplicitSpecialization() &&
499 hasExplicitVisibilityAlready(computation))
500 return false;
501
502 return !hasDirectVisibilityAttribute(spec, computation);
503}
504
505/// Merge in template-related linkage and visibility for the given
506/// variable template specialization. As usual, follow class template
507/// specialization logic up to initialization.
508static void mergeTemplateLV(LinkageInfo &LV,
509 const VarTemplateSpecializationDecl *spec,
510 LVComputationKind computation) {
511 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
512
513 // Merge information from the template parameters, but ignore
514 // visibility if we're only considering template arguments.
515
516 VarTemplateDecl *temp = spec->getSpecializedTemplate();
517 LinkageInfo tempLV =
518 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
519 LV.mergeMaybeWithVisibility(tempLV,
520 considerVisibility && !hasExplicitVisibilityAlready(computation));
521
522 // Merge information from the template arguments. We ignore
523 // template-argument visibility if we've got an explicit
524 // instantiation with a visibility attribute.
525 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
526 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
527 if (considerVisibility)
528 LV.mergeVisibility(argsLV);
529 LV.mergeExternalVisibility(argsLV);
530}
531
Rafael Espindolab04b7312012-07-13 14:25:36 +0000532static bool useInlineVisibilityHidden(const NamedDecl *D) {
533 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola0bab9da2012-07-13 23:26:43 +0000534 const LangOptions &Opts = D->getASTContext().getLangOpts();
535 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolab04b7312012-07-13 14:25:36 +0000536 return false;
537
538 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
539 if (!FD)
540 return false;
541
542 TemplateSpecializationKind TSK = TSK_Undeclared;
543 if (FunctionTemplateSpecializationInfo *spec
544 = FD->getTemplateSpecializationInfo()) {
545 TSK = spec->getTemplateSpecializationKind();
546 } else if (MemberSpecializationInfo *MSI =
547 FD->getMemberSpecializationInfo()) {
548 TSK = MSI->getTemplateSpecializationKind();
549 }
550
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700551 const FunctionDecl *Def = nullptr;
Rafael Espindolab04b7312012-07-13 14:25:36 +0000552 // InlineVisibilityHidden only applies to definitions, and
553 // isInlined() only gives meaningful answers on definitions
554 // anyway.
555 return TSK != TSK_ExplicitInstantiationDeclaration &&
556 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindola0142f0c2012-10-11 16:32:25 +0000557 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolab04b7312012-07-13 14:25:36 +0000558}
559
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +0000560template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindolabc650912013-10-17 15:37:26 +0000561 const T *First = D->getFirstDecl();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +0000562 return First->isInExternCContext();
Rafael Espindola950fee22013-02-14 01:18:37 +0000563}
564
Stephen Hines651f13c2014-04-23 16:59:28 -0700565static bool isSingleLineLanguageLinkage(const Decl &D) {
Rafael Espindolae5e575d2013-04-26 01:30:23 +0000566 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Stephen Hines651f13c2014-04-23 16:59:28 -0700567 if (!SD->hasBraces())
Rafael Espindolae5e575d2013-04-26 01:30:23 +0000568 return true;
569 return false;
570}
571
Rafael Espindola1266b612012-04-21 23:28:21 +0000572static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCall5a758de2013-02-16 00:17:33 +0000573 LVComputationKind computation) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000574 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregord85b5b92009-11-25 22:24:25 +0000575 "Not a name having namespace scope");
576 ASTContext &Context = D->getASTContext();
577
578 // C++ [basic.link]p3:
579 // A name having namespace scope (3.3.6) has internal linkage if it
580 // is the name of
581 // - an object, reference, function or function template that is
582 // explicitly declared static; or,
583 // (This bullet corresponds to C99 6.2.2p3.)
584 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
585 // Explicitly declared static.
John McCalld931b082010-08-26 03:08:43 +0000586 if (Var->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000587 return LinkageInfo::internal();
Douglas Gregord85b5b92009-11-25 22:24:25 +0000588
Richard Smith820e9a72012-10-19 06:37:48 +0000589 // - a non-volatile object or reference that is explicitly declared const
590 // or constexpr and neither explicitly declared extern nor previously
591 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikie4e4d0842012-03-11 07:00:24 +0000592 if (Context.getLangOpts().CPlusPlus &&
Richard Smith820e9a72012-10-19 06:37:48 +0000593 Var->getType().isConstQualified() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000594 !Var->getType().isVolatileQualified()) {
Rafael Espindola4f8a3eb2013-04-03 19:22:20 +0000595 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola4f8a3eb2013-04-03 19:22:20 +0000596 if (PrevVar)
Rafael Espindola74caf012013-05-29 04:55:30 +0000597 return getLVForDecl(PrevVar, computation);
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000598
599 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindolae5e575d2013-04-26 01:30:23 +0000600 Var->getStorageClass() != SC_PrivateExtern &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700601 !isSingleLineLanguageLinkage(*Var))
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000602 return LinkageInfo::internal();
603 }
604
605 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
606 PrevVar = PrevVar->getPreviousDecl()) {
607 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
608 Var->getStorageClass() == SC_None)
609 return PrevVar->getLinkageAndVisibility();
610 // Explicitly declared static.
611 if (PrevVar->getStorageClass() == SC_Static)
612 return LinkageInfo::internal();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000613 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700614 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000615 // C++ [temp]p4:
616 // A non-member function template can have internal linkage; any
617 // other template name shall have external linkage.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000618
619 // Explicitly declared static.
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000620 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallaf146032010-10-30 11:50:40 +0000621 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700622 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
623 // - a data member of an anonymous union.
624 const VarDecl *VD = IFD->getVarDecl();
625 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
626 return getLVForNamespaceScopeDecl(VD, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000627 }
David Majnemer885d8bf2013-10-23 20:52:43 +0000628 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregord85b5b92009-11-25 22:24:25 +0000629
Chandler Carruth094b6432011-02-24 19:03:39 +0000630 if (D->isInAnonymousNamespace()) {
631 const VarDecl *Var = dyn_cast<VarDecl>(D);
632 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +0000633 if ((!Var || !isFirstInExternCContext(Var)) &&
634 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth094b6432011-02-24 19:03:39 +0000635 return LinkageInfo::uniqueExternal();
636 }
John McCalle7bc9722010-10-28 04:18:25 +0000637
John McCall1fb0caa2010-10-22 21:05:15 +0000638 // Set up the defaults.
639
640 // C99 6.2.2p5:
641 // If the declaration of an identifier for an object has file
642 // scope and no storage-class specifier, its linkage is
643 // external.
John McCallaf146032010-10-30 11:50:40 +0000644 LinkageInfo LV;
645
John McCalld4c3d662013-02-20 01:54:26 +0000646 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000647 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola5727cf52012-04-19 02:22:07 +0000648 LV.mergeVisibility(*Vis, true);
Rafael Espindolae9836a22012-04-16 18:46:26 +0000649 } else {
650 // If we're declared in a namespace with a visibility attribute,
John McCall5a758de2013-02-16 00:17:33 +0000651 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindolae9836a22012-04-16 18:46:26 +0000652 for (const DeclContext *DC = D->getDeclContext();
653 !isa<TranslationUnitDecl>(DC);
654 DC = DC->getParent()) {
655 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
656 if (!ND) continue;
David Blaikiedc84cd52013-02-20 22:23:23 +0000657 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola5727cf52012-04-19 02:22:07 +0000658 LV.mergeVisibility(*Vis, true);
Rafael Espindolae9836a22012-04-16 18:46:26 +0000659 break;
660 }
661 }
662 }
Rafael Espindolae9836a22012-04-16 18:46:26 +0000663
John McCall5a758de2013-02-16 00:17:33 +0000664 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000665 if (!LV.isVisibilityExplicit()) {
John McCalla880b192013-02-19 01:57:35 +0000666 // Use global type/value visibility as appropriate.
667 Visibility globalVisibility;
668 if (computation == LVForValue) {
669 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
670 } else {
671 assert(computation == LVForType);
672 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
673 }
674 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCall5a758de2013-02-16 00:17:33 +0000675
676 // If we're paying attention to global visibility, apply
677 // -finline-visibility-hidden if this is an inline method.
678 if (useInlineVisibilityHidden(D))
679 LV.mergeVisibility(HiddenVisibility, true);
680 }
Rafael Espindolab04b7312012-07-13 14:25:36 +0000681 }
Rafael Espindolaff257982012-04-19 02:55:01 +0000682
Douglas Gregord85b5b92009-11-25 22:24:25 +0000683 // C++ [basic.link]p4:
John McCall1fb0caa2010-10-22 21:05:15 +0000684
Douglas Gregord85b5b92009-11-25 22:24:25 +0000685 // A name having namespace scope has external linkage if it is the
686 // name of
687 //
688 // - an object or reference, unless it has internal linkage; or
689 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall110e8e52010-10-29 22:22:43 +0000690 // GCC applies the following optimization to variables and static
691 // data members, but not to functions:
692 //
John McCall1fb0caa2010-10-22 21:05:15 +0000693 // Modify the variable's LV by the LV of its type unless this is
694 // C or extern "C". This follows from [basic.link]p9:
695 // A type without linkage shall not be used as the type of a
696 // variable or function with external linkage unless
697 // - the entity has C language linkage, or
698 // - the entity is declared within an unnamed namespace, or
699 // - the entity is not used or is defined in the same
700 // translation unit.
701 // and [basic.link]p10:
702 // ...the types specified by all declarations referring to a
703 // given variable or function shall be identical...
704 // C does not have an equivalent rule.
705 //
John McCallac65c622010-10-26 04:59:26 +0000706 // Ignore this if we've got an explicit attribute; the user
707 // probably knows what they're doing.
708 //
John McCall1fb0caa2010-10-22 21:05:15 +0000709 // Note that we don't want to make the variable non-external
710 // because of this, but unique-external linkage suits us.
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +0000711 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindola74caf012013-05-29 04:55:30 +0000712 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000713 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000714 return LinkageInfo::uniqueExternal();
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000715 if (!LV.isVisibilityExplicit())
John McCall5a758de2013-02-16 00:17:33 +0000716 LV.mergeVisibility(TypeLV);
John McCall110e8e52010-10-29 22:22:43 +0000717 }
718
John McCall35cebc32010-11-02 18:38:13 +0000719 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola5727cf52012-04-19 02:22:07 +0000720 LV.mergeVisibility(HiddenVisibility, true);
John McCall35cebc32010-11-02 18:38:13 +0000721
Rafael Espindola538fb982012-11-12 04:10:23 +0000722 // Note that Sema::MergeVarDecl already takes care of implementing
723 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
724 // to do it here.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000725
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700726 // As per function and class template specializations (below),
727 // consider LV for the template and template arguments. We're at file
728 // scope, so we do not need to worry about nested specializations.
729 if (const VarTemplateSpecializationDecl *spec
730 = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
731 mergeTemplateLV(LV, spec, computation);
732 }
733
Douglas Gregord85b5b92009-11-25 22:24:25 +0000734 // - a function, unless it has internal linkage; or
John McCall1fb0caa2010-10-22 21:05:15 +0000735 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall67fa6d52010-10-28 07:07:52 +0000736 // In theory, we can modify the function's LV by the LV of its
737 // type unless it has C linkage (see comment above about variables
738 // for justification). In practice, GCC doesn't do this, so it's
739 // just too painful to make work.
John McCall1fb0caa2010-10-22 21:05:15 +0000740
John McCall35cebc32010-11-02 18:38:13 +0000741 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola5727cf52012-04-19 02:22:07 +0000742 LV.mergeVisibility(HiddenVisibility, true);
John McCall35cebc32010-11-02 18:38:13 +0000743
Rafael Espindola51758612012-11-21 02:47:19 +0000744 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
745 // merging storage classes and visibility attributes, so we don't have to
746 // look at previous decls in here.
Douglas Gregord85b5b92009-11-25 22:24:25 +0000747
John McCallaf8ca372011-02-10 06:50:24 +0000748 // In C++, then if the type of the function uses a type with
749 // unique-external linkage, it's not legally usable from outside
750 // this translation unit. However, we should use the C linkage
751 // rules instead for extern "C" declarations.
David Blaikie4e4d0842012-03-11 07:00:24 +0000752 if (Context.getLangOpts().CPlusPlus &&
Richard Smithd248e582013-05-12 23:17:59 +0000753 !Function->isInExternCContext()) {
754 // Only look at the type-as-written. If this function has an auto-deduced
755 // return type, we can't compute the linkage of that type because it could
756 // require looking at the linkage of this function, and we don't need this
757 // for correctness because the type is not part of the function's
758 // signature.
Faisal Valiffc63a82013-10-08 04:15:04 +0000759 // FIXME: This is a hack. We should be able to solve this circularity and
760 // the one in getLVForClassMember for Functions some other way.
Richard Smithd248e582013-05-12 23:17:59 +0000761 QualType TypeAsWritten = Function->getType();
762 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
763 TypeAsWritten = TSI->getType();
764 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
765 return LinkageInfo::uniqueExternal();
766 }
John McCallaf8ca372011-02-10 06:50:24 +0000767
John McCall3892d022013-02-21 23:42:58 +0000768 // Consider LV from the template and the template arguments.
769 // We're at file scope, so we do not need to worry about nested
770 // specializations.
John McCall6ce51ee2011-06-27 23:06:04 +0000771 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000772 = Function->getTemplateSpecializationInfo()) {
Rafael Espindola74caf012013-05-29 04:55:30 +0000773 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000774 }
775
Douglas Gregord85b5b92009-11-25 22:24:25 +0000776 // - a named class (Clause 9), or an unnamed class defined in a
777 // typedef declaration in which the class has the typedef name
778 // for linkage purposes (7.1.3); or
779 // - a named enumeration (7.2), or an unnamed enumeration
780 // defined in a typedef declaration in which the enumeration
781 // has the typedef name for linkage purposes (7.1.3); or
John McCall1fb0caa2010-10-22 21:05:15 +0000782 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
783 // Unnamed tags have no linkage.
John McCall83972f12013-03-09 00:54:27 +0000784 if (!Tag->hasNameForLinkage())
John McCallaf146032010-10-30 11:50:40 +0000785 return LinkageInfo::none();
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000786
John McCall1fb0caa2010-10-22 21:05:15 +0000787 // If this is a class template specialization, consider the
John McCall3892d022013-02-21 23:42:58 +0000788 // linkage of the template and template arguments. We're at file
789 // scope, so we do not need to worry about nested specializations.
John McCall6ce51ee2011-06-27 23:06:04 +0000790 if (const ClassTemplateSpecializationDecl *spec
John McCall1fb0caa2010-10-22 21:05:15 +0000791 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCall5a758de2013-02-16 00:17:33 +0000792 mergeTemplateLV(LV, spec, computation);
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +0000793 }
Douglas Gregord85b5b92009-11-25 22:24:25 +0000794
795 // - an enumerator belonging to an enumeration with external linkage;
John McCall1fb0caa2010-10-22 21:05:15 +0000796 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola1266b612012-04-21 23:28:21 +0000797 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCall5a758de2013-02-16 00:17:33 +0000798 computation);
Rafael Espindola88ce12a2013-05-27 14:14:42 +0000799 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallaf146032010-10-30 11:50:40 +0000800 return LinkageInfo::none();
801 LV.merge(EnumLV);
Douglas Gregord85b5b92009-11-25 22:24:25 +0000802
803 // - a template, unless it is a function template that has
804 // internal linkage (Clause 14);
John McCall1a0918a2011-03-04 10:39:25 +0000805 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld4c3d662013-02-20 01:54:26 +0000806 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCall5a758de2013-02-16 00:17:33 +0000807 LinkageInfo tempLV =
Rafael Espindola74caf012013-05-29 04:55:30 +0000808 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCall5a758de2013-02-16 00:17:33 +0000809 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
810
Douglas Gregord85b5b92009-11-25 22:24:25 +0000811 // - a namespace (7.3), unless it is declared within an unnamed
812 // namespace.
John McCall1fb0caa2010-10-22 21:05:15 +0000813 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
814 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000815
John McCall1fb0caa2010-10-22 21:05:15 +0000816 // By extension, we assign external linkage to Objective-C
817 // interfaces.
818 } else if (isa<ObjCInterfaceDecl>(D)) {
819 // fallout
820
821 // Everything not covered here has no linkage.
822 } else {
Stephen Hines176edba2014-12-01 14:53:08 -0800823 // FIXME: A typedef declaration has linkage if it gives a type a name for
824 // linkage purposes.
John McCallaf146032010-10-30 11:50:40 +0000825 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +0000826 }
827
828 // If we ended up with non-external linkage, visibility should
829 // always be default.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000830 if (LV.getLinkage() != ExternalLinkage)
831 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall1fb0caa2010-10-22 21:05:15 +0000832
John McCall1fb0caa2010-10-22 21:05:15 +0000833 return LV;
Douglas Gregord85b5b92009-11-25 22:24:25 +0000834}
835
John McCall5a758de2013-02-16 00:17:33 +0000836static LinkageInfo getLVForClassMember(const NamedDecl *D,
837 LVComputationKind computation) {
John McCall1fb0caa2010-10-22 21:05:15 +0000838 // Only certain class members have linkage. Note that fields don't
839 // really have linkage, but it's convenient to say they do for the
840 // purposes of calculating linkage of pointer-to-data-member
841 // template arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -0700842 //
843 // Templates also don't officially have linkage, but since we ignore
844 // the C++ standard and look at template arguments when determining
845 // linkage and visibility of a template specialization, we might hit
846 // a template template argument that way. If we do, we need to
847 // consider its linkage.
John McCall3cdfc4d2010-08-13 08:35:10 +0000848 if (!(isa<CXXMethodDecl>(D) ||
849 isa<VarDecl>(D) ||
John McCall1fb0caa2010-10-22 21:05:15 +0000850 isa<FieldDecl>(D) ||
David Majnemer885d8bf2013-10-23 20:52:43 +0000851 isa<IndirectFieldDecl>(D) ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700852 isa<TagDecl>(D) ||
853 isa<TemplateDecl>(D)))
John McCallaf146032010-10-30 11:50:40 +0000854 return LinkageInfo::none();
John McCall3cdfc4d2010-08-13 08:35:10 +0000855
John McCall36987482010-11-02 01:45:15 +0000856 LinkageInfo LV;
857
John McCall36987482010-11-02 01:45:15 +0000858 // If we have an explicit visibility attribute, merge that in.
John McCalld4c3d662013-02-20 01:54:26 +0000859 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000860 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000861 LV.mergeVisibility(*Vis, true);
Rafael Espindolab04b7312012-07-13 14:25:36 +0000862 // If we're paying attention to global visibility, apply
863 // -finline-visibility-hidden if this is an inline method.
864 //
865 // Note that we do this before merging information about
866 // the class visibility.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000867 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolab04b7312012-07-13 14:25:36 +0000868 LV.mergeVisibility(HiddenVisibility, true);
John McCall36987482010-11-02 01:45:15 +0000869 }
Rafael Espindolac7e60602012-04-19 05:50:08 +0000870
871 // If this class member has an explicit visibility attribute, the only
872 // thing that can change its visibility is the template arguments, so
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000873 // only look for them when processing the class.
John McCalld4c3d662013-02-20 01:54:26 +0000874 LVComputationKind classComputation = computation;
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000875 if (LV.isVisibilityExplicit())
John McCalld4c3d662013-02-20 01:54:26 +0000876 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola0f905902012-04-16 18:25:01 +0000877
John McCall3892d022013-02-21 23:42:58 +0000878 LinkageInfo classLV =
879 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall3cdfc4d2010-08-13 08:35:10 +0000880 // If the class already has unique-external linkage, we can't improve.
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000881 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallaf146032010-10-30 11:50:40 +0000882 return LinkageInfo::uniqueExternal();
John McCall3cdfc4d2010-08-13 08:35:10 +0000883
Rafael Espindolae8328542013-05-28 02:22:10 +0000884 if (!isExternallyVisible(classLV.getLinkage()))
885 return LinkageInfo::none();
886
887
John McCall3892d022013-02-21 23:42:58 +0000888 // Otherwise, don't merge in classLV yet, because in certain cases
889 // we need to completely ignore the visibility from it.
890
891 // Specifically, if this decl exists and has an explicit attribute.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700892 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall3892d022013-02-21 23:42:58 +0000893
John McCall3cdfc4d2010-08-13 08:35:10 +0000894 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallaf8ca372011-02-10 06:50:24 +0000895 // If the type of the function uses a type with unique-external
896 // linkage, it's not legally usable from outside this translation unit.
Faisal Valiffc63a82013-10-08 04:15:04 +0000897 // But only look at the type-as-written. If this function has an auto-deduced
898 // return type, we can't compute the linkage of that type because it could
899 // require looking at the linkage of this function, and we don't need this
900 // for correctness because the type is not part of the function's
901 // signature.
902 // FIXME: This is a hack. We should be able to solve this circularity and the
903 // one in getLVForNamespaceScopeDecl for Functions some other way.
904 {
905 QualType TypeAsWritten = MD->getType();
906 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
907 TypeAsWritten = TSI->getType();
908 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
909 return LinkageInfo::uniqueExternal();
910 }
John McCall1fb0caa2010-10-22 21:05:15 +0000911 // If this is a method template specialization, use the linkage for
912 // the template parameters and arguments.
John McCall6ce51ee2011-06-27 23:06:04 +0000913 if (FunctionTemplateSpecializationInfo *spec
John McCall3cdfc4d2010-08-13 08:35:10 +0000914 = MD->getTemplateSpecializationInfo()) {
Rafael Espindola74caf012013-05-29 04:55:30 +0000915 mergeTemplateLV(LV, MD, spec, computation);
John McCall3892d022013-02-21 23:42:58 +0000916 if (spec->isExplicitSpecialization()) {
917 explicitSpecSuppressor = MD;
918 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
919 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
920 }
921 } else if (isExplicitMemberSpecialization(MD)) {
922 explicitSpecSuppressor = MD;
John McCall66cbcf32010-11-01 01:29:57 +0000923 }
John McCall1fb0caa2010-10-22 21:05:15 +0000924
John McCall110e8e52010-10-29 22:22:43 +0000925 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCall6ce51ee2011-06-27 23:06:04 +0000926 if (const ClassTemplateSpecializationDecl *spec
John McCall110e8e52010-10-29 22:22:43 +0000927 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCall5a758de2013-02-16 00:17:33 +0000928 mergeTemplateLV(LV, spec, computation);
John McCall3892d022013-02-21 23:42:58 +0000929 if (spec->isExplicitSpecialization()) {
930 explicitSpecSuppressor = spec;
931 } else {
932 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
933 if (isExplicitMemberSpecialization(temp)) {
934 explicitSpecSuppressor = temp->getTemplatedDecl();
935 }
936 }
937 } else if (isExplicitMemberSpecialization(RD)) {
938 explicitSpecSuppressor = RD;
John McCall110e8e52010-10-29 22:22:43 +0000939 }
940
John McCall110e8e52010-10-29 22:22:43 +0000941 // Static data members.
942 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700943 if (const VarTemplateSpecializationDecl *spec
944 = dyn_cast<VarTemplateSpecializationDecl>(VD))
945 mergeTemplateLV(LV, spec, computation);
946
John McCallee301022010-10-30 09:18:49 +0000947 // Modify the variable's linkage by its type, but ignore the
948 // type's visibility unless it's a definition.
Rafael Espindola74caf012013-05-29 04:55:30 +0000949 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindolae9808902013-05-30 21:23:15 +0000950 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
951 LV.mergeVisibility(typeLV);
952 LV.mergeExternalVisibility(typeLV);
John McCall3892d022013-02-21 23:42:58 +0000953
954 if (isExplicitMemberSpecialization(VD)) {
955 explicitSpecSuppressor = VD;
956 }
John McCall5a758de2013-02-16 00:17:33 +0000957
958 // Template members.
959 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
960 bool considerVisibility =
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000961 (!LV.isVisibilityExplicit() &&
962 !classLV.isVisibilityExplicit() &&
John McCalld4c3d662013-02-20 01:54:26 +0000963 !hasExplicitVisibilityAlready(computation));
John McCall5a758de2013-02-16 00:17:33 +0000964 LinkageInfo tempLV =
Rafael Espindola74caf012013-05-29 04:55:30 +0000965 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCall5a758de2013-02-16 00:17:33 +0000966 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall3892d022013-02-21 23:42:58 +0000967
968 if (const RedeclarableTemplateDecl *redeclTemp =
969 dyn_cast<RedeclarableTemplateDecl>(temp)) {
970 if (isExplicitMemberSpecialization(redeclTemp)) {
971 explicitSpecSuppressor = temp->getTemplatedDecl();
972 }
973 }
John McCall110e8e52010-10-29 22:22:43 +0000974 }
975
John McCall3892d022013-02-21 23:42:58 +0000976 // We should never be looking for an attribute directly on a template.
977 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
978
979 // If this member is an explicit member specialization, and it has
980 // an explicit attribute, ignore visibility from the parent.
981 bool considerClassVisibility = true;
982 if (explicitSpecSuppressor &&
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000983 // optimization: hasDVA() is true only with explicit visibility.
984 LV.isVisibilityExplicit() &&
985 classLV.getVisibility() != DefaultVisibility &&
John McCall3892d022013-02-21 23:42:58 +0000986 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
987 considerClassVisibility = false;
988 }
989
990 // Finally, merge in information from the class.
991 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall1fb0caa2010-10-22 21:05:15 +0000992 return LV;
John McCall3cdfc4d2010-08-13 08:35:10 +0000993}
994
David Blaikie99ba9e32011-12-20 02:48:34 +0000995void NamedDecl::anchor() { }
996
Rafael Espindola74caf012013-05-29 04:55:30 +0000997static LinkageInfo computeLVForDecl(const NamedDecl *D,
998 LVComputationKind computation);
999
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001000bool NamedDecl::isLinkageValid() const {
Rafael Espindolaa99ecbc2013-05-25 17:16:20 +00001001 if (!hasCachedLinkage())
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001002 return true;
John McCallf76b0922011-02-08 19:01:05 +00001003
Rafael Espindola74caf012013-05-29 04:55:30 +00001004 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindolaa99ecbc2013-05-25 17:16:20 +00001005 getCachedLinkage();
John McCallf76b0922011-02-08 19:01:05 +00001006}
1007
Stephen Hines176edba2014-12-01 14:53:08 -08001008ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1009 StringRef name = getName();
1010 if (name.empty()) return SFF_None;
1011
1012 if (name.front() == 'C')
1013 if (name == "CFStringCreateWithFormat" ||
1014 name == "CFStringCreateWithFormatAndArguments" ||
1015 name == "CFStringAppendFormat" ||
1016 name == "CFStringAppendFormatAndArguments")
1017 return SFF_CFString;
1018 return SFF_None;
1019}
1020
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001021Linkage NamedDecl::getLinkageInternal() const {
John McCalld4c3d662013-02-20 01:54:26 +00001022 // We don't care about visibility here, so ask for the cheapest
1023 // possible visibility analysis.
Rafael Espindoladc070562013-05-28 19:43:11 +00001024 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregor381d34e2010-12-06 18:36:25 +00001025}
1026
John McCallaf146032010-10-30 11:50:40 +00001027LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCall5a758de2013-02-16 00:17:33 +00001028 LVComputationKind computation =
1029 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindoladc070562013-05-28 19:43:11 +00001030 return getLVForDecl(this, computation);
John McCall0df95872010-10-29 00:29:13 +00001031}
Ted Kremenekbecc3082010-04-20 23:15:35 +00001032
Bill Wendlingb8110d42013-11-27 05:28:46 +00001033static Optional<Visibility>
1034getExplicitVisibilityAux(const NamedDecl *ND,
1035 NamedDecl::ExplicitVisibilityKind kind,
1036 bool IsMostRecent) {
1037 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1038
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +00001039 // Check the declaration itself first.
Bill Wendlingb8110d42013-11-27 05:28:46 +00001040 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +00001041 return V;
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001042
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +00001043 // If this is a member class of a specialization of a class template
1044 // and the corresponding decl has explicit visibility, use that.
Bill Wendlingb8110d42013-11-27 05:28:46 +00001045 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +00001046 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1047 if (InstantiatedFrom)
1048 return getVisibilityOf(InstantiatedFrom, kind);
1049 }
1050
1051 // If there wasn't explicit visibility there, and this is a
1052 // specialization of a class template, check for visibility
1053 // on the pattern.
1054 if (const ClassTemplateSpecializationDecl *spec
Bill Wendlingb8110d42013-11-27 05:28:46 +00001055 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +00001056 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1057 kind);
1058
1059 // Use the most recent declaration.
Bill Wendling525f2f52013-12-09 02:00:10 +00001060 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Bill Wendlingb8110d42013-11-27 05:28:46 +00001061 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1062 if (MostRecent != ND)
1063 return getExplicitVisibilityAux(MostRecent, kind, true);
1064 }
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +00001065
Bill Wendlingb8110d42013-11-27 05:28:46 +00001066 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola797105a2012-05-16 02:10:38 +00001067 if (Var->isStaticDataMember()) {
1068 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1069 if (InstantiatedFrom)
John McCalld4c3d662013-02-20 01:54:26 +00001070 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola797105a2012-05-16 02:10:38 +00001071 }
1072
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001073 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1074 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1075 kind);
1076
David Blaikie66874fb2013-02-21 01:47:18 +00001077 return None;
Rafael Espindola797105a2012-05-16 02:10:38 +00001078 }
Rafael Espindolad3b2f0a2013-02-26 19:33:14 +00001079 // Also handle function template specializations.
Bill Wendlingb8110d42013-11-27 05:28:46 +00001080 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001081 // If the function is a specialization of a template with an
1082 // explicit visibility attribute, use that.
1083 if (FunctionTemplateSpecializationInfo *templateInfo
1084 = fn->getTemplateSpecializationInfo())
John McCalld4c3d662013-02-20 01:54:26 +00001085 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1086 kind);
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001087
Rafael Espindola860097c2012-02-23 04:17:32 +00001088 // If the function is a member of a specialization of a class template
1089 // and the corresponding decl has explicit visibility, use that.
1090 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1091 if (InstantiatedFrom)
John McCalld4c3d662013-02-20 01:54:26 +00001092 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola860097c2012-02-23 04:17:32 +00001093
David Blaikie66874fb2013-02-21 01:47:18 +00001094 return None;
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001095 }
1096
Rafael Espindola98499012012-07-31 19:02:02 +00001097 // The visibility of a template is stored in the templated decl.
Bill Wendlingb8110d42013-11-27 05:28:46 +00001098 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
John McCalld4c3d662013-02-20 01:54:26 +00001099 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindola98499012012-07-31 19:02:02 +00001100
David Blaikie66874fb2013-02-21 01:47:18 +00001101 return None;
Douglas Gregor4421d2b2011-03-26 12:10:19 +00001102}
1103
Bill Wendlingb8110d42013-11-27 05:28:46 +00001104Optional<Visibility>
1105NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1106 return getExplicitVisibilityAux(this, kind, false);
1107}
1108
Eli Friedman07369dd2013-07-01 20:22:57 +00001109static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1110 LVComputationKind computation) {
1111 // This lambda has its linkage/visibility determined by its owner.
1112 if (ContextDecl) {
1113 if (isa<ParmVarDecl>(ContextDecl))
1114 DC = ContextDecl->getDeclContext()->getRedeclContext();
1115 else
1116 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1117 }
Faisal Valic6867dd2013-09-29 20:27:06 +00001118
Eli Friedman07369dd2013-07-01 20:22:57 +00001119 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1120 return getLVForDecl(ND, computation);
Faisal Valic6867dd2013-09-29 20:27:06 +00001121
Eli Friedman07369dd2013-07-01 20:22:57 +00001122 return LinkageInfo::external();
1123}
1124
John McCall5a758de2013-02-16 00:17:33 +00001125static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1126 LVComputationKind computation) {
1127 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1128 if (Function->isInAnonymousNamespace() &&
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00001129 !Function->isInExternCContext())
John McCall5a758de2013-02-16 00:17:33 +00001130 return LinkageInfo::uniqueExternal();
1131
1132 // This is a "void f();" which got merged with a file static.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001133 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCall5a758de2013-02-16 00:17:33 +00001134 return LinkageInfo::internal();
1135
1136 LinkageInfo LV;
John McCalld4c3d662013-02-20 01:54:26 +00001137 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001138 if (Optional<Visibility> Vis =
1139 getExplicitVisibility(Function, computation))
John McCall5a758de2013-02-16 00:17:33 +00001140 LV.mergeVisibility(*Vis, true);
1141 }
1142
1143 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1144 // merging storage classes and visibility attributes, so we don't have to
1145 // look at previous decls in here.
1146
1147 return LV;
1148 }
1149
1150 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001151 if (Var->hasExternalStorage()) {
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00001152 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCall5a758de2013-02-16 00:17:33 +00001153 return LinkageInfo::uniqueExternal();
1154
John McCall5a758de2013-02-16 00:17:33 +00001155 LinkageInfo LV;
1156 if (Var->getStorageClass() == SC_PrivateExtern)
1157 LV.mergeVisibility(HiddenVisibility, true);
John McCalld4c3d662013-02-20 01:54:26 +00001158 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikiedc84cd52013-02-20 22:23:23 +00001159 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCall5a758de2013-02-16 00:17:33 +00001160 LV.mergeVisibility(*Vis, true);
1161 }
1162
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001163 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1164 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1165 if (PrevLV.getLinkage())
1166 LV.setLinkage(PrevLV.getLinkage());
1167 LV.mergeVisibility(PrevLV);
1168 }
1169
John McCall5a758de2013-02-16 00:17:33 +00001170 return LV;
1171 }
Rafael Espindola9610d772013-06-17 20:04:51 +00001172
1173 if (!Var->isStaticLocal())
1174 return LinkageInfo::none();
John McCall5a758de2013-02-16 00:17:33 +00001175 }
1176
Rafael Espindola9610d772013-06-17 20:04:51 +00001177 ASTContext &Context = D->getASTContext();
1178 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaa99ecbc2013-05-25 17:16:20 +00001179 return LinkageInfo::none();
1180
Eli Friedman07369dd2013-07-01 20:22:57 +00001181 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1182 if (!OuterD)
Rafael Espindolaa99ecbc2013-05-25 17:16:20 +00001183 return LinkageInfo::none();
Rafael Espindolaec0d96f2013-06-04 13:43:35 +00001184
Eli Friedman07369dd2013-07-01 20:22:57 +00001185 LinkageInfo LV;
1186 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1187 if (!BD->getBlockManglingNumber())
1188 return LinkageInfo::none();
Rafael Espindolaec0d96f2013-06-04 13:43:35 +00001189
Eli Friedman07369dd2013-07-01 20:22:57 +00001190 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1191 BD->getBlockManglingContextDecl(), computation);
1192 } else {
1193 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1194 if (!FD->isInlined() &&
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001195 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman07369dd2013-07-01 20:22:57 +00001196 return LinkageInfo::none();
1197
1198 LV = getLVForDecl(FD, computation);
1199 }
Rafael Espindolabdf2bba2013-05-27 14:50:21 +00001200 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindolaa99ecbc2013-05-25 17:16:20 +00001201 return LinkageInfo::none();
1202 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1203 LV.isVisibilityExplicit());
John McCall5a758de2013-02-16 00:17:33 +00001204}
1205
Faisal Valide8eaa22013-10-01 02:51:53 +00001206static inline const CXXRecordDecl*
1207getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1208 const CXXRecordDecl *Ret = Record;
1209 while (Record && Record->isLambda()) {
1210 Ret = Record;
1211 if (!Record->getParent()) break;
1212 // Get the Containing Class of this Lambda Class
1213 Record = dyn_cast_or_null<CXXRecordDecl>(
1214 Record->getParent()->getParent());
1215 }
1216 return Ret;
1217}
1218
Rafael Espindoladc070562013-05-28 19:43:11 +00001219static LinkageInfo computeLVForDecl(const NamedDecl *D,
1220 LVComputationKind computation) {
Ted Kremenekbecc3082010-04-20 23:15:35 +00001221 // Objective-C: treat all Objective-C declarations as having external
1222 // linkage.
John McCall0df95872010-10-29 00:29:13 +00001223 switch (D->getKind()) {
Ted Kremenekbecc3082010-04-20 23:15:35 +00001224 default:
1225 break;
Argyrios Kyrtzidisf8d34ed2011-12-01 01:28:21 +00001226 case Decl::ParmVar:
1227 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +00001228 case Decl::TemplateTemplateParm: // count these as external
1229 case Decl::NonTypeTemplateParm:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001230 case Decl::ObjCAtDefsField:
1231 case Decl::ObjCCategory:
1232 case Decl::ObjCCategoryImpl:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001233 case Decl::ObjCCompatibleAlias:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001234 case Decl::ObjCImplementation:
Ted Kremenekbecc3082010-04-20 23:15:35 +00001235 case Decl::ObjCMethod:
1236 case Decl::ObjCProperty:
1237 case Decl::ObjCPropertyImpl:
1238 case Decl::ObjCProtocol:
John McCallaf146032010-10-30 11:50:40 +00001239 return LinkageInfo::external();
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001240
1241 case Decl::CXXRecord: {
1242 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1243 if (Record->isLambda()) {
1244 if (!Record->getLambdaManglingNumber()) {
1245 // This lambda has no mangling number, so it's internal.
1246 return LinkageInfo::internal();
1247 }
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001248
Faisal Valide8eaa22013-10-01 02:51:53 +00001249 // This lambda has its linkage/visibility determined:
1250 // - either by the outermost lambda if that lambda has no mangling
1251 // number.
1252 // - or by the parent of the outer most lambda
1253 // This prevents infinite recursion in settings such as nested lambdas
1254 // used in NSDMI's, for e.g.
1255 // struct L {
1256 // int t{};
1257 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1258 // };
1259 const CXXRecordDecl *OuterMostLambda =
1260 getOutermostEnclosingLambda(Record);
1261 if (!OuterMostLambda->getLambdaManglingNumber())
1262 return LinkageInfo::internal();
1263
1264 return getLVForClosure(
1265 OuterMostLambda->getDeclContext()->getRedeclContext(),
1266 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001267 }
1268
1269 break;
1270 }
Ted Kremenekbecc3082010-04-20 23:15:35 +00001271 }
1272
Douglas Gregord85b5b92009-11-25 22:24:25 +00001273 // Handle linkage for namespace-scope names.
John McCall0df95872010-10-29 00:29:13 +00001274 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall5a758de2013-02-16 00:17:33 +00001275 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001276
1277 // C++ [basic.link]p5:
1278 // In addition, a member function, static data member, a named
1279 // class or enumeration of class scope, or an unnamed class or
1280 // enumeration defined in a class-scope typedef declaration such
1281 // that the class or enumeration has the typedef name for linkage
1282 // purposes (7.1.3), has external linkage if the name of the class
1283 // has external linkage.
John McCall0df95872010-10-29 00:29:13 +00001284 if (D->getDeclContext()->isRecord())
John McCall5a758de2013-02-16 00:17:33 +00001285 return getLVForClassMember(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001286
1287 // C++ [basic.link]p6:
1288 // The name of a function declared in block scope and the name of
1289 // an object declared by a block scope extern declaration have
1290 // linkage. If there is a visible declaration of an entity with
1291 // linkage having the same name and type, ignoring entities
1292 // declared outside the innermost enclosing namespace scope, the
1293 // block scope declaration declares that same entity and receives
1294 // the linkage of the previous declaration. If there is more than
1295 // one such matching entity, the program is ill-formed. Otherwise,
1296 // if no matching entity is found, the block scope entity receives
1297 // external linkage.
John McCall5a758de2013-02-16 00:17:33 +00001298 if (D->getDeclContext()->isFunctionOrMethod())
1299 return getLVForLocalDecl(D, computation);
Douglas Gregord85b5b92009-11-25 22:24:25 +00001300
1301 // C++ [basic.link]p6:
1302 // Names not covered by these rules have no linkage.
John McCallaf146032010-10-30 11:50:40 +00001303 return LinkageInfo::none();
John McCall1fb0caa2010-10-22 21:05:15 +00001304}
Douglas Gregord85b5b92009-11-25 22:24:25 +00001305
Rafael Espindoladc070562013-05-28 19:43:11 +00001306namespace clang {
1307class LinkageComputer {
1308public:
1309 static LinkageInfo getLVForDecl(const NamedDecl *D,
1310 LVComputationKind computation) {
1311 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1312 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1313
1314 LinkageInfo LV = computeLVForDecl(D, computation);
1315 if (D->hasCachedLinkage())
1316 assert(D->getCachedLinkage() == LV.getLinkage());
1317
1318 D->setCachedLinkage(LV.getLinkage());
1319
1320#ifndef NDEBUG
1321 // In C (because of gnu inline) and in c++ with microsoft extensions an
1322 // static can follow an extern, so we can have two decls with different
1323 // linkages.
1324 const LangOptions &Opts = D->getASTContext().getLangOpts();
1325 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1326 return LV;
1327
1328 // We have just computed the linkage for this decl. By induction we know
1329 // that all other computed linkages match, check that the one we just
Stephen Hines651f13c2014-04-23 16:59:28 -07001330 // computed also does.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001331 NamedDecl *Old = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001332 for (auto I : D->redecls()) {
1333 NamedDecl *T = cast<NamedDecl>(I);
Rafael Espindoladc070562013-05-28 19:43:11 +00001334 if (T == D)
1335 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07001336 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindoladc070562013-05-28 19:43:11 +00001337 Old = T;
1338 break;
1339 }
1340 }
1341 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1342#endif
1343
1344 return LV;
1345 }
1346};
1347}
1348
1349static LinkageInfo getLVForDecl(const NamedDecl *D,
1350 LVComputationKind computation) {
1351 return clang::LinkageComputer::getLVForDecl(D, computation);
1352}
1353
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001354std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001355 std::string QualName;
1356 llvm::raw_string_ostream OS(QualName);
Stephen Hines651f13c2014-04-23 16:59:28 -07001357 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001358 return OS.str();
1359}
1360
1361void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1362 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1363}
1364
1365void NamedDecl::printQualifiedName(raw_ostream &OS,
1366 const PrintingPolicy &P) const {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001367 const DeclContext *Ctx = getDeclContext();
1368
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001369 if (Ctx->isFunctionOrMethod()) {
1370 printName(OS);
1371 return;
1372 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001373
Chris Lattner5f9e2722011-07-23 10:55:15 +00001374 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001375 ContextsTy Contexts;
1376
1377 // Collect contexts.
1378 while (Ctx && isa<NamedDecl>(Ctx)) {
1379 Contexts.push_back(Ctx);
1380 Ctx = Ctx->getParent();
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001381 }
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001382
1383 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1384 I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001385 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001386 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer5eada842013-02-22 15:46:01 +00001387 OS << Spec->getName();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001388 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer5eada842013-02-22 15:46:01 +00001389 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1390 TemplateArgs.data(),
1391 TemplateArgs.size(),
1392 P);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001393 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001394 if (P.SuppressUnwrittenScope &&
1395 (ND->isAnonymousNamespace() || ND->isInline()))
1396 continue;
Sam Weinig6be11202009-12-24 23:15:03 +00001397 if (ND->isAnonymousNamespace())
Stephen Hines651f13c2014-04-23 16:59:28 -07001398 OS << "(anonymous namespace)";
Sam Weinig6be11202009-12-24 23:15:03 +00001399 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001400 OS << *ND;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001401 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1402 if (!RD->getIdentifier())
Stephen Hines651f13c2014-04-23 16:59:28 -07001403 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001404 else
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001405 OS << *RD;
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001406 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001407 const FunctionProtoType *FT = nullptr;
Sam Weinig3521d012009-12-28 03:19:38 +00001408 if (FD->hasWrittenPrototype())
Eli Friedman482466b2012-08-30 22:22:09 +00001409 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinig3521d012009-12-28 03:19:38 +00001410
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001411 OS << *FD << '(';
Sam Weinig3521d012009-12-28 03:19:38 +00001412 if (FT) {
Sam Weinig3521d012009-12-28 03:19:38 +00001413 unsigned NumParams = FD->getNumParams();
1414 for (unsigned i = 0; i < NumParams; ++i) {
1415 if (i)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001416 OS << ", ";
Argyrios Kyrtzidis7ad5c992012-05-05 04:20:37 +00001417 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinig3521d012009-12-28 03:19:38 +00001418 }
1419
1420 if (FT->isVariadic()) {
1421 if (NumParams > 0)
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001422 OS << ", ";
1423 OS << "...";
Sam Weinig3521d012009-12-28 03:19:38 +00001424 }
1425 }
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001426 OS << ')';
1427 } else {
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001428 OS << *cast<NamedDecl>(*I);
Benjamin Kramer68eebbb2010-04-28 14:33:51 +00001429 }
1430 OS << "::";
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001431 }
1432
John McCall8472af42010-03-16 21:48:18 +00001433 if (getDeclName())
Benjamin Kramerb8989f22011-10-14 18:45:37 +00001434 OS << *this;
John McCall8472af42010-03-16 21:48:18 +00001435 else
Stephen Hines651f13c2014-04-23 16:59:28 -07001436 OS << "(anonymous)";
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001437}
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001438
Benjamin Kramerb063ef02013-02-23 13:53:57 +00001439void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1440 const PrintingPolicy &Policy,
1441 bool Qualified) const {
1442 if (Qualified)
1443 printQualifiedName(OS, Policy);
1444 else
1445 printName(OS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001446}
1447
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001448static bool isKindReplaceableBy(Decl::Kind OldK, Decl::Kind NewK) {
1449 // For method declarations, we never replace.
1450 if (ObjCMethodDecl::classofKind(NewK))
1451 return false;
1452
1453 if (OldK == NewK)
1454 return true;
1455
1456 // A compatibility alias for a class can be replaced by an interface.
1457 if (ObjCCompatibleAliasDecl::classofKind(OldK) &&
1458 ObjCInterfaceDecl::classofKind(NewK))
1459 return true;
1460
1461 // A typedef-declaration, alias-declaration, or Objective-C class declaration
1462 // can replace another declaration of the same type. Semantic analysis checks
1463 // that we have matching types.
1464 if ((TypedefNameDecl::classofKind(OldK) ||
1465 ObjCInterfaceDecl::classofKind(OldK)) &&
1466 (TypedefNameDecl::classofKind(NewK) ||
1467 ObjCInterfaceDecl::classofKind(NewK)))
1468 return true;
1469
1470 // Otherwise, a kind mismatch implies that the declaration is not replaced.
1471 return false;
1472}
1473
1474template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1475 return true;
1476}
1477static bool isRedeclarableImpl(...) { return false; }
1478static bool isRedeclarable(Decl::Kind K) {
1479 switch (K) {
1480#define DECL(Type, Base) \
1481 case Decl::Type: \
1482 return isRedeclarableImpl((Type##Decl *)nullptr);
1483#define ABSTRACT_DECL(DECL)
1484#include "clang/AST/DeclNodes.inc"
1485 }
1486 llvm_unreachable("unknown decl kind");
1487}
1488
1489bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001490 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1491
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07001492 // Never replace one imported declaration with another; we need both results
1493 // when re-exporting.
1494 if (OldD->isFromASTFile() && isFromASTFile())
1495 return false;
1496
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001497 if (!isKindReplaceableBy(OldD->getKind(), getKind()))
1498 return false;
1499
1500 // Inline namespaces can give us two declarations with the same
1501 // name and kind in the same scope but different contexts; we should
1502 // keep both declarations in this case.
1503 if (!this->getDeclContext()->getRedeclContext()->Equals(
1504 OldD->getDeclContext()->getRedeclContext()))
1505 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001507 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1508 // For function declarations, we keep track of redeclarations.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001509 // FIXME: This returns false for functions that should in fact be replaced.
1510 // Instead, perform some kind of type check?
1511 if (FD->getPreviousDecl() != OldD)
1512 return false;
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001513
Douglas Gregore53060f2009-06-25 22:08:12 +00001514 // For function templates, the underlying function declarations are linked.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001515 if (const FunctionTemplateDecl *FunctionTemplate =
1516 dyn_cast<FunctionTemplateDecl>(this))
1517 return FunctionTemplate->getTemplatedDecl()->declarationReplaces(
1518 cast<FunctionTemplateDecl>(OldD)->getTemplatedDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001520 // Using shadow declarations can be overloaded on their target declarations
1521 // if they introduce functions.
1522 // FIXME: If our target replaces the old target, can we replace the old
1523 // shadow declaration?
1524 if (auto *USD = dyn_cast<UsingShadowDecl>(this))
1525 if (USD->getTargetDecl() != cast<UsingShadowDecl>(OldD)->getTargetDecl())
1526 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001528 // Using declarations can be overloaded if they introduce functions.
1529 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregordc355712011-02-25 00:36:19 +00001530 ASTContext &Context = getASTContext();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001531 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregordc355712011-02-25 00:36:19 +00001532 Context.getCanonicalNestedNameSpecifier(
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001533 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregordc355712011-02-25 00:36:19 +00001534 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001535 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman13b572c2013-08-20 00:39:40 +00001536 ASTContext &Context = getASTContext();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001537 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman13b572c2013-08-20 00:39:40 +00001538 Context.getCanonicalNestedNameSpecifier(
1539 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1540 }
1541
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001542 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1543 // We want to keep it, unless it nominates same namespace.
1544 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1545 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1546 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1547 ->getOriginalNamespace();
Stephen Hines651f13c2014-04-23 16:59:28 -07001548
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001549 if (!IsKnownNewer && isRedeclarable(getKind())) {
1550 // Check whether this is actually newer than OldD. We want to keep the
1551 // newer declaration. This loop will usually only iterate once, because
1552 // OldD is usually the previous declaration.
1553 for (auto D : redecls()) {
1554 if (D == OldD)
1555 break;
1556
1557 // If we reach the canonical declaration, then OldD is not actually older
1558 // than this one.
1559 //
1560 // FIXME: In this case, we should not add this decl to the lookup table.
1561 if (D->isCanonicalDecl())
1562 return false;
1563 }
1564 }
1565
1566 // It's a newer declaration of the same kind of declaration in the same scope,
1567 // and not an overload: we want this decl instead of the existing one.
1568 return true;
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001569}
1570
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001571bool NamedDecl::hasLinkage() const {
Rafael Espindolaa99ecbc2013-05-25 17:16:20 +00001572 return getFormalLinkage() != NoLinkage;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001573}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001574
Daniel Dunbar6daffa52012-03-08 18:20:41 +00001575NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlssone136e0e2009-06-26 06:29:23 +00001576 NamedDecl *ND = this;
Benjamin Kramer56757e92012-03-08 21:00:45 +00001577 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1578 ND = UD->getTargetDecl();
1579
1580 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1581 return AD->getClassInterface();
1582
1583 return ND;
Anders Carlssone136e0e2009-06-26 06:29:23 +00001584}
1585
John McCall161755a2010-04-06 21:38:20 +00001586bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor5bc37f62012-03-08 02:08:05 +00001587 if (!isCXXClassMember())
1588 return false;
1589
John McCall161755a2010-04-06 21:38:20 +00001590 const NamedDecl *D = this;
1591 if (isa<UsingShadowDecl>(D))
1592 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1593
John McCall76da55d2013-04-16 07:28:30 +00001594 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCall161755a2010-04-06 21:38:20 +00001595 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07001596 if (const CXXMethodDecl *MD =
1597 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1598 return MD->isInstance();
John McCall161755a2010-04-06 21:38:20 +00001599 return false;
1600}
1601
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001602//===----------------------------------------------------------------------===//
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001603// DeclaratorDecl Implementation
1604//===----------------------------------------------------------------------===//
1605
Douglas Gregor1693e152010-07-06 18:42:40 +00001606template <typename DeclT>
1607static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1608 if (decl->getNumTemplateParameterLists() > 0)
1609 return decl->getTemplateParameterList(0)->getTemplateLoc();
1610 else
1611 return decl->getInnerLocStart();
1612}
1613
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001614SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCall4e449832010-05-28 23:32:21 +00001615 TypeSourceInfo *TSI = getTypeSourceInfo();
1616 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001617 return SourceLocation();
1618}
1619
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001620void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1621 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00001622 // Make sure the extended decl info is allocated.
1623 if (!hasExtInfo()) {
1624 // Save (non-extended) type source info pointer.
1625 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1626 // Allocate external info struct.
1627 DeclInfo = new (getASTContext()) ExtInfo;
1628 // Restore savedTInfo into (extended) decl info.
1629 getExtInfo()->TInfo = savedTInfo;
1630 }
1631 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001632 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00001633 } else {
John McCallb6217662010-03-15 10:12:16 +00001634 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00001635 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001636 if (getExtInfo()->NumTemplParamLists == 0) {
1637 // Save type source info pointer.
1638 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1639 // Deallocate the extended decl info.
1640 getASTContext().Deallocate(getExtInfo());
1641 // Restore savedTInfo into (non-extended) decl info.
1642 DeclInfo = savedTInfo;
1643 }
1644 else
1645 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00001646 }
1647 }
1648}
1649
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00001650void
1651DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1652 unsigned NumTPLists,
1653 TemplateParameterList **TPLists) {
1654 assert(NumTPLists > 0);
1655 // Make sure the extended decl info is allocated.
1656 if (!hasExtInfo()) {
1657 // Save (non-extended) type source info pointer.
1658 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1659 // Allocate external info struct.
1660 DeclInfo = new (getASTContext()) ExtInfo;
1661 // Restore savedTInfo into (extended) decl info.
1662 getExtInfo()->TInfo = savedTInfo;
1663 }
1664 // Set the template parameter lists info.
1665 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1666}
1667
Douglas Gregor1693e152010-07-06 18:42:40 +00001668SourceLocation DeclaratorDecl::getOuterLocStart() const {
1669 return getTemplateOrInnerLocStart(this);
1670}
1671
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001672namespace {
1673
1674// Helper function: returns true if QT is or contains a type
1675// having a postfix component.
1676bool typeIsPostfix(clang::QualType QT) {
1677 while (true) {
1678 const Type* T = QT.getTypePtr();
1679 switch (T->getTypeClass()) {
1680 default:
1681 return false;
1682 case Type::Pointer:
1683 QT = cast<PointerType>(T)->getPointeeType();
1684 break;
1685 case Type::BlockPointer:
1686 QT = cast<BlockPointerType>(T)->getPointeeType();
1687 break;
1688 case Type::MemberPointer:
1689 QT = cast<MemberPointerType>(T)->getPointeeType();
1690 break;
1691 case Type::LValueReference:
1692 case Type::RValueReference:
1693 QT = cast<ReferenceType>(T)->getPointeeType();
1694 break;
1695 case Type::PackExpansion:
1696 QT = cast<PackExpansionType>(T)->getPattern();
1697 break;
1698 case Type::Paren:
1699 case Type::ConstantArray:
1700 case Type::DependentSizedArray:
1701 case Type::IncompleteArray:
1702 case Type::VariableArray:
1703 case Type::FunctionProto:
1704 case Type::FunctionNoProto:
1705 return true;
1706 }
1707 }
1708}
1709
1710} // namespace
1711
1712SourceRange DeclaratorDecl::getSourceRange() const {
1713 SourceLocation RangeEnd = getLocation();
1714 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001715 // If the declaration has no name or the type extends past the name take the
1716 // end location of the type.
1717 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001718 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1719 }
1720 return SourceRange(getOuterLocStart(), RangeEnd);
1721}
1722
Abramo Bagnara9b934882010-06-12 08:15:14 +00001723void
Douglas Gregorc722ea42010-06-15 17:44:38 +00001724QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1725 unsigned NumTPLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00001726 TemplateParameterList **TPLists) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001727 assert((NumTPLists == 0 || TPLists != nullptr) &&
Abramo Bagnara9b934882010-06-12 08:15:14 +00001728 "Empty array of template parameters with positive size!");
Abramo Bagnara9b934882010-06-12 08:15:14 +00001729
1730 // Free previous template parameters (if any).
1731 if (NumTemplParamLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001732 Context.Deallocate(TemplParamLists);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001733 TemplParamLists = nullptr;
Abramo Bagnara9b934882010-06-12 08:15:14 +00001734 NumTemplParamLists = 0;
1735 }
1736 // Set info on matched template parameter lists (if any).
1737 if (NumTPLists > 0) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00001738 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnara9b934882010-06-12 08:15:14 +00001739 NumTemplParamLists = NumTPLists;
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001740 std::copy(TPLists, TPLists + NumTPLists, TemplParamLists);
Abramo Bagnara9b934882010-06-12 08:15:14 +00001741 }
1742}
1743
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00001744//===----------------------------------------------------------------------===//
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001745// VarDecl Implementation
1746//===----------------------------------------------------------------------===//
1747
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001748const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1749 switch (SC) {
Peter Collingbourne8c25fc52011-09-19 21:14:35 +00001750 case SC_None: break;
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001751 case SC_Auto: return "auto";
1752 case SC_Extern: return "extern";
1753 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1754 case SC_PrivateExtern: return "__private_extern__";
1755 case SC_Register: return "register";
1756 case SC_Static: return "static";
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001757 }
1758
Peter Collingbourne8be0c742011-09-20 12:40:26 +00001759 llvm_unreachable("Invalid storage class");
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001760}
1761
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001762VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1763 SourceLocation StartLoc, SourceLocation IdLoc,
1764 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1765 StorageClass SC)
1766 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1767 redeclarable_base(C), Init() {
Stephen Hines651f13c2014-04-23 16:59:28 -07001768 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1769 "VarDeclBitfields too large!");
1770 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1771 "ParmVarDeclBitfields too large!");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001772 AllBits = 0;
1773 VarDeclBits.SClass = SC;
1774 // Everything else is implicitly initialized to false.
1775}
1776
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001777VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1778 SourceLocation StartL, SourceLocation IdL,
John McCalla93c9342009-12-07 02:54:59 +00001779 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001780 StorageClass S) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001781 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes99f06ba2008-12-17 23:39:55 +00001782}
1783
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001784VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001785 return new (C, ID)
1786 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1787 QualType(), nullptr, SC_None);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00001788}
1789
Douglas Gregor381d34e2010-12-06 18:36:25 +00001790void VarDecl::setStorageClass(StorageClass SC) {
1791 assert(isLegalForVariable(SC));
John McCallf1e4fbf2011-05-01 02:13:58 +00001792 VarDeclBits.SClass = SC;
Douglas Gregor381d34e2010-12-06 18:36:25 +00001793}
1794
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001795VarDecl::TLSKind VarDecl::getTLSKind() const {
1796 switch (VarDeclBits.TSCSpec) {
1797 case TSCS_unspecified:
1798 if (hasAttr<ThreadAttr>())
1799 return TLS_Static;
1800 return TLS_None;
1801 case TSCS___thread: // Fall through.
1802 case TSCS__Thread_local:
1803 return TLS_Static;
1804 case TSCS_thread_local:
1805 return TLS_Dynamic;
1806 }
1807 llvm_unreachable("Unknown thread storage class specifier!");
1808}
1809
Douglas Gregor1693e152010-07-06 18:42:40 +00001810SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidisd69f31c2012-10-08 23:08:41 +00001811 if (const Expr *Init = getInit()) {
1812 SourceLocation InitEnd = Init->getLocEnd();
Nico Weber3a344f92013-01-22 17:00:09 +00001813 // If Init is implicit, ignore its source range and fallback on
1814 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1815 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidisd69f31c2012-10-08 23:08:41 +00001816 return SourceRange(getOuterLocStart(), InitEnd);
1817 }
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00001818 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00001819}
1820
Rafael Espindola7ac928b2013-01-04 21:18:45 +00001821template<typename T>
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001822static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindolad2fdd422013-02-14 01:47:04 +00001823 // C++ [dcl.link]p1: All function types, function names with external linkage,
1824 // and variable names with external linkage have a language linkage.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001825 if (!D.hasExternalFormalLinkage())
Rafael Espindolad2fdd422013-02-14 01:47:04 +00001826 return NoLanguageLinkage;
1827
1828 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola2b721f52013-01-04 20:41:40 +00001829 // C language linkage fits the implementation nicely.
Rafael Espindola78eeba82012-12-28 14:21:58 +00001830 ASTContext &Context = D.getASTContext();
1831 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola950fee22013-02-14 01:18:37 +00001832 return CLanguageLinkage;
1833
Rafael Espindolad2fdd422013-02-14 01:47:04 +00001834 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1835 // language linkage of the names of class members and the function type of
1836 // class member functions.
Rafael Espindola78eeba82012-12-28 14:21:58 +00001837 const DeclContext *DC = D.getDeclContext();
1838 if (DC->isRecord())
Rafael Espindola950fee22013-02-14 01:18:37 +00001839 return CXXLanguageLinkage;
Rafael Espindola78eeba82012-12-28 14:21:58 +00001840
1841 // If the first decl is in an extern "C" context, any other redeclaration
1842 // will have C language linkage. If the first one is not in an extern "C"
1843 // context, we would have reported an error for any other decl being in one.
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00001844 if (isFirstInExternCContext(&D))
Rafael Espindola950fee22013-02-14 01:18:37 +00001845 return CLanguageLinkage;
1846 return CXXLanguageLinkage;
Rafael Espindola78eeba82012-12-28 14:21:58 +00001847}
1848
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001849template<typename T>
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001850static bool isDeclExternC(const T &D) {
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001851 // Since the context is ignored for class members, they can only have C++
1852 // language linkage or no language linkage.
1853 const DeclContext *DC = D.getDeclContext();
1854 if (DC->isRecord()) {
1855 assert(D.getASTContext().getLangOpts().CPlusPlus);
1856 return false;
1857 }
1858
1859 return D.getLanguageLinkage() == CLanguageLinkage;
1860}
1861
Rafael Espindola950fee22013-02-14 01:18:37 +00001862LanguageLinkage VarDecl::getLanguageLinkage() const {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001863 return getDeclLanguageLinkage(*this);
Rafael Espindola78eeba82012-12-28 14:21:58 +00001864}
1865
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001866bool VarDecl::isExternC() const {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001867 return isDeclExternC(*this);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001868}
1869
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00001870bool VarDecl::isInExternCContext() const {
Serge Pavlov142ab062013-11-14 02:13:03 +00001871 return getLexicalDeclContext()->isExternCContext();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00001872}
1873
1874bool VarDecl::isInExternCXXContext() const {
Serge Pavlov142ab062013-11-14 02:13:03 +00001875 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00001876}
1877
Rafael Espindolabc650912013-10-17 15:37:26 +00001878VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001879
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001880VarDecl::DefinitionKind
1881VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redle9d12b62010-01-31 22:27:38 +00001882 // C++ [basic.def]p2:
1883 // A declaration is a definition unless [...] it contains the 'extern'
1884 // specifier or a linkage-specification and neither an initializer [...],
1885 // it declares a static data member in a class declaration [...].
Richard Smithd0629eb2013-09-27 20:14:12 +00001886 // C++1y [temp.expl.spec]p15:
1887 // An explicit specialization of a static data member or an explicit
1888 // specialization of a static data member template is a definition if the
1889 // declaration includes an initializer; otherwise, it is a declaration.
1890 //
1891 // FIXME: How do you declare (but not define) a partial specialization of
1892 // a static data member template outside the containing class?
Sebastian Redle9d12b62010-01-31 22:27:38 +00001893 if (isStaticDataMember()) {
Richard Smithd0629eb2013-09-27 20:14:12 +00001894 if (isOutOfLine() &&
1895 (hasInit() ||
1896 // If the first declaration is out-of-line, this may be an
1897 // instantiation of an out-of-line partial specialization of a variable
1898 // template for which we have not yet instantiated the initializer.
Rafael Espindolabc650912013-10-17 15:37:26 +00001899 (getFirstDecl()->isOutOfLine()
Richard Smithd0629eb2013-09-27 20:14:12 +00001900 ? getTemplateSpecializationKind() == TSK_Undeclared
1901 : getTemplateSpecializationKind() !=
1902 TSK_ExplicitSpecialization) ||
1903 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redle9d12b62010-01-31 22:27:38 +00001904 return Definition;
1905 else
1906 return DeclarationOnly;
1907 }
1908 // C99 6.7p5:
1909 // A definition of an identifier is a declaration for that identifier that
1910 // [...] causes storage to be reserved for that object.
1911 // Note: that applies for all non-file-scope objects.
1912 // C99 6.9.2p1:
1913 // If the declaration of an identifier for an object has file scope and an
1914 // initializer, the declaration is an external definition for the identifier
1915 if (hasInit())
1916 return Definition;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00001917
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07001918 if (hasAttr<AliasAttr>() || hasAttr<SelectAnyAttr>())
Rafael Espindolab1c0e202013-10-22 21:39:03 +00001919 return Definition;
1920
Richard Smithd0629eb2013-09-27 20:14:12 +00001921 // A variable template specialization (other than a static data member
1922 // template or an explicit specialization) is a declaration until we
1923 // instantiate its initializer.
1924 if (isa<VarTemplateSpecializationDecl>(this) &&
1925 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1926 return DeclarationOnly;
1927
Sebastian Redle9d12b62010-01-31 22:27:38 +00001928 if (hasExternalStorage())
1929 return DeclarationOnly;
Rafael Espindola37783002013-03-07 01:42:44 +00001930
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00001931 // [dcl.link] p7:
1932 // A declaration directly contained in a linkage-specification is treated
1933 // as if it contains the extern specifier for the purpose of determining
1934 // the linkage of the declared name and whether it is a definition.
Stephen Hines651f13c2014-04-23 16:59:28 -07001935 if (isSingleLineLanguageLinkage(*this))
Rafael Espindolae5e575d2013-04-26 01:30:23 +00001936 return DeclarationOnly;
Rafael Espindola65dfa2b2013-04-25 12:11:36 +00001937
Sebastian Redle9d12b62010-01-31 22:27:38 +00001938 // C99 6.9.2p2:
1939 // A declaration of an object that has file scope without an initializer,
1940 // and without a storage class specifier or the scs 'static', constitutes
1941 // a tentative definition.
1942 // No such thing in C++.
David Blaikie4e4d0842012-03-11 07:00:24 +00001943 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redle9d12b62010-01-31 22:27:38 +00001944 return TentativeDefinition;
1945
1946 // What's left is (in C, block-scope) declarations without initializers or
1947 // external storage. These are definitions.
1948 return Definition;
1949}
1950
Sebastian Redle9d12b62010-01-31 22:27:38 +00001951VarDecl *VarDecl::getActingDefinition() {
1952 DefinitionKind Kind = isThisDeclarationADefinition();
1953 if (Kind != TentativeDefinition)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001954 return nullptr;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001955
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001956 VarDecl *LastTentative = nullptr;
Rafael Espindolabc650912013-10-17 15:37:26 +00001957 VarDecl *First = getFirstDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -07001958 for (auto I : First->redecls()) {
1959 Kind = I->isThisDeclarationADefinition();
Sebastian Redle9d12b62010-01-31 22:27:38 +00001960 if (Kind == Definition)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001961 return nullptr;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001962 else if (Kind == TentativeDefinition)
Stephen Hines651f13c2014-04-23 16:59:28 -07001963 LastTentative = I;
Sebastian Redle9d12b62010-01-31 22:27:38 +00001964 }
1965 return LastTentative;
1966}
1967
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001968VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindolabc650912013-10-17 15:37:26 +00001969 VarDecl *First = getFirstDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -07001970 for (auto I : First->redecls()) {
1971 if (I->isThisDeclarationADefinition(C) == Definition)
1972 return I;
Sebastian Redl31310a22010-02-01 20:16:42 +00001973 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001974 return nullptr;
Sebastian Redl31310a22010-02-01 20:16:42 +00001975}
1976
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001977VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall110e8e52010-10-29 22:22:43 +00001978 DefinitionKind Kind = DeclarationOnly;
1979
Rafael Espindolabc650912013-10-17 15:37:26 +00001980 const VarDecl *First = getFirstDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -07001981 for (auto I : First->redecls()) {
1982 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar047da192012-03-06 23:52:46 +00001983 if (Kind == Definition)
1984 break;
1985 }
John McCall110e8e52010-10-29 22:22:43 +00001986
1987 return Kind;
1988}
1989
Sebastian Redl31310a22010-02-01 20:16:42 +00001990const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07001991 for (auto I : redecls()) {
1992 if (auto Expr = I->getInit()) {
1993 D = I;
1994 return Expr;
1995 }
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001996 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001997 return nullptr;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00001998}
1999
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002000bool VarDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00002001 if (Decl::isOutOfLine())
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002002 return true;
Chandler Carruth8761d682010-02-21 07:08:09 +00002003
2004 if (!isStaticDataMember())
2005 return false;
2006
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002007 // If this static data member was instantiated from a static data member of
2008 // a class template, check whether that static data member was defined
2009 // out-of-line.
2010 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2011 return VD->isOutOfLine();
2012
2013 return false;
2014}
2015
Douglas Gregor0d035142009-10-27 18:42:08 +00002016VarDecl *VarDecl::getOutOfLineDefinition() {
2017 if (!isStaticDataMember())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002018 return nullptr;
2019
Stephen Hines651f13c2014-04-23 16:59:28 -07002020 for (auto RD : redecls()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002021 if (RD->getLexicalDeclContext()->isFileContext())
Stephen Hines651f13c2014-04-23 16:59:28 -07002022 return RD;
Douglas Gregor0d035142009-10-27 18:42:08 +00002023 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002024
2025 return nullptr;
Douglas Gregor0d035142009-10-27 18:42:08 +00002026}
2027
Douglas Gregor838db382010-02-11 01:19:42 +00002028void VarDecl::setInit(Expr *I) {
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002029 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2030 Eval->~EvaluatedStmt();
Douglas Gregor838db382010-02-11 01:19:42 +00002031 getASTContext().Deallocate(Eval);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002032 }
2033
2034 Init = I;
2035}
2036
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00002037bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00002038 const LangOptions &Lang = C.getLangOpts();
Richard Smith1d238ea2011-12-21 02:55:12 +00002039
Richard Smith16581332012-03-02 04:14:40 +00002040 if (!Lang.CPlusPlus)
2041 return false;
2042
2043 // In C++11, any variable of reference type can be used in a constant
2044 // expression if it is initialized by a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00002045 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith16581332012-03-02 04:14:40 +00002046 return true;
2047
2048 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith1d238ea2011-12-21 02:55:12 +00002049 // not require the variable to be non-volatile, but we consider this to be a
2050 // defect.
Richard Smith16581332012-03-02 04:14:40 +00002051 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith1d238ea2011-12-21 02:55:12 +00002052 return false;
2053
2054 // In C++, const, non-volatile variables of integral or enumeration types
2055 // can be used in constant expressions.
2056 if (getType()->isIntegralOrEnumerationType())
2057 return true;
2058
Richard Smith16581332012-03-02 04:14:40 +00002059 // Additionally, in C++11, non-volatile constexpr variables can be used in
2060 // constant expressions.
Richard Smith80ad52f2013-01-02 11:42:31 +00002061 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith1d238ea2011-12-21 02:55:12 +00002062}
2063
Richard Smith099e7f62011-12-19 06:19:21 +00002064/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2065/// form, which contains extra information on the evaluated value of the
2066/// initializer.
2067EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2068 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
2069 if (!Eval) {
2070 Stmt *S = Init.get<Stmt *>();
Manuel Klimekf0f353b2013-06-03 13:51:33 +00002071 // Note: EvaluatedStmt contains an APValue, which usually holds
2072 // resources not allocated from the ASTContext. We need to do some
2073 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2074 // where we can detect whether there's anything to clean up or not.
Richard Smith099e7f62011-12-19 06:19:21 +00002075 Eval = new (getASTContext()) EvaluatedStmt;
2076 Eval->Value = S;
2077 Init = Eval;
2078 }
2079 return Eval;
2080}
2081
Richard Smith2d6a5672012-01-14 04:30:29 +00002082APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002083 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith2d6a5672012-01-14 04:30:29 +00002084 return evaluateValue(Notes);
2085}
2086
Manuel Klimekf0f353b2013-06-03 13:51:33 +00002087namespace {
2088// Destroy an APValue that was allocated in an ASTContext.
2089void DestroyAPValue(void* UntypedValue) {
2090 static_cast<APValue*>(UntypedValue)->~APValue();
2091}
2092} // namespace
2093
Richard Smith2d6a5672012-01-14 04:30:29 +00002094APValue *VarDecl::evaluateValue(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002095 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith099e7f62011-12-19 06:19:21 +00002096 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2097
2098 // We only produce notes indicating why an initializer is non-constant the
2099 // first time it is evaluated. FIXME: The notes won't always be emitted the
2100 // first time we try evaluation, so might not be produced at all.
2101 if (Eval->WasEvaluated)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002102 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smith099e7f62011-12-19 06:19:21 +00002103
2104 const Expr *Init = cast<Expr>(Eval->Value);
2105 assert(!Init->isValueDependent());
2106
2107 if (Eval->IsEvaluating) {
2108 // FIXME: Produce a diagnostic for self-initialization.
2109 Eval->CheckedICE = true;
2110 Eval->IsICE = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002111 return nullptr;
Richard Smith099e7f62011-12-19 06:19:21 +00002112 }
2113
2114 Eval->IsEvaluating = true;
2115
2116 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2117 this, Notes);
2118
Manuel Klimekf0f353b2013-06-03 13:51:33 +00002119 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2120 // or that it's empty (so that there's nothing to clean up) if evaluation
2121 // failed.
Richard Smith099e7f62011-12-19 06:19:21 +00002122 if (!Result)
2123 Eval->Evaluated = APValue();
Manuel Klimekf0f353b2013-06-03 13:51:33 +00002124 else if (Eval->Evaluated.needsCleanup())
2125 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smith099e7f62011-12-19 06:19:21 +00002126
2127 Eval->IsEvaluating = false;
2128 Eval->WasEvaluated = true;
2129
2130 // In C++11, we have determined whether the initializer was a constant
2131 // expression as a side-effect.
Richard Smith80ad52f2013-01-02 11:42:31 +00002132 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smith099e7f62011-12-19 06:19:21 +00002133 Eval->CheckedICE = true;
Eli Friedman210386e2012-02-06 21:50:18 +00002134 Eval->IsICE = Result && Notes.empty();
Richard Smith099e7f62011-12-19 06:19:21 +00002135 }
2136
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002137 return Result ? &Eval->Evaluated : nullptr;
Richard Smith099e7f62011-12-19 06:19:21 +00002138}
2139
2140bool VarDecl::checkInitIsICE() const {
John McCall73076432012-01-05 00:13:19 +00002141 // Initializers of weak variables are never ICEs.
2142 if (isWeak())
2143 return false;
2144
Richard Smith099e7f62011-12-19 06:19:21 +00002145 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2146 if (Eval->CheckedICE)
2147 // We have already checked whether this subexpression is an
2148 // integral constant expression.
2149 return Eval->IsICE;
2150
2151 const Expr *Init = cast<Expr>(Eval->Value);
2152 assert(!Init->isValueDependent());
2153
2154 // In C++11, evaluate the initializer to check whether it's a constant
2155 // expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00002156 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002157 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00002158 evaluateValue(Notes);
2159 return Eval->IsICE;
2160 }
2161
2162 // It's an ICE whether or not the definition we found is
2163 // out-of-line. See DR 721 and the discussion in Clang PR
2164 // 6206 for details.
2165
2166 if (Eval->CheckingICE)
2167 return false;
2168 Eval->CheckingICE = true;
2169
2170 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2171 Eval->CheckingICE = false;
2172 Eval->CheckedICE = true;
2173 return Eval->IsICE;
2174}
2175
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002176VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002177 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002178 return cast<VarDecl>(MSI->getInstantiatedFrom());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002179
2180 return nullptr;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002181}
2182
Douglas Gregor663b5a02009-10-14 20:14:33 +00002183TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Larisse Voufoef4579c2013-08-06 01:03:05 +00002184 if (const VarTemplateSpecializationDecl *Spec =
2185 dyn_cast<VarTemplateSpecializationDecl>(this))
2186 return Spec->getSpecializationKind();
2187
Sebastian Redle9d12b62010-01-31 22:27:38 +00002188 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002189 return MSI->getTemplateSpecializationKind();
Richard Smithd0629eb2013-09-27 20:14:12 +00002190
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002191 return TSK_Undeclared;
2192}
2193
Richard Smithd0629eb2013-09-27 20:14:12 +00002194SourceLocation VarDecl::getPointOfInstantiation() const {
2195 if (const VarTemplateSpecializationDecl *Spec =
2196 dyn_cast<VarTemplateSpecializationDecl>(this))
2197 return Spec->getPointOfInstantiation();
2198
2199 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2200 return MSI->getPointOfInstantiation();
2201
2202 return SourceLocation();
2203}
2204
Larisse Voufoef4579c2013-08-06 01:03:05 +00002205VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2206 return getASTContext().getTemplateOrSpecializationInfo(this)
2207 .dyn_cast<VarTemplateDecl *>();
2208}
2209
2210void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2211 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2212}
2213
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002214MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smith3f322102013-08-01 04:12:04 +00002215 if (isStaticDataMember())
Larisse Voufoef4579c2013-08-06 01:03:05 +00002216 // FIXME: Remove ?
2217 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2218 return getASTContext().getTemplateOrSpecializationInfo(this)
2219 .dyn_cast<MemberSpecializationInfo *>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002220 return nullptr;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002221}
2222
Douglas Gregor0a897e32009-10-15 17:21:20 +00002223void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2224 SourceLocation PointOfInstantiation) {
Richard Smithd0629eb2013-09-27 20:14:12 +00002225 assert((isa<VarTemplateSpecializationDecl>(this) ||
2226 getMemberSpecializationInfo()) &&
2227 "not a variable or static data member template specialization");
2228
Larisse Voufoef4579c2013-08-06 01:03:05 +00002229 if (VarTemplateSpecializationDecl *Spec =
2230 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2231 Spec->setSpecializationKind(TSK);
2232 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2233 Spec->getPointOfInstantiation().isInvalid())
2234 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002235 }
2236
2237 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2238 MSI->setTemplateSpecializationKind(TSK);
2239 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2240 MSI->getPointOfInstantiation().isInvalid())
2241 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002242 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00002243}
2244
2245void
2246VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2247 TemplateSpecializationKind TSK) {
2248 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2249 "Previous template or instantiation?");
2250 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002251}
2252
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002253//===----------------------------------------------------------------------===//
2254// ParmVarDecl Implementation
2255//===----------------------------------------------------------------------===//
Douglas Gregor275a3692009-03-10 23:43:53 +00002256
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002257ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002258 SourceLocation StartLoc,
2259 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002260 QualType T, TypeSourceInfo *TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002261 StorageClass S, Expr *DefArg) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002262 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Stephen Hines651f13c2014-04-23 16:59:28 -07002263 S, DefArg);
Douglas Gregor275a3692009-03-10 23:43:53 +00002264}
2265
Reid Kleckner12df2462013-06-24 17:51:48 +00002266QualType ParmVarDecl::getOriginalType() const {
2267 TypeSourceInfo *TSI = getTypeSourceInfo();
2268 QualType T = TSI ? TSI->getType() : getType();
2269 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2270 return DT->getOriginalType();
2271 return T;
2272}
2273
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002274ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002275 return new (C, ID)
2276 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2277 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00002278}
2279
Argyrios Kyrtzidis0bfe83b2011-07-30 17:23:26 +00002280SourceRange ParmVarDecl::getSourceRange() const {
2281 if (!hasInheritedDefaultArg()) {
2282 SourceRange ArgRange = getDefaultArgRange();
2283 if (ArgRange.isValid())
2284 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2285 }
2286
Argyrios Kyrtzidis673c5d52013-04-17 01:56:48 +00002287 // DeclaratorDecl considers the range of postfix types as overlapping with the
2288 // declaration name, but this is not the case with parameters in ObjC methods.
2289 if (isa<ObjCMethodDecl>(getDeclContext()))
2290 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2291
Argyrios Kyrtzidis0bfe83b2011-07-30 17:23:26 +00002292 return DeclaratorDecl::getSourceRange();
2293}
2294
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002295Expr *ParmVarDecl::getDefaultArg() {
2296 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2297 assert(!hasUninstantiatedDefaultArg() &&
2298 "Default argument is not yet instantiated!");
2299
2300 Expr *Arg = getInit();
John McCall4765fa02010-12-06 08:20:24 +00002301 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002302 return E->getSubExpr();
Douglas Gregor275a3692009-03-10 23:43:53 +00002303
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002304 return Arg;
2305}
2306
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002307SourceRange ParmVarDecl::getDefaultArgRange() const {
2308 if (const Expr *E = getInit())
2309 return E->getSourceRange();
2310
2311 if (hasUninstantiatedDefaultArg())
2312 return getUninstantiatedDefaultArg()->getSourceRange();
2313
2314 return SourceRange();
Argyrios Kyrtzidisfc7e2a82009-07-05 22:21:56 +00002315}
2316
Douglas Gregor1fe85ea2011-01-05 21:11:38 +00002317bool ParmVarDecl::isParameterPack() const {
2318 return isa<PackExpansionType>(getType());
2319}
2320
Ted Kremenekd211cb72011-10-06 05:00:56 +00002321void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2322 getASTContext().setParameterIndex(this, parameterIndex);
2323 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2324}
2325
2326unsigned ParmVarDecl::getParameterIndexLarge() const {
2327 return getASTContext().getParameterIndex(this);
2328}
2329
Nuno Lopes99f06ba2008-12-17 23:39:55 +00002330//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00002331// FunctionDecl Implementation
2332//===----------------------------------------------------------------------===//
2333
Benjamin Kramer5eada842013-02-22 15:46:01 +00002334void FunctionDecl::getNameForDiagnostic(
2335 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2336 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorda2142f2011-02-19 18:51:44 +00002337 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2338 if (TemplateArgs)
Benjamin Kramer5eada842013-02-22 15:46:01 +00002339 TemplateSpecializationType::PrintTemplateArgumentList(
2340 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorda2142f2011-02-19 18:51:44 +00002341}
2342
Ted Kremenek9498d382010-04-29 16:49:01 +00002343bool FunctionDecl::isVariadic() const {
2344 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2345 return FT->isVariadic();
2346 return false;
2347}
2348
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002349bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07002350 for (auto I : redecls()) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00002351 if (I->Body || I->IsLateTemplateParsed) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002352 Definition = I;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002353 return true;
2354 }
2355 }
2356
2357 return false;
2358}
2359
Anders Carlssonffb945f2011-05-14 23:26:09 +00002360bool FunctionDecl::hasTrivialBody() const
2361{
2362 Stmt *S = getBody();
2363 if (!S) {
2364 // Since we don't have a body for this function, we don't know if it's
2365 // trivial or not.
2366 return false;
2367 }
2368
2369 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2370 return true;
2371 return false;
2372}
2373
Sean Hunt10620eb2011-05-06 20:44:56 +00002374bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07002375 for (auto I : redecls()) {
Rafael Espindolab1c0e202013-10-22 21:39:03 +00002376 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2377 I->hasAttr<AliasAttr>()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002378 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Sean Hunt10620eb2011-05-06 20:44:56 +00002379 return true;
2380 }
2381 }
2382
2383 return false;
2384}
2385
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002386Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola65d10962013-10-19 01:37:17 +00002387 if (!hasBody(Definition))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002388 return nullptr;
Rafael Espindola65d10962013-10-19 01:37:17 +00002389
2390 if (Definition->Body)
2391 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregorf0097952008-04-21 02:02:58 +00002392
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002393 return nullptr;
Reid Spencer5f016e22007-07-11 17:01:13 +00002394}
2395
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00002396void FunctionDecl::setBody(Stmt *B) {
2397 Body = B;
Douglas Gregorb5f35ba2010-12-06 17:49:01 +00002398 if (B)
Argyrios Kyrtzidis55d608c2009-06-20 08:09:14 +00002399 EndRangeLoc = B->getLocEnd();
2400}
2401
Douglas Gregor21386642010-09-28 21:55:22 +00002402void FunctionDecl::setPure(bool P) {
2403 IsPure = P;
2404 if (P)
2405 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2406 Parent->markedVirtualFunctionPure();
2407}
2408
Richard Smithddcff1b2013-07-21 23:12:18 +00002409template<std::size_t Len>
2410static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2411 IdentifierInfo *II = ND->getIdentifier();
2412 return II && II->isStr(Str);
2413}
2414
Douglas Gregor48a83b52009-09-12 00:17:51 +00002415bool FunctionDecl::isMain() const {
John McCall23c608d2011-05-15 17:49:20 +00002416 const TranslationUnitDecl *tunit =
2417 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2418 return tunit &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002419 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smithddcff1b2013-07-21 23:12:18 +00002420 isNamed(this, "main");
John McCall23c608d2011-05-15 17:49:20 +00002421}
2422
David Majnemere9f6f332013-09-16 22:44:20 +00002423bool FunctionDecl::isMSVCRTEntryPoint() const {
2424 const TranslationUnitDecl *TUnit =
2425 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2426 if (!TUnit)
2427 return false;
2428
2429 // Even though we aren't really targeting MSVCRT if we are freestanding,
2430 // semantic analysis for these functions remains the same.
2431
2432 // MSVCRT entry points only exist on MSVCRT targets.
2433 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2434 return false;
2435
2436 // Nameless functions like constructors cannot be entry points.
2437 if (!getIdentifier())
2438 return false;
2439
2440 return llvm::StringSwitch<bool>(getName())
2441 .Cases("main", // an ANSI console app
2442 "wmain", // a Unicode console App
2443 "WinMain", // an ANSI GUI app
2444 "wWinMain", // a Unicode GUI app
2445 "DllMain", // a DLL
2446 true)
2447 .Default(false);
2448}
2449
John McCall23c608d2011-05-15 17:49:20 +00002450bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2451 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2452 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2453 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2454 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2455 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2456
Stephen Hines651f13c2014-04-23 16:59:28 -07002457 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2458 return false;
John McCall23c608d2011-05-15 17:49:20 +00002459
2460 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002461 if (proto->getNumParams() != 2 || proto->isVariadic())
2462 return false;
John McCall23c608d2011-05-15 17:49:20 +00002463
2464 ASTContext &Context =
2465 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2466 ->getASTContext();
2467
2468 // The result type and first argument type are constant across all
2469 // these operators. The second argument must be exactly void*.
Stephen Hines651f13c2014-04-23 16:59:28 -07002470 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregor04495c82009-02-24 01:23:02 +00002471}
2472
Richard Smithddcff1b2013-07-21 23:12:18 +00002473bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2474 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2475 return false;
2476 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2477 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2478 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2479 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2480 return false;
2481
2482 if (isa<CXXRecordDecl>(getDeclContext()))
2483 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002484
2485 // This can only fail for an invalid 'operator new' declaration.
2486 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2487 return false;
Richard Smithddcff1b2013-07-21 23:12:18 +00002488
2489 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002490 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smithddcff1b2013-07-21 23:12:18 +00002491 return false;
2492
2493 // If this is a single-parameter function, it must be a replaceable global
2494 // allocation or deallocation function.
Stephen Hines651f13c2014-04-23 16:59:28 -07002495 if (FPT->getNumParams() == 1)
Richard Smithddcff1b2013-07-21 23:12:18 +00002496 return true;
2497
2498 // Otherwise, we're looking for a second parameter whose type is
Richard Smith4cb295d2013-09-29 04:40:38 +00002499 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Stephen Hines651f13c2014-04-23 16:59:28 -07002500 QualType Ty = FPT->getParamType(1);
Richard Smith4cb295d2013-09-29 04:40:38 +00002501 ASTContext &Ctx = getASTContext();
Richard Smith3cebc732013-11-05 09:12:18 +00002502 if (Ctx.getLangOpts().SizedDeallocation &&
2503 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith4cb295d2013-09-29 04:40:38 +00002504 return true;
Richard Smithddcff1b2013-07-21 23:12:18 +00002505 if (!Ty->isReferenceType())
2506 return false;
2507 Ty = Ty->getPointeeType();
2508 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2509 return false;
Richard Smithddcff1b2013-07-21 23:12:18 +00002510 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002511 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
Richard Smithddcff1b2013-07-21 23:12:18 +00002512}
2513
Rafael Espindola950fee22013-02-14 01:18:37 +00002514LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002515 return getDeclLanguageLinkage(*this);
Rafael Espindola78eeba82012-12-28 14:21:58 +00002516}
2517
Rafael Espindola2d1b0962013-03-14 03:07:35 +00002518bool FunctionDecl::isExternC() const {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002519 return isDeclExternC(*this);
Rafael Espindola2d1b0962013-03-14 03:07:35 +00002520}
2521
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002522bool FunctionDecl::isInExternCContext() const {
Serge Pavlov142ab062013-11-14 02:13:03 +00002523 return getLexicalDeclContext()->isExternCContext();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002524}
2525
2526bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov142ab062013-11-14 02:13:03 +00002527 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00002528}
2529
Douglas Gregor8499f3f2009-03-31 16:35:03 +00002530bool FunctionDecl::isGlobal() const {
2531 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2532 return Method->isStatic();
2533
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002534 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregor8499f3f2009-03-31 16:35:03 +00002535 return false;
2536
Mike Stump1eb44332009-09-09 15:08:12 +00002537 for (const DeclContext *DC = getDeclContext();
Douglas Gregor8499f3f2009-03-31 16:35:03 +00002538 DC->isNamespace();
2539 DC = DC->getParent()) {
2540 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2541 if (!Namespace->getDeclName())
2542 return false;
2543 break;
2544 }
2545 }
2546
2547 return true;
2548}
2549
Richard Smithcd8ab512013-01-17 01:30:42 +00002550bool FunctionDecl::isNoReturn() const {
2551 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smith7586a6e2013-01-30 05:45:05 +00002552 hasAttr<C11NoReturnAttr>() ||
Richard Smithcd8ab512013-01-17 01:30:42 +00002553 getType()->getAs<FunctionType>()->getNoReturnAttr();
2554}
2555
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002556void
2557FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindolabc650912013-10-17 15:37:26 +00002558 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002559
2560 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2561 FunctionTemplateDecl *PrevFunTmpl
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002562 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002563 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindolabc650912013-10-17 15:37:26 +00002564 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002565 }
Douglas Gregor8f150942010-12-09 16:59:22 +00002566
Axel Naumannd9d137e2011-11-08 18:21:06 +00002567 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregor8f150942010-12-09 16:59:22 +00002568 IsInline = true;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002569}
2570
2571const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
Rafael Espindolabc650912013-10-17 15:37:26 +00002572 return getFirstDecl();
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002573}
2574
Rafael Espindolabc650912013-10-17 15:37:26 +00002575FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl7783bfc2010-01-26 22:01:41 +00002576
Douglas Gregor3e41d602009-02-13 23:20:09 +00002577/// \brief Returns a value indicating whether this function
2578/// corresponds to a builtin function.
2579///
2580/// The function corresponds to a built-in function if it is
2581/// declared at translation scope or within an extern "C" block and
2582/// its name matches with the name of a builtin. The returned value
2583/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump1eb44332009-09-09 15:08:12 +00002584/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregor3e41d602009-02-13 23:20:09 +00002585/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00002586unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar60d302a2012-03-06 23:52:37 +00002587 if (!getIdentifier())
Douglas Gregor3c385e52009-02-14 18:57:46 +00002588 return 0;
2589
2590 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar60d302a2012-03-06 23:52:37 +00002591 if (!BuiltinID)
2592 return 0;
2593
2594 ASTContext &Context = getASTContext();
Warren Hunt2d023ec2013-11-01 23:46:51 +00002595 if (Context.getLangOpts().CPlusPlus) {
2596 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2597 getFirstDecl()->getDeclContext());
2598 // In C++, the first declaration of a builtin is always inside an implicit
2599 // extern "C".
2600 // FIXME: A recognised library function may not be directly in an extern "C"
2601 // declaration, for instance "extern "C" { namespace std { decl } }".
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002602 if (!LinkageDecl) {
2603 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2604 Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2605 isInStdNamespace())
2606 return Builtin::BI__GetExceptionInfo;
2607 return 0;
2608 }
2609 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt2d023ec2013-11-01 23:46:51 +00002610 return 0;
2611 }
2612
2613 // If the function is marked "overloadable", it has a different mangled name
2614 // and is not the C library function.
Stephen Hines651f13c2014-04-23 16:59:28 -07002615 if (hasAttr<OverloadableAttr>())
Warren Hunt2d023ec2013-11-01 23:46:51 +00002616 return 0;
2617
Douglas Gregor3c385e52009-02-14 18:57:46 +00002618 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2619 return BuiltinID;
2620
2621 // This function has the name of a known C library
2622 // function. Determine whether it actually refers to the C library
2623 // function or whether it just has the same name.
2624
Douglas Gregor9add3172009-02-17 03:23:10 +00002625 // If this is a static function, it's not a builtin.
John McCalld931b082010-08-26 03:08:43 +00002626 if (getStorageClass() == SC_Static)
Douglas Gregor9add3172009-02-17 03:23:10 +00002627 return 0;
2628
Warren Hunt2d023ec2013-11-01 23:46:51 +00002629 return BuiltinID;
Douglas Gregor3e41d602009-02-13 23:20:09 +00002630}
2631
2632
Chris Lattner1ad9b282009-04-25 06:03:53 +00002633/// getNumParams - Return the number of parameters this function must have
Bob Wilson8dbfbf42011-01-10 18:23:55 +00002634/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner1ad9b282009-04-25 06:03:53 +00002635/// after it has been created.
2636unsigned FunctionDecl::getNumParams() const {
Stephen Hines651f13c2014-04-23 16:59:28 -07002637 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
2638 return FPT ? FPT->getNumParams() : 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002639}
2640
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002641void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002642 ArrayRef<ParmVarDecl *> NewParamInfo) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002643 assert(!ParamInfo && "Already has param info!");
David Blaikie4278c652011-09-21 18:16:56 +00002644 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Reid Spencer5f016e22007-07-11 17:01:13 +00002646 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00002647 if (!NewParamInfo.empty()) {
2648 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2649 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 }
2651}
2652
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002653void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy16f1f712012-02-29 10:24:19 +00002654 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2655
2656 if (!NewDecls.empty()) {
2657 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2658 std::copy(NewDecls.begin(), NewDecls.end(), A);
Stephen Hines176edba2014-12-01 14:53:08 -08002659 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002660 // Move declarations introduced in prototype to the function context.
2661 for (auto I : NewDecls) {
2662 DeclContext *DC = I->getDeclContext();
2663 // Forward-declared reference to an enumeration is not added to
2664 // declaration scope, so skip declaration that is absent from its
2665 // declaration contexts.
2666 if (DC->containsDecl(I)) {
2667 DC->removeDecl(I);
2668 I->setDeclContext(this);
2669 addDecl(I);
2670 }
2671 }
James Molloy16f1f712012-02-29 10:24:19 +00002672 }
2673}
2674
Chris Lattner8123a952008-04-10 02:22:51 +00002675/// getMinRequiredArguments - Returns the minimum number of arguments
2676/// needed to call this function. This may be fewer than the number of
2677/// function parameters, if some of the parameters have default
Stephen Hines651f13c2014-04-23 16:59:28 -07002678/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner8123a952008-04-10 02:22:51 +00002679unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikie4e4d0842012-03-11 07:00:24 +00002680 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002681 return getNumParams();
Chris Lattner8123a952008-04-10 02:22:51 +00002682
Stephen Hines651f13c2014-04-23 16:59:28 -07002683 unsigned NumRequiredArgs = 0;
2684 for (auto *Param : params())
2685 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2686 ++NumRequiredArgs;
Chris Lattner8123a952008-04-10 02:22:51 +00002687 return NumRequiredArgs;
2688}
2689
Stephen Hines651f13c2014-04-23 16:59:28 -07002690/// \brief The combination of the extern and inline keywords under MSVC forces
2691/// the function to be required.
2692///
2693/// Note: This function assumes that we will only get called when isInlined()
2694/// would return true for this FunctionDecl.
2695bool FunctionDecl::isMSExternInline() const {
2696 assert(isInlined() && "expected to get called on an inlined function!");
2697
2698 const ASTContext &Context = getASTContext();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002699 if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -07002700 return false;
2701
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07002702 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2703 FD = FD->getPreviousDecl())
Stephen Hines651f13c2014-04-23 16:59:28 -07002704 if (FD->getStorageClass() == SC_Extern)
2705 return true;
2706
2707 return false;
2708}
2709
2710static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2711 if (Redecl->getStorageClass() != SC_Extern)
2712 return false;
2713
2714 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2715 FD = FD->getPreviousDecl())
2716 if (FD->getStorageClass() == SC_Extern)
2717 return false;
2718
2719 return true;
2720}
2721
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002722static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2723 // Only consider file-scope declarations in this test.
2724 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2725 return false;
2726
2727 // Only consider explicit declarations; the presence of a builtin for a
2728 // libcall shouldn't affect whether a definition is externally visible.
2729 if (Redecl->isImplicit())
2730 return false;
2731
2732 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2733 return true; // Not an inline definition
2734
2735 return false;
2736}
2737
Nick Lewyckydce67a72011-07-18 05:26:13 +00002738/// \brief For a function declaration in C or C++, determine whether this
2739/// declaration causes the definition to be externally visible.
2740///
Stephen Hines651f13c2014-04-23 16:59:28 -07002741/// For instance, this determines if adding the current declaration to the set
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002742/// of redeclarations of the given functions causes
2743/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewyckydce67a72011-07-18 05:26:13 +00002744bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2745 assert(!doesThisDeclarationHaveABody() &&
2746 "Must have a declaration without a body.");
2747
2748 ASTContext &Context = getASTContext();
2749
Stephen Hines651f13c2014-04-23 16:59:28 -07002750 if (Context.getLangOpts().MSVCCompat) {
2751 const FunctionDecl *Definition;
2752 if (hasBody(Definition) && Definition->isInlined() &&
2753 redeclForcesDefMSVC(this))
2754 return true;
2755 }
2756
David Blaikie4e4d0842012-03-11 07:00:24 +00002757 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002758 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2759 // an externally visible definition.
2760 //
2761 // FIXME: What happens if gnu_inline gets added on after the first
2762 // declaration?
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002763 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002764 return false;
2765
2766 const FunctionDecl *Prev = this;
2767 bool FoundBody = false;
2768 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7247c882013-05-15 07:37:26 +00002769 FoundBody |= Prev->Body.isValid();
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002770
2771 if (Prev->Body) {
2772 // If it's not the case that both 'inline' and 'extern' are
2773 // specified on the definition, then it is always externally visible.
2774 if (!Prev->isInlineSpecified() ||
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002775 Prev->getStorageClass() != SC_Extern)
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002776 return false;
2777 } else if (Prev->isInlineSpecified() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002778 Prev->getStorageClass() != SC_Extern) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002779 return false;
2780 }
2781 }
2782 return FoundBody;
2783 }
2784
David Blaikie4e4d0842012-03-11 07:00:24 +00002785 if (Context.getLangOpts().CPlusPlus)
Nick Lewyckydce67a72011-07-18 05:26:13 +00002786 return false;
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002787
2788 // C99 6.7.4p6:
2789 // [...] If all of the file scope declarations for a function in a
2790 // translation unit include the inline function specifier without extern,
2791 // then the definition in that translation unit is an inline definition.
2792 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewyckydce67a72011-07-18 05:26:13 +00002793 return false;
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002794 const FunctionDecl *Prev = this;
2795 bool FoundBody = false;
2796 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7247c882013-05-15 07:37:26 +00002797 FoundBody |= Prev->Body.isValid();
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002798 if (RedeclForcesDefC99(Prev))
2799 return false;
2800 }
2801 return FoundBody;
Nick Lewyckydce67a72011-07-18 05:26:13 +00002802}
2803
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002804SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2805 const TypeSourceInfo *TSI = getTypeSourceInfo();
2806 if (!TSI)
2807 return SourceRange();
2808 FunctionTypeLoc FTL =
2809 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2810 if (!FTL)
2811 return SourceRange();
2812
2813 // Skip self-referential return types.
2814 const SourceManager &SM = getASTContext().getSourceManager();
2815 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2816 SourceLocation Boundary = getNameInfo().getLocStart();
2817 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2818 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2819 return SourceRange();
2820
2821 return RTRange;
2822}
2823
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07002824bool FunctionDecl::hasUnusedResultAttr() const {
2825 QualType RetType = getReturnType();
2826 if (RetType->isRecordType()) {
2827 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
2828 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(this);
2829 if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
2830 !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
2831 return true;
2832 }
2833 return hasAttr<WarnUnusedResultAttr>();
2834}
2835
Richard Smithd4497dd2013-01-25 00:08:28 +00002836/// \brief For an inline function definition in C, or for a gnu_inline function
2837/// in C++, determine whether the definition will be externally visible.
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002838///
2839/// Inline function definitions are always available for inlining optimizations.
2840/// However, depending on the language dialect, declaration specifiers, and
2841/// attributes, the definition of an inline function may or may not be
2842/// "externally" visible to other translation units in the program.
2843///
2844/// In C99, inline definitions are not externally visible by default. However,
Mike Stump1e5fd7f2010-01-06 02:05:39 +00002845/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002846/// inline definition becomes externally visible (C99 6.7.4p6).
2847///
2848/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2849/// definition, we use the GNU semantics for inline, which are nearly the
2850/// opposite of C99 semantics. In particular, "inline" by itself will create
2851/// an externally visible symbol, but "extern inline" will not create an
2852/// externally visible symbol.
2853bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Sean Hunt10620eb2011-05-06 20:44:56 +00002854 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002855 assert(isInlined() && "Function must be inline");
Douglas Gregor7d9c3c92009-10-27 23:26:40 +00002856 ASTContext &Context = getASTContext();
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002857
David Blaikie4e4d0842012-03-11 07:00:24 +00002858 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002859 // Note: If you change the logic here, please change
2860 // doesDeclarationForceExternallyVisibleDefinition as well.
2861 //
Douglas Gregor8f150942010-12-09 16:59:22 +00002862 // If it's not the case that both 'inline' and 'extern' are
2863 // specified on the definition, then this inline definition is
2864 // externally visible.
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002865 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregor8f150942010-12-09 16:59:22 +00002866 return true;
2867
2868 // If any declaration is 'inline' but not 'extern', then this definition
2869 // is externally visible.
Stephen Hines651f13c2014-04-23 16:59:28 -07002870 for (auto Redecl : redecls()) {
Douglas Gregor8f150942010-12-09 16:59:22 +00002871 if (Redecl->isInlineSpecified() &&
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002872 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002873 return true;
Douglas Gregor8f150942010-12-09 16:59:22 +00002874 }
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002875
Douglas Gregor9f9bf252009-04-28 06:37:30 +00002876 return false;
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002877 }
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002878
Richard Smithd4497dd2013-01-25 00:08:28 +00002879 // The rest of this function is C-only.
2880 assert(!Context.getLangOpts().CPlusPlus &&
2881 "should not use C inline rules in C++");
2882
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002883 // C99 6.7.4p6:
2884 // [...] If all of the file scope declarations for a function in a
2885 // translation unit include the inline function specifier without extern,
2886 // then the definition in that translation unit is an inline definition.
Stephen Hines651f13c2014-04-23 16:59:28 -07002887 for (auto Redecl : redecls()) {
2888 if (RedeclForcesDefC99(Redecl))
Eli Friedmana3b9fa22012-02-07 03:50:18 +00002889 return true;
Douglas Gregor1fc09a92009-09-13 07:46:26 +00002890 }
2891
2892 // C99 6.7.4p6:
2893 // An inline definition does not provide an external definition for the
2894 // function, and does not forbid an external definition in another
2895 // translation unit.
Douglas Gregor9f9bf252009-04-28 06:37:30 +00002896 return false;
2897}
2898
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002899/// getOverloadedOperator - Which C++ overloaded operator this
2900/// function represents, if any.
2901OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregore94ca9e42008-11-18 14:39:36 +00002902 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2903 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002904 else
2905 return OO_None;
2906}
2907
Sean Hunta6c058d2010-01-13 09:01:02 +00002908/// getLiteralIdentifier - The literal suffix identifier this function
2909/// represents, if any.
2910const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2911 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2912 return getDeclName().getCXXLiteralIdentifier();
2913 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002914 return nullptr;
Sean Hunta6c058d2010-01-13 09:01:02 +00002915}
2916
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002917FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2918 if (TemplateOrSpecialization.isNull())
2919 return TK_NonTemplate;
2920 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2921 return TK_FunctionTemplate;
2922 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2923 return TK_MemberSpecialization;
2924 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2925 return TK_FunctionTemplateSpecialization;
2926 if (TemplateOrSpecialization.is
2927 <DependentFunctionTemplateSpecializationInfo*>())
2928 return TK_DependentFunctionTemplateSpecialization;
2929
David Blaikieb219cfc2011-09-23 05:06:16 +00002930 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidisd0913552010-06-22 09:54:51 +00002931}
2932
Douglas Gregor2db32322009-10-07 23:56:10 +00002933FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00002934 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregor2db32322009-10-07 23:56:10 +00002935 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002936
2937 return nullptr;
Douglas Gregor2db32322009-10-07 23:56:10 +00002938}
2939
2940void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002941FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2942 FunctionDecl *FD,
Douglas Gregor2db32322009-10-07 23:56:10 +00002943 TemplateSpecializationKind TSK) {
2944 assert(TemplateOrSpecialization.isNull() &&
2945 "Member function is already a specialization");
2946 MemberSpecializationInfo *Info
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00002947 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregor2db32322009-10-07 23:56:10 +00002948 TemplateOrSpecialization = Info;
2949}
2950
Douglas Gregor3b846b62009-10-27 20:53:28 +00002951bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002952 // If the function is invalid, it can't be implicitly instantiated.
2953 if (isInvalidDecl())
Douglas Gregor3b846b62009-10-27 20:53:28 +00002954 return false;
2955
2956 switch (getTemplateSpecializationKind()) {
2957 case TSK_Undeclared:
Douglas Gregor3b846b62009-10-27 20:53:28 +00002958 case TSK_ExplicitInstantiationDefinition:
2959 return false;
2960
2961 case TSK_ImplicitInstantiation:
2962 return true;
2963
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002964 // It is possible to instantiate TSK_ExplicitSpecialization kind
2965 // if the FunctionDecl has a class scope specialization pattern.
2966 case TSK_ExplicitSpecialization:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002967 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002968
Douglas Gregor3b846b62009-10-27 20:53:28 +00002969 case TSK_ExplicitInstantiationDeclaration:
2970 // Handled below.
2971 break;
2972 }
2973
2974 // Find the actual template from which we will instantiate.
2975 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002976 bool HasPattern = false;
Douglas Gregor3b846b62009-10-27 20:53:28 +00002977 if (PatternDecl)
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002978 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregor3b846b62009-10-27 20:53:28 +00002979
2980 // C++0x [temp.explicit]p9:
2981 // Except for inline functions, other explicit instantiation declarations
2982 // have the effect of suppressing the implicit instantiation of the entity
2983 // to which they refer.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002984 if (!HasPattern || !PatternDecl)
Douglas Gregor3b846b62009-10-27 20:53:28 +00002985 return true;
2986
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002987 return PatternDecl->isInlined();
Ted Kremenek75df4ee2011-12-01 00:59:17 +00002988}
2989
2990bool FunctionDecl::isTemplateInstantiation() const {
2991 switch (getTemplateSpecializationKind()) {
2992 case TSK_Undeclared:
2993 case TSK_ExplicitSpecialization:
2994 return false;
2995 case TSK_ImplicitInstantiation:
2996 case TSK_ExplicitInstantiationDeclaration:
2997 case TSK_ExplicitInstantiationDefinition:
2998 return true;
2999 }
3000 llvm_unreachable("All TSK values handled.");
3001}
Douglas Gregor3b846b62009-10-27 20:53:28 +00003002
3003FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003004 // Handle class scope explicit specialization special case.
3005 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3006 return getClassScopeSpecializationPattern();
Stephen Hines651f13c2014-04-23 16:59:28 -07003007
3008 // If this is a generic lambda call operator specialization, its
3009 // instantiation pattern is always its primary template's pattern
3010 // even if its primary template was instantiated from another
3011 // member template (which happens with nested generic lambdas).
3012 // Since a lambda's call operator's body is transformed eagerly,
3013 // we don't have to go hunting for a prototype definition template
3014 // (i.e. instantiated-from-member-template) to use as an instantiation
3015 // pattern.
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003016
Stephen Hines651f13c2014-04-23 16:59:28 -07003017 if (isGenericLambdaCallOperatorSpecialization(
3018 dyn_cast<CXXMethodDecl>(this))) {
3019 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3020 "generated from a primary call operator "
3021 "template");
3022 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3023 "A generic lambda call operator template must always have a body - "
3024 "even if instantiated from a prototype (i.e. as written) member "
3025 "template");
3026 return getPrimaryTemplate()->getTemplatedDecl();
3027 }
3028
Douglas Gregor3b846b62009-10-27 20:53:28 +00003029 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3030 while (Primary->getInstantiatedFromMemberTemplate()) {
3031 // If we have hit a point where the user provided a specialization of
3032 // this template, we're done looking.
3033 if (Primary->isMemberSpecialization())
3034 break;
Douglas Gregor3b846b62009-10-27 20:53:28 +00003035 Primary = Primary->getInstantiatedFromMemberTemplate();
3036 }
3037
3038 return Primary->getTemplatedDecl();
3039 }
3040
3041 return getInstantiatedFromMemberFunction();
3042}
3043
Douglas Gregor16e8be22009-06-29 17:30:29 +00003044FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump1eb44332009-09-09 15:08:12 +00003045 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00003046 = TemplateOrSpecialization
3047 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00003048 return Info->Template.getPointer();
Douglas Gregor16e8be22009-06-29 17:30:29 +00003049 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003050 return nullptr;
Douglas Gregor16e8be22009-06-29 17:30:29 +00003051}
3052
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003053FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3054 return getASTContext().getClassScopeSpecializationPattern(this);
3055}
3056
Douglas Gregor16e8be22009-06-29 17:30:29 +00003057const TemplateArgumentList *
3058FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump1eb44332009-09-09 15:08:12 +00003059 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorfd056bc2009-10-13 16:30:37 +00003060 = TemplateOrSpecialization
3061 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor16e8be22009-06-29 17:30:29 +00003062 return Info->TemplateArguments;
3063 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003064 return nullptr;
Douglas Gregor16e8be22009-06-29 17:30:29 +00003065}
3066
Argyrios Kyrtzidis71a76052011-09-22 20:07:09 +00003067const ASTTemplateArgumentListInfo *
Abramo Bagnarae03db982010-05-20 15:32:11 +00003068FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3069 if (FunctionTemplateSpecializationInfo *Info
3070 = TemplateOrSpecialization
3071 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3072 return Info->TemplateArgumentsAsWritten;
3073 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003074 return nullptr;
Abramo Bagnarae03db982010-05-20 15:32:11 +00003075}
3076
Mike Stump1eb44332009-09-09 15:08:12 +00003077void
Argyrios Kyrtzidis6b541512010-09-08 19:31:22 +00003078FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3079 FunctionTemplateDecl *Template,
Douglas Gregor127102b2009-06-29 20:59:39 +00003080 const TemplateArgumentList *TemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003081 void *InsertPos,
Abramo Bagnarae03db982010-05-20 15:32:11 +00003082 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis7b081c82010-07-05 10:37:55 +00003083 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3084 SourceLocation PointOfInstantiation) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00003085 assert(TSK != TSK_Undeclared &&
3086 "Must specify the type of function template specialization");
Mike Stump1eb44332009-09-09 15:08:12 +00003087 FunctionTemplateSpecializationInfo *Info
Douglas Gregor16e8be22009-06-29 17:30:29 +00003088 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor1637be72009-06-26 00:10:03 +00003089 if (!Info)
Argyrios Kyrtzidisa626a3d2010-09-09 11:28:23 +00003090 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3091 TemplateArgs,
3092 TemplateArgsAsWritten,
3093 PointOfInstantiation);
Douglas Gregor1637be72009-06-26 00:10:03 +00003094 TemplateOrSpecialization = Info;
Douglas Gregor1e1e9722012-03-28 14:34:23 +00003095 Template->addSpecialization(Info, InsertPos);
Douglas Gregor1637be72009-06-26 00:10:03 +00003096}
3097
John McCallaf2094e2010-04-08 09:05:18 +00003098void
3099FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3100 const UnresolvedSetImpl &Templates,
3101 const TemplateArgumentListInfo &TemplateArgs) {
3102 assert(TemplateOrSpecialization.isNull());
3103 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
3104 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall21c01602010-04-13 22:18:28 +00003105 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallaf2094e2010-04-08 09:05:18 +00003106 void *Buffer = Context.Allocate(Size);
3107 DependentFunctionTemplateSpecializationInfo *Info =
3108 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
3109 TemplateArgs);
3110 TemplateOrSpecialization = Info;
3111}
3112
3113DependentFunctionTemplateSpecializationInfo::
3114DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3115 const TemplateArgumentListInfo &TArgs)
3116 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -07003117 static_assert(sizeof(*this) % llvm::AlignOf<void *>::Alignment == 0,
3118 "Trailing data is unaligned!");
John McCallaf2094e2010-04-08 09:05:18 +00003119
3120 d.NumTemplates = Ts.size();
3121 d.NumArgs = TArgs.size();
3122
3123 FunctionTemplateDecl **TsArray =
3124 const_cast<FunctionTemplateDecl**>(getTemplates());
3125 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3126 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3127
3128 TemplateArgumentLoc *ArgsArray =
3129 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
3130 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3131 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3132}
3133
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003134TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump1eb44332009-09-09 15:08:12 +00003135 // For a function template specialization, query the specialization
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003136 // information object.
Douglas Gregor2db32322009-10-07 23:56:10 +00003137 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00003138 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor2db32322009-10-07 23:56:10 +00003139 if (FTSInfo)
3140 return FTSInfo->getTemplateSpecializationKind();
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Douglas Gregor2db32322009-10-07 23:56:10 +00003142 MemberSpecializationInfo *MSInfo
3143 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3144 if (MSInfo)
3145 return MSInfo->getTemplateSpecializationKind();
3146
3147 return TSK_Undeclared;
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003148}
3149
Mike Stump1eb44332009-09-09 15:08:12 +00003150void
Douglas Gregor0a897e32009-10-15 17:21:20 +00003151FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3152 SourceLocation PointOfInstantiation) {
3153 if (FunctionTemplateSpecializationInfo *FTSInfo
3154 = TemplateOrSpecialization.dyn_cast<
3155 FunctionTemplateSpecializationInfo*>()) {
3156 FTSInfo->setTemplateSpecializationKind(TSK);
3157 if (TSK != TSK_ExplicitSpecialization &&
3158 PointOfInstantiation.isValid() &&
3159 FTSInfo->getPointOfInstantiation().isInvalid())
3160 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3161 } else if (MemberSpecializationInfo *MSInfo
3162 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3163 MSInfo->setTemplateSpecializationKind(TSK);
3164 if (TSK != TSK_ExplicitSpecialization &&
3165 PointOfInstantiation.isValid() &&
3166 MSInfo->getPointOfInstantiation().isInvalid())
3167 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3168 } else
David Blaikieb219cfc2011-09-23 05:06:16 +00003169 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor0a897e32009-10-15 17:21:20 +00003170}
3171
3172SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregor2db32322009-10-07 23:56:10 +00003173 if (FunctionTemplateSpecializationInfo *FTSInfo
3174 = TemplateOrSpecialization.dyn_cast<
3175 FunctionTemplateSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00003176 return FTSInfo->getPointOfInstantiation();
Douglas Gregor2db32322009-10-07 23:56:10 +00003177 else if (MemberSpecializationInfo *MSInfo
3178 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor0a897e32009-10-15 17:21:20 +00003179 return MSInfo->getPointOfInstantiation();
3180
3181 return SourceLocation();
Douglas Gregor1fd2dd12009-06-29 22:39:32 +00003182}
3183
Douglas Gregor9f185072009-09-11 20:15:17 +00003184bool FunctionDecl::isOutOfLine() const {
Douglas Gregorda2142f2011-02-19 18:51:44 +00003185 if (Decl::isOutOfLine())
Douglas Gregor9f185072009-09-11 20:15:17 +00003186 return true;
3187
3188 // If this function was instantiated from a member function of a
3189 // class template, check whether that member function was defined out-of-line.
3190 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3191 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003192 if (FD->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00003193 return Definition->isOutOfLine();
3194 }
3195
3196 // If this function was instantiated from a function template,
3197 // check whether that function template was defined out-of-line.
3198 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3199 const FunctionDecl *Definition;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00003200 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor9f185072009-09-11 20:15:17 +00003201 return Definition->isOutOfLine();
3202 }
3203
3204 return false;
3205}
3206
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00003207SourceRange FunctionDecl::getSourceRange() const {
3208 return SourceRange(getOuterLocStart(), EndRangeLoc);
3209}
3210
Anna Zaks9392d4e2012-01-18 02:45:01 +00003211unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaksd9b859a2012-01-13 21:52:01 +00003212 IdentifierInfo *FnInfo = getIdentifier();
3213
3214 if (!FnInfo)
Anna Zaks0a151a12012-01-17 00:37:07 +00003215 return 0;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003216
3217 // Builtin handling.
3218 switch (getBuiltinID()) {
3219 case Builtin::BI__builtin_memset:
3220 case Builtin::BI__builtin___memset_chk:
3221 case Builtin::BImemset:
Anna Zaks0a151a12012-01-17 00:37:07 +00003222 return Builtin::BImemset;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003223
3224 case Builtin::BI__builtin_memcpy:
3225 case Builtin::BI__builtin___memcpy_chk:
3226 case Builtin::BImemcpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00003227 return Builtin::BImemcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003228
3229 case Builtin::BI__builtin_memmove:
3230 case Builtin::BI__builtin___memmove_chk:
3231 case Builtin::BImemmove:
Anna Zaks0a151a12012-01-17 00:37:07 +00003232 return Builtin::BImemmove;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003233
3234 case Builtin::BIstrlcpy:
Stephen Hines176edba2014-12-01 14:53:08 -08003235 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks0a151a12012-01-17 00:37:07 +00003236 return Builtin::BIstrlcpy;
Stephen Hines176edba2014-12-01 14:53:08 -08003237
Anna Zaksd9b859a2012-01-13 21:52:01 +00003238 case Builtin::BIstrlcat:
Stephen Hines176edba2014-12-01 14:53:08 -08003239 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks0a151a12012-01-17 00:37:07 +00003240 return Builtin::BIstrlcat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003241
3242 case Builtin::BI__builtin_memcmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00003243 case Builtin::BImemcmp:
3244 return Builtin::BImemcmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003245
3246 case Builtin::BI__builtin_strncpy:
3247 case Builtin::BI__builtin___strncpy_chk:
3248 case Builtin::BIstrncpy:
Anna Zaks0a151a12012-01-17 00:37:07 +00003249 return Builtin::BIstrncpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003250
3251 case Builtin::BI__builtin_strncmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00003252 case Builtin::BIstrncmp:
3253 return Builtin::BIstrncmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003254
3255 case Builtin::BI__builtin_strncasecmp:
Anna Zaks0a151a12012-01-17 00:37:07 +00003256 case Builtin::BIstrncasecmp:
3257 return Builtin::BIstrncasecmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003258
3259 case Builtin::BI__builtin_strncat:
Anna Zaksc36bedc2012-02-01 19:08:57 +00003260 case Builtin::BI__builtin___strncat_chk:
Anna Zaksd9b859a2012-01-13 21:52:01 +00003261 case Builtin::BIstrncat:
Anna Zaks0a151a12012-01-17 00:37:07 +00003262 return Builtin::BIstrncat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003263
3264 case Builtin::BI__builtin_strndup:
3265 case Builtin::BIstrndup:
Anna Zaks0a151a12012-01-17 00:37:07 +00003266 return Builtin::BIstrndup;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003267
Anna Zaksc36bedc2012-02-01 19:08:57 +00003268 case Builtin::BI__builtin_strlen:
3269 case Builtin::BIstrlen:
3270 return Builtin::BIstrlen;
3271
Anna Zaksd9b859a2012-01-13 21:52:01 +00003272 default:
Rafael Espindolad2fdd422013-02-14 01:47:04 +00003273 if (isExternC()) {
Anna Zaksd9b859a2012-01-13 21:52:01 +00003274 if (FnInfo->isStr("memset"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003275 return Builtin::BImemset;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003276 else if (FnInfo->isStr("memcpy"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003277 return Builtin::BImemcpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003278 else if (FnInfo->isStr("memmove"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003279 return Builtin::BImemmove;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003280 else if (FnInfo->isStr("memcmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003281 return Builtin::BImemcmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003282 else if (FnInfo->isStr("strncpy"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003283 return Builtin::BIstrncpy;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003284 else if (FnInfo->isStr("strncmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003285 return Builtin::BIstrncmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003286 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003287 return Builtin::BIstrncasecmp;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003288 else if (FnInfo->isStr("strncat"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003289 return Builtin::BIstrncat;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003290 else if (FnInfo->isStr("strndup"))
Anna Zaks0a151a12012-01-17 00:37:07 +00003291 return Builtin::BIstrndup;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003292 else if (FnInfo->isStr("strlen"))
3293 return Builtin::BIstrlen;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003294 }
3295 break;
3296 }
Anna Zaks0a151a12012-01-17 00:37:07 +00003297 return 0;
Anna Zaksd9b859a2012-01-13 21:52:01 +00003298}
3299
Chris Lattner8a934232008-03-31 00:36:02 +00003300//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003301// FieldDecl Implementation
3302//===----------------------------------------------------------------------===//
3303
Jay Foad4ba2a172011-01-12 09:06:06 +00003304FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003305 SourceLocation StartLoc, SourceLocation IdLoc,
3306 IdentifierInfo *Id, QualType T,
Richard Smith7a614d82011-06-11 17:19:42 +00003307 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smithca523302012-06-10 03:12:00 +00003308 InClassInitStyle InitStyle) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003309 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3310 BW, Mutable, InitStyle);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003311}
3312
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003313FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003314 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3315 SourceLocation(), nullptr, QualType(), nullptr,
3316 nullptr, false, ICIS_NoInit);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003317}
3318
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003319bool FieldDecl::isAnonymousStructOrUnion() const {
3320 if (!isImplicit() || getDeclName())
3321 return false;
3322
3323 if (const RecordType *Record = getType()->getAs<RecordType>())
3324 return Record->getDecl()->isAnonymousStructOrUnion();
3325
3326 return false;
3327}
3328
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003329unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3330 assert(isBitField() && "not a bitfield");
Stephen Hines176edba2014-12-01 14:53:08 -08003331 Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003332 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3333}
3334
John McCallba4f5d52011-01-20 07:57:12 +00003335unsigned FieldDecl::getFieldIndex() const {
Richard Smith4ed01222013-10-07 08:02:11 +00003336 const FieldDecl *Canonical = getCanonicalDecl();
3337 if (Canonical != this)
3338 return Canonical->getFieldIndex();
3339
John McCallba4f5d52011-01-20 07:57:12 +00003340 if (CachedFieldIndex) return CachedFieldIndex - 1;
3341
Richard Smith180f4792011-11-10 06:34:14 +00003342 unsigned Index = 0;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +00003343 const RecordDecl *RD = getParent();
Richard Smith180f4792011-11-10 06:34:14 +00003344
Stephen Hines176edba2014-12-01 14:53:08 -08003345 for (auto *Field : RD->fields()) {
3346 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3347 ++Index;
3348 }
John McCallba4f5d52011-01-20 07:57:12 +00003349
Richard Smith180f4792011-11-10 06:34:14 +00003350 assert(CachedFieldIndex && "failed to find field in parent");
3351 return CachedFieldIndex - 1;
John McCallba4f5d52011-01-20 07:57:12 +00003352}
3353
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00003354SourceRange FieldDecl::getSourceRange() const {
Stephen Hines176edba2014-12-01 14:53:08 -08003355 switch (InitStorage.getInt()) {
3356 // All three of these cases store an optional Expr*.
3357 case ISK_BitWidthOrNothing:
3358 case ISK_InClassCopyInit:
3359 case ISK_InClassListInit:
3360 if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
3361 return SourceRange(getInnerLocStart(), E->getLocEnd());
3362 // FALLTHROUGH
3363
3364 case ISK_CapturedVLAType:
3365 return DeclaratorDecl::getSourceRange();
3366 }
3367 llvm_unreachable("bad init storage kind");
Abramo Bagnaraf2cf5622011-03-08 11:07:11 +00003368}
3369
Stephen Hines176edba2014-12-01 14:53:08 -08003370void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3371 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
3372 "capturing type in non-lambda or captured record.");
3373 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3374 InitStorage.getPointer() == nullptr &&
3375 "bit width, initializer or captured type already set");
3376 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3377 ISK_CapturedVLAType);
Richard Smith7a614d82011-06-11 17:19:42 +00003378}
3379
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003380//===----------------------------------------------------------------------===//
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003381// TagDecl Implementation
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003382//===----------------------------------------------------------------------===//
3383
Douglas Gregor1693e152010-07-06 18:42:40 +00003384SourceLocation TagDecl::getOuterLocStart() const {
3385 return getTemplateOrInnerLocStart(this);
3386}
3387
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00003388SourceRange TagDecl::getSourceRange() const {
3389 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregor1693e152010-07-06 18:42:40 +00003390 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidisf602c8b2009-07-14 03:17:17 +00003391}
3392
Rafael Espindolabc650912013-10-17 15:37:26 +00003393TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidisb57a4fe2009-07-18 00:34:07 +00003394
Rafael Espindola2d9e8832013-03-12 21:06:00 +00003395void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemeraa824612013-09-17 23:57:10 +00003396 NamedDeclOrQualifier = TDD;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003397 if (const Type *T = getTypeForDecl()) {
3398 (void)T;
3399 assert(T->isLinkageValid());
3400 }
Rafael Espindola2d1b0962013-03-14 03:07:35 +00003401 assert(isLinkageValid());
Douglas Gregor60e70642010-05-19 18:39:18 +00003402}
3403
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003404void TagDecl::startDefinition() {
Sebastian Redled48a8f2010-08-02 18:27:05 +00003405 IsBeingDefined = true;
John McCall86ff3082010-02-04 22:26:26 +00003406
David Blaikie66cff722012-11-14 01:52:05 +00003407 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003408 struct CXXRecordDecl::DefinitionData *Data =
John McCall86ff3082010-02-04 22:26:26 +00003409 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Stephen Hines651f13c2014-04-23 16:59:28 -07003410 for (auto I : redecls())
3411 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall86ff3082010-02-04 22:26:26 +00003412 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003413}
3414
3415void TagDecl::completeDefinition() {
John McCall5cfa0112010-02-05 01:33:36 +00003416 assert((!isa<CXXRecordDecl>(this) ||
3417 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3418 "definition completed but not started");
3419
John McCall5e1cdac2011-10-07 06:10:15 +00003420 IsCompleteDefinition = true;
Sebastian Redled48a8f2010-08-02 18:27:05 +00003421 IsBeingDefined = false;
Argyrios Kyrtzidis565bf302010-10-24 17:26:50 +00003422
3423 if (ASTMutationListener *L = getASTMutationListener())
3424 L->CompletedTagDefinition(this);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003425}
3426
John McCall5e1cdac2011-10-07 06:10:15 +00003427TagDecl *TagDecl::getDefinition() const {
3428 if (isCompleteDefinition())
Douglas Gregor8e9e9ef2009-07-29 23:36:44 +00003429 return const_cast<TagDecl *>(this);
Douglas Gregor6bd99292013-02-09 01:35:03 +00003430
3431 // If it's possible for us to have an out-of-date definition, check now.
3432 if (MayHaveOutOfDateDef) {
3433 if (IdentifierInfo *II = getIdentifier()) {
3434 if (II->isOutOfDate()) {
3435 updateOutOfDate(*II);
3436 }
3437 }
3438 }
3439
Andrew Trick220a9c82010-10-19 21:54:32 +00003440 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3441 return CXXRD->getDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Stephen Hines651f13c2014-04-23 16:59:28 -07003443 for (auto R : redecls())
John McCall5e1cdac2011-10-07 06:10:15 +00003444 if (R->isCompleteDefinition())
Stephen Hines651f13c2014-04-23 16:59:28 -07003445 return R;
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003447 return nullptr;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003448}
3449
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00003450void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3451 if (QualifierLoc) {
John McCallb6217662010-03-15 10:12:16 +00003452 // Make sure the extended qualifier info is allocated.
3453 if (!hasExtInfo())
David Majnemeraa824612013-09-17 23:57:10 +00003454 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCallb6217662010-03-15 10:12:16 +00003455 // Set qualifier info.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00003456 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier30601782011-08-17 23:08:45 +00003457 } else {
John McCallb6217662010-03-15 10:12:16 +00003458 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCallb6217662010-03-15 10:12:16 +00003459 if (hasExtInfo()) {
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00003460 if (getExtInfo()->NumTemplParamLists == 0) {
3461 getASTContext().Deallocate(getExtInfo());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003462 NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00003463 }
3464 else
3465 getExtInfo()->QualifierLoc = QualifierLoc;
John McCallb6217662010-03-15 10:12:16 +00003466 }
3467 }
3468}
3469
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00003470void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3471 unsigned NumTPLists,
3472 TemplateParameterList **TPLists) {
3473 assert(NumTPLists > 0);
3474 // Make sure the extended decl info is allocated.
3475 if (!hasExtInfo())
3476 // Allocate external info struct.
David Majnemeraa824612013-09-17 23:57:10 +00003477 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00003478 // Set the template parameter lists info.
3479 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3480}
3481
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003482//===----------------------------------------------------------------------===//
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003483// EnumDecl Implementation
3484//===----------------------------------------------------------------------===//
3485
David Blaikie99ba9e32011-12-20 02:48:34 +00003486void EnumDecl::anchor() { }
3487
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003488EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3489 SourceLocation StartLoc, SourceLocation IdLoc,
3490 IdentifierInfo *Id,
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00003491 EnumDecl *PrevDecl, bool IsScoped,
3492 bool IsScopedUsingClassTag, bool IsFixed) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003493 EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
Stephen Hines651f13c2014-04-23 16:59:28 -07003494 IsScoped, IsScopedUsingClassTag,
3495 IsFixed);
Douglas Gregor6bd99292013-02-09 01:35:03 +00003496 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003497 C.getTypeDeclType(Enum, PrevDecl);
3498 return Enum;
3499}
3500
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003501EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003502 EnumDecl *Enum =
3503 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3504 nullptr, nullptr, false, false, false);
Douglas Gregor6bd99292013-02-09 01:35:03 +00003505 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3506 return Enum;
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00003507}
3508
Stephen Hines651f13c2014-04-23 16:59:28 -07003509SourceRange EnumDecl::getIntegerTypeRange() const {
3510 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3511 return TI->getTypeLoc().getSourceRange();
3512 return SourceRange();
3513}
3514
Douglas Gregor838db382010-02-11 01:19:42 +00003515void EnumDecl::completeDefinition(QualType NewType,
John McCall1b5a6182010-05-06 08:49:23 +00003516 QualType NewPromotionType,
3517 unsigned NumPositiveBits,
3518 unsigned NumNegativeBits) {
John McCall5e1cdac2011-10-07 06:10:15 +00003519 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor1274ccd2010-10-08 23:50:27 +00003520 if (!IntegerType)
3521 IntegerType = NewType.getTypePtr();
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003522 PromotionType = NewPromotionType;
John McCall1b5a6182010-05-06 08:49:23 +00003523 setNumPositiveBits(NumPositiveBits);
3524 setNumNegativeBits(NumNegativeBits);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003525 TagDecl::completeDefinition();
3526}
3527
Richard Smith1af83c42012-03-23 03:33:32 +00003528TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3529 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3530 return MSI->getTemplateSpecializationKind();
3531
3532 return TSK_Undeclared;
3533}
3534
3535void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3536 SourceLocation PointOfInstantiation) {
3537 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3538 assert(MSI && "Not an instantiated member enumeration?");
3539 MSI->setTemplateSpecializationKind(TSK);
3540 if (TSK != TSK_ExplicitSpecialization &&
3541 PointOfInstantiation.isValid() &&
3542 MSI->getPointOfInstantiation().isInvalid())
3543 MSI->setPointOfInstantiation(PointOfInstantiation);
3544}
3545
Richard Smithf1c66b42012-03-14 23:13:10 +00003546EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3547 if (SpecializationInfo)
3548 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3549
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003550 return nullptr;
Richard Smithf1c66b42012-03-14 23:13:10 +00003551}
3552
3553void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3554 TemplateSpecializationKind TSK) {
3555 assert(!SpecializationInfo && "Member enum is already a specialization");
3556 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3557}
3558
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003559//===----------------------------------------------------------------------===//
Chris Lattner8a934232008-03-31 00:36:02 +00003560// RecordDecl Implementation
3561//===----------------------------------------------------------------------===//
Reid Spencer5f016e22007-07-11 17:01:13 +00003562
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003563RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3564 DeclContext *DC, SourceLocation StartLoc,
3565 SourceLocation IdLoc, IdentifierInfo *Id,
3566 RecordDecl *PrevDecl)
3567 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek63597922008-09-02 21:12:32 +00003568 HasFlexibleArrayMember = false;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003569 AnonymousStructOrUnion = false;
Fariborz Jahanian082b02e2009-07-08 01:18:33 +00003570 HasObjectMember = false;
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +00003571 HasVolatileMember = false;
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003572 LoadedFieldsFromExternalStorage = false;
Ted Kremenek63597922008-09-02 21:12:32 +00003573 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek63597922008-09-02 21:12:32 +00003574}
3575
Jay Foad4ba2a172011-01-12 09:06:06 +00003576RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003577 SourceLocation StartLoc, SourceLocation IdLoc,
3578 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003579 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3580 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor6bd99292013-02-09 01:35:03 +00003581 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3582
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003583 C.getTypeDeclType(R, PrevDecl);
3584 return R;
Ted Kremenek63597922008-09-02 21:12:32 +00003585}
3586
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003587RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003588 RecordDecl *R =
3589 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3590 SourceLocation(), nullptr, nullptr);
Douglas Gregor6bd99292013-02-09 01:35:03 +00003591 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3592 return R;
Argyrios Kyrtzidisb8b03e62010-07-02 11:54:55 +00003593}
3594
Douglas Gregorc9b5b402009-03-25 15:59:44 +00003595bool RecordDecl::isInjectedClassName() const {
Mike Stump1eb44332009-09-09 15:08:12 +00003596 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregorc9b5b402009-03-25 15:59:44 +00003597 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3598}
3599
Stephen Hines176edba2014-12-01 14:53:08 -08003600bool RecordDecl::isLambda() const {
3601 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3602 return RD->isLambda();
3603 return false;
3604}
3605
3606bool RecordDecl::isCapturedRecord() const {
3607 return hasAttr<CapturedRecordAttr>();
3608}
3609
3610void RecordDecl::setCapturedRecord() {
3611 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3612}
3613
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003614RecordDecl::field_iterator RecordDecl::field_begin() const {
3615 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3616 LoadFieldsFromExternalStorage();
3617
3618 return field_iterator(decl_iterator(FirstDecl));
3619}
3620
Douglas Gregorda2142f2011-02-19 18:51:44 +00003621/// completeDefinition - Notes that the definition of this type is now
3622/// complete.
3623void RecordDecl::completeDefinition() {
John McCall5e1cdac2011-10-07 06:10:15 +00003624 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorda2142f2011-02-19 18:51:44 +00003625 TagDecl::completeDefinition();
3626}
3627
Eli Friedman5f608ae2012-10-12 23:29:20 +00003628/// isMsStruct - Get whether or not this record uses ms_struct layout.
3629/// This which can be turned on with an attribute, pragma, or the
3630/// -mms-bitfields command-line option.
3631bool RecordDecl::isMsStruct(const ASTContext &C) const {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003632 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman5f608ae2012-10-12 23:29:20 +00003633}
3634
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00003635static bool isFieldOrIndirectField(Decl::Kind K) {
3636 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3637}
3638
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003639void RecordDecl::LoadFieldsFromExternalStorage() const {
3640 ExternalASTSource *Source = getASTContext().getExternalSource();
3641 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3642
3643 // Notify that we have a RecordDecl doing some initialization.
3644 ExternalASTSource::Deserializing TheFields(Source);
3645
Chris Lattner5f9e2722011-07-23 10:55:15 +00003646 SmallVector<Decl*, 64> Decls;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003647 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00003648 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3649 Decls)) {
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003650 case ELR_Success:
3651 break;
3652
3653 case ELR_AlreadyLoaded:
3654 case ELR_Failure:
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003655 return;
Douglas Gregorba6ffaf2011-07-15 21:46:17 +00003656 }
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003657
3658#ifndef NDEBUG
3659 // Check that all decls we got were FieldDecls.
3660 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidis22cd9ac2012-09-10 22:04:22 +00003661 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003662#endif
3663
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003664 if (Decls.empty())
3665 return;
3666
Stephen Hines651f13c2014-04-23 16:59:28 -07003667 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidisec2ec1f2011-10-07 21:55:43 +00003668 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidiseb5e9982010-10-14 20:14:34 +00003669}
3670
Stephen Hines176edba2014-12-01 14:53:08 -08003671bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3672 ASTContext &Context = getASTContext();
3673 if (!Context.getLangOpts().Sanitize.has(SanitizerKind::Address) ||
3674 !Context.getLangOpts().SanitizeAddressFieldPadding)
3675 return false;
3676 const auto &Blacklist = Context.getSanitizerBlacklist();
3677 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
3678 // We may be able to relax some of these requirements.
3679 int ReasonToReject = -1;
3680 if (!CXXRD || CXXRD->isExternCContext())
3681 ReasonToReject = 0; // is not C++.
3682 else if (CXXRD->hasAttr<PackedAttr>())
3683 ReasonToReject = 1; // is packed.
3684 else if (CXXRD->isUnion())
3685 ReasonToReject = 2; // is a union.
3686 else if (CXXRD->isTriviallyCopyable())
3687 ReasonToReject = 3; // is trivially copyable.
3688 else if (CXXRD->hasTrivialDestructor())
3689 ReasonToReject = 4; // has trivial destructor.
3690 else if (CXXRD->isStandardLayout())
3691 ReasonToReject = 5; // is standard layout.
3692 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
3693 ReasonToReject = 6; // is in a blacklisted file.
3694 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3695 "field-padding"))
3696 ReasonToReject = 7; // is blacklisted.
3697
3698 if (EmitRemark) {
3699 if (ReasonToReject >= 0)
3700 Context.getDiagnostics().Report(
3701 getLocation(),
3702 diag::remark_sanitize_address_insert_extra_padding_rejected)
3703 << getQualifiedNameAsString() << ReasonToReject;
3704 else
3705 Context.getDiagnostics().Report(
3706 getLocation(),
3707 diag::remark_sanitize_address_insert_extra_padding_accepted)
3708 << getQualifiedNameAsString();
3709 }
3710 return ReasonToReject < 0;
3711}
3712
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003713const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3714 for (const auto *I : fields()) {
3715 if (I->getIdentifier())
3716 return I;
3717
3718 if (const RecordType *RT = I->getType()->getAs<RecordType>())
3719 if (const FieldDecl *NamedDataMember =
3720 RT->getDecl()->findFirstNamedDataMember())
3721 return NamedDataMember;
3722 }
3723
3724 // We didn't find a named data member.
3725 return nullptr;
3726}
3727
3728
Steve Naroff56ee6892008-10-08 17:01:13 +00003729//===----------------------------------------------------------------------===//
3730// BlockDecl Implementation
3731//===----------------------------------------------------------------------===//
3732
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003733void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003734 assert(!ParamInfo && "Already has param info!");
Mike Stump1eb44332009-09-09 15:08:12 +00003735
Steve Naroffe78b8092009-03-13 16:56:44 +00003736 // Zero params -> null pointer.
David Blaikie4278c652011-09-21 18:16:56 +00003737 if (!NewParamInfo.empty()) {
3738 NumParams = NewParamInfo.size();
3739 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3740 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffe78b8092009-03-13 16:56:44 +00003741 }
3742}
3743
John McCall6b5a61b2011-02-07 10:33:21 +00003744void BlockDecl::setCaptures(ASTContext &Context,
3745 const Capture *begin,
3746 const Capture *end,
3747 bool capturesCXXThis) {
John McCall469a1eb2011-02-02 13:00:07 +00003748 CapturesCXXThis = capturesCXXThis;
3749
3750 if (begin == end) {
John McCall6b5a61b2011-02-07 10:33:21 +00003751 NumCaptures = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003752 Captures = nullptr;
John McCall469a1eb2011-02-02 13:00:07 +00003753 return;
3754 }
3755
John McCall6b5a61b2011-02-07 10:33:21 +00003756 NumCaptures = end - begin;
3757
3758 // Avoid new Capture[] because we don't want to provide a default
3759 // constructor.
3760 size_t allocationSize = NumCaptures * sizeof(Capture);
3761 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3762 memcpy(buffer, begin, allocationSize);
3763 Captures = static_cast<Capture*>(buffer);
Steve Naroffe78b8092009-03-13 16:56:44 +00003764}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003765
John McCall204e1332011-06-15 22:51:16 +00003766bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07003767 for (const auto &I : captures())
John McCall204e1332011-06-15 22:51:16 +00003768 // Only auto vars can be captured, so no redeclaration worries.
Stephen Hines651f13c2014-04-23 16:59:28 -07003769 if (I.getVariable() == variable)
John McCall204e1332011-06-15 22:51:16 +00003770 return true;
3771
3772 return false;
3773}
3774
Douglas Gregor2fcbcef2010-12-21 16:27:07 +00003775SourceRange BlockDecl::getSourceRange() const {
3776 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3777}
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003778
3779//===----------------------------------------------------------------------===//
3780// Other Decl Allocation/Deallocation Method Implementations
3781//===----------------------------------------------------------------------===//
3782
David Blaikie99ba9e32011-12-20 02:48:34 +00003783void TranslationUnitDecl::anchor() { }
3784
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003785TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003786 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003787}
3788
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003789void ExternCContextDecl::anchor() { }
3790
3791ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
3792 TranslationUnitDecl *DC) {
3793 return new (C, DC) ExternCContextDecl(DC);
3794}
3795
David Blaikie99ba9e32011-12-20 02:48:34 +00003796void LabelDecl::anchor() { }
3797
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003798LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara67843042011-03-05 18:21:20 +00003799 SourceLocation IdentL, IdentifierInfo *II) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003800 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara67843042011-03-05 18:21:20 +00003801}
3802
3803LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3804 SourceLocation IdentL, IdentifierInfo *II,
3805 SourceLocation GnuLabelL) {
3806 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003807 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerad8dcf42011-02-17 07:39:24 +00003808}
3809
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003810LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003811 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3812 SourceLocation());
Douglas Gregor06c91932010-10-27 19:49:05 +00003813}
3814
Stephen Hines176edba2014-12-01 14:53:08 -08003815void LabelDecl::setMSAsmLabel(StringRef Name) {
3816 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3817 memcpy(Buffer, Name.data(), Name.size());
3818 Buffer[Name.size()] = '\0';
3819 MSAsmName = Buffer;
3820}
3821
David Blaikie99ba9e32011-12-20 02:48:34 +00003822void ValueDecl::anchor() { }
3823
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +00003824bool ValueDecl::isWeak() const {
Stephen Hines651f13c2014-04-23 16:59:28 -07003825 for (const auto *I : attrs())
3826 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +00003827 return true;
3828
3829 return isWeakImported();
3830}
3831
David Blaikie99ba9e32011-12-20 02:48:34 +00003832void ImplicitParamDecl::anchor() { }
3833
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003834ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003835 SourceLocation IdLoc,
3836 IdentifierInfo *Id,
3837 QualType Type) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003838 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003839}
3840
Stephen Hines651f13c2014-04-23 16:59:28 -07003841ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003842 unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003843 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
3844 QualType());
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003845}
3846
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003847FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003848 SourceLocation StartLoc,
Abramo Bagnara25777432010-08-11 22:01:17 +00003849 const DeclarationNameInfo &NameInfo,
3850 QualType T, TypeSourceInfo *TInfo,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003851 StorageClass SC,
Stephen Hines651f13c2014-04-23 16:59:28 -07003852 bool isInlineSpecified,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00003853 bool hasWrittenPrototype,
3854 bool isConstexprSpecified) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003855 FunctionDecl *New =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003856 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3857 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003858 New->HasWrittenPrototype = hasWrittenPrototype;
3859 return New;
3860}
3861
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003862FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003863 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
3864 DeclarationNameInfo(), QualType(), nullptr,
Stephen Hines651f13c2014-04-23 16:59:28 -07003865 SC_None, false, false);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003866}
3867
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003868BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003869 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003870}
3871
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003872BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003873 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall76da55d2013-04-16 07:28:30 +00003874}
3875
Ben Langmuir8c045ac2013-05-03 19:00:33 +00003876CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3877 unsigned NumParams) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003878 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3879 CapturedDecl(DC, NumParams);
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00003880}
3881
Ben Langmuirdc5be4f2013-05-03 19:20:19 +00003882CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Stephen Hines651f13c2014-04-23 16:59:28 -07003883 unsigned NumParams) {
3884 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003885 CapturedDecl(nullptr, NumParams);
Ben Langmuirdc5be4f2013-05-03 19:20:19 +00003886}
3887
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003888EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3889 SourceLocation L,
3890 IdentifierInfo *Id, QualType T,
3891 Expr *E, const llvm::APSInt &V) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003892 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003893}
3894
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003895EnumConstantDecl *
3896EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003897 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
3898 QualType(), nullptr, llvm::APSInt());
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003899}
3900
David Blaikie99ba9e32011-12-20 02:48:34 +00003901void IndirectFieldDecl::anchor() { }
3902
Benjamin Kramerd9811462010-11-21 14:11:41 +00003903IndirectFieldDecl *
3904IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3905 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3906 unsigned CHS) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003907 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet87c2e122010-11-21 06:08:52 +00003908}
3909
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003910IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3911 unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003912 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
3913 DeclarationName(), QualType(), nullptr,
3914 0);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003915}
3916
Douglas Gregor8e7139c2010-09-01 20:41:53 +00003917SourceRange EnumConstantDecl::getSourceRange() const {
3918 SourceLocation End = getLocation();
3919 if (Init)
3920 End = Init->getLocEnd();
3921 return SourceRange(getLocation(), End);
3922}
3923
David Blaikie99ba9e32011-12-20 02:48:34 +00003924void TypeDecl::anchor() { }
3925
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003926TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003927 SourceLocation StartLoc, SourceLocation IdLoc,
3928 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003929 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003930}
3931
David Blaikie99ba9e32011-12-20 02:48:34 +00003932void TypedefNameDecl::anchor() { }
3933
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -07003934TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName() const {
3935 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>())
3936 if (TT->getDecl()->getTypedefNameForAnonDecl() == this)
3937 return TT->getDecl();
3938
3939 return nullptr;
3940}
3941
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003942TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003943 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
3944 nullptr, nullptr);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003945}
3946
Richard Smith162e1c12011-04-15 14:24:37 +00003947TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3948 SourceLocation StartLoc,
3949 SourceLocation IdLoc, IdentifierInfo *Id,
3950 TypeSourceInfo *TInfo) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003951 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00003952}
3953
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003954TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003955 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
3956 SourceLocation(), nullptr, nullptr);
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003957}
3958
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00003959SourceRange TypedefDecl::getSourceRange() const {
3960 SourceLocation RangeEnd = getLocation();
3961 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3962 if (typeIsPostfix(TInfo->getType()))
3963 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3964 }
3965 return SourceRange(getLocStart(), RangeEnd);
3966}
3967
Richard Smith162e1c12011-04-15 14:24:37 +00003968SourceRange TypeAliasDecl::getSourceRange() const {
3969 SourceLocation RangeEnd = getLocStart();
3970 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3971 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3972 return SourceRange(getLocStart(), RangeEnd);
3973}
3974
David Blaikie99ba9e32011-12-20 02:48:34 +00003975void FileScopeAsmDecl::anchor() { }
3976
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003977FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara21e006e2011-03-03 14:20:18 +00003978 StringLiteral *Str,
3979 SourceLocation AsmLoc,
3980 SourceLocation RParenLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003981 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl7783bfc2010-01-26 22:01:41 +00003982}
Douglas Gregor15de72c2011-12-02 23:23:56 +00003983
Stephen Hines651f13c2014-04-23 16:59:28 -07003984FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003985 unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003986 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
3987 SourceLocation());
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00003988}
3989
Michael Han684aa732013-02-22 17:15:32 +00003990void EmptyDecl::anchor() {}
3991
3992EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003993 return new (C, DC) EmptyDecl(DC, L);
Michael Han684aa732013-02-22 17:15:32 +00003994}
3995
3996EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003997 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han684aa732013-02-22 17:15:32 +00003998}
3999
Douglas Gregor15de72c2011-12-02 23:23:56 +00004000//===----------------------------------------------------------------------===//
4001// ImportDecl Implementation
4002//===----------------------------------------------------------------------===//
4003
4004/// \brief Retrieve the number of module identifiers needed to name the given
4005/// module.
4006static unsigned getNumModuleIdentifiers(Module *Mod) {
4007 unsigned Result = 1;
4008 while (Mod->Parent) {
4009 Mod = Mod->Parent;
4010 ++Result;
4011 }
4012 return Result;
4013}
4014
Douglas Gregor5948ae12012-01-03 18:04:46 +00004015ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00004016 Module *Imported,
4017 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor5948ae12012-01-03 18:04:46 +00004018 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregore6649772011-12-03 00:30:27 +00004019 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00004020{
4021 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4022 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
4023 memcpy(StoredLocs, IdentifierLocs.data(),
4024 IdentifierLocs.size() * sizeof(SourceLocation));
4025}
4026
Douglas Gregor5948ae12012-01-03 18:04:46 +00004027ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregor15de72c2011-12-02 23:23:56 +00004028 Module *Imported, SourceLocation EndLoc)
Douglas Gregor5948ae12012-01-03 18:04:46 +00004029 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregore6649772011-12-03 00:30:27 +00004030 NextLocalImport()
Douglas Gregor15de72c2011-12-02 23:23:56 +00004031{
4032 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
4033}
4034
Stephen Hines651f13c2014-04-23 16:59:28 -07004035ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00004036 SourceLocation StartLoc, Module *Imported,
Douglas Gregor15de72c2011-12-02 23:23:56 +00004037 ArrayRef<SourceLocation> IdentifierLocs) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004038 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
4039 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregor15de72c2011-12-02 23:23:56 +00004040}
4041
Stephen Hines651f13c2014-04-23 16:59:28 -07004042ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor5948ae12012-01-03 18:04:46 +00004043 SourceLocation StartLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -07004044 Module *Imported,
Douglas Gregor15de72c2011-12-02 23:23:56 +00004045 SourceLocation EndLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004046 ImportDecl *Import =
4047 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
4048 Imported, EndLoc);
Douglas Gregor15de72c2011-12-02 23:23:56 +00004049 Import->setImplicit();
4050 return Import;
4051}
4052
Douglas Gregor1e68ecc2012-01-05 21:55:30 +00004053ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4054 unsigned NumLocations) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004055 return new (C, ID, NumLocations * sizeof(SourceLocation))
4056 ImportDecl(EmptyShell());
Douglas Gregor15de72c2011-12-02 23:23:56 +00004057}
4058
4059ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4060 if (!ImportedAndComplete.getInt())
Dmitri Gribenko55431692013-05-05 00:41:58 +00004061 return None;
Douglas Gregor15de72c2011-12-02 23:23:56 +00004062
4063 const SourceLocation *StoredLocs
4064 = reinterpret_cast<const SourceLocation *>(this + 1);
Stephen Hines176edba2014-12-01 14:53:08 -08004065 return llvm::makeArrayRef(StoredLocs,
4066 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregor15de72c2011-12-02 23:23:56 +00004067}
4068
4069SourceRange ImportDecl::getSourceRange() const {
4070 if (!ImportedAndComplete.getInt())
4071 return SourceRange(getLocation(),
4072 *reinterpret_cast<const SourceLocation *>(this + 1));
4073
4074 return SourceRange(getLocation(), getIdentifierLocs().back());
4075}