blob: 550810367d96f19f6d02ee08a3cd1aa83a369578 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Faisal Valib90b2112014-04-03 16:32:21 +000016#include "clang/AST/ASTLambda.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000022#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000024#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "clang/AST/Stmt.h"
26#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000028#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000029#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000030#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000031#include "clang/Basic/TargetInfo.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000032#include "clang/Frontend/FrontendDiagnostic.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000033#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000034#include <algorithm>
35
Chris Lattner6d9a6852006-10-25 05:11:20 +000036using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000037
Richard Smith0b87e072013-10-07 08:02:11 +000038Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
40}
41
Richard Smith73b21d82014-09-03 02:33:22 +000042// Defined here so that it can be inlined into its direct callers.
43bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
45}
46
Chris Lattner88f70d62008-03-15 05:43:15 +000047//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000048// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000049//===----------------------------------------------------------------------===//
50
John McCalldf25c432013-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 McCalld041a9b2013-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 McCalldf25c432013-02-16 00:17:33 +000096
John McCall5f46c482013-02-21 23:42:58 +000097const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +000098const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +000099
John McCalldf25c432013-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 McCall5f46c482013-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 McCalld041a9b2013-02-20 01:54:26 +0000107 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000108
John McCall5f46c482013-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 McCalld041a9b2013-02-20 01:54:26 +0000112 LVForValue = NamedDecl::VisibilityForValue,
113
John McCall5f46c482013-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 McCalld041a9b2013-02-20 01:54:26 +0000118
John McCall5f46c482013-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 Espindola9551d3b2013-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 McCalldf25c432013-02-16 00:17:33 +0000127};
128
John McCalld041a9b2013-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 McCall5f46c482013-02-21 23:42:58 +0000132 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-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 McCall5f46c482013-02-21 23:42:58 +0000140 static_cast<LVComputationKind>(unsigned(oldKind) |
141 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-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 Blaikie05785d12013-02-20 22:23:23 +0000149static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
150 LVComputationKind kind) {
John McCalld041a9b2013-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 McCalldf25c432013-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 McCallb4a99d32013-02-19 01:57:35 +0000159 return isa<TypeDecl>(D) ||
160 isa<ClassTemplateDecl>(D) ||
161 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000162}
163
John McCall5f46c482013-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
Benjamin Kramered2f4762014-03-07 14:30:23 +0000167std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-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 McCalld041a9b2013-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 McCalldf25c432013-02-16 00:17:33 +0000198/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000199static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-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 Gregor1baf38f2011-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 McCalld041a9b2013-02-20 01:54:26 +0000211 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000212 }
Douglas Gregor1baf38f2011-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 Gregore8bbc122011-09-02 00:18:52 +0000216 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000217 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
218 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000219 return DefaultVisibility;
220 }
221
David Blaikie7a30dc52013-02-21 01:47:18 +0000222 return None;
John McCall457a04e2010-10-22 21:05:15 +0000223}
224
Rafael Espindolaecf63c62013-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 Gregor7dc5c172010-02-03 09:33:45 +0000232/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000233/// template parameter list. For visibility purposes, template
234/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000235static LinkageInfo
David Majnemerc7b85c42014-04-23 05:16:48 +0000236getLVForTemplateParameterList(const TemplateParameterList *Params,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000237 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000238 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000239 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000240 // Template type parameters are the most common and never
241 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000242 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-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.
David Majnemerc7b85c42014-04-23 05:16:48 +0000249 if (const NonTypeTemplateParmDecl *NTTP =
250 dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000251 // Handle the non-pack case first.
252 if (!NTTP->isExpandedParameterPack()) {
253 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000254 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000255 }
256 continue;
257 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000258
John McCalldf25c432013-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 Espindola6fbfafe2013-02-27 02:27:19 +0000263 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000264 }
John McCalldf25c432013-02-16 00:17:33 +0000265 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000266 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000267
John McCalldf25c432013-02-16 00:17:33 +0000268 // Template template parameters can be restricted by their
269 // template parameters, recursively.
David Majnemerc7b85c42014-04-23 05:16:48 +0000270 const TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000271
272 // Handle the non-pack case first.
273 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000274 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
275 computation));
John McCalldf25c432013-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 Espindolaecf63c62013-05-29 04:55:30 +0000283 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000284 }
285 }
286
John McCall457a04e2010-10-22 21:05:15 +0000287 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000288}
289
Rafael Espindola19de5612013-01-12 06:42:30 +0000290/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000291static LinkageInfo getLVForDecl(const NamedDecl *D,
292 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000293
Eli Friedman7e346a82013-07-01 20:22:57 +0000294static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000295 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000296 const DeclContext *DC = D->getDeclContext();
297 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000298 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
299 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000300 DC = DC->getParent();
301 }
302 return Ret;
303}
304
Douglas Gregor7dc5c172010-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 McCalldf25c432013-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.
David Majnemerc7b85c42014-04-23 05:16:48 +0000310static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
311 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000312 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000313
David Majnemerc7b85c42014-04-23 05:16:48 +0000314 for (const TemplateArgument &Arg : Args) {
315 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000316 case TemplateArgument::Null:
317 case TemplateArgument::Integral:
318 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000319 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000320
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000322 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000323 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000324
325 case TemplateArgument::Declaration:
David Majnemerc7b85c42014-04-23 05:16:48 +0000326 if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000327 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000328 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000329 }
330 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000331
332 case TemplateArgument::NullPtr:
David Majnemerc7b85c42014-04-23 05:16:48 +0000333 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000334 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000335
336 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000337 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000338 if (TemplateDecl *Template =
339 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000340 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000341 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000342
343 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000344 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000345 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000346 }
John McCalldf25c432013-02-16 00:17:33 +0000347 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000348 }
349
John McCall457a04e2010-10-22 21:05:15 +0000350 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351}
352
Rafael Espindola2f869a32012-01-14 00:30:36 +0000353static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000354getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
355 LVComputationKind computation) {
356 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000357}
358
John McCall5f46c482013-02-21 23:42:58 +0000359static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
360 const FunctionTemplateSpecializationInfo *specInfo) {
361 // Include visibility from the template parameters and arguments
362 // only if this is not an explicit instantiation or specialization
363 // with direct explicit visibility. (Implicit instantiations won't
364 // have a direct attribute.)
365 if (!specInfo->isExplicitInstantiationOrSpecialization())
366 return true;
367
368 return !fn->hasAttr<VisibilityAttr>();
369}
370
John McCalldf25c432013-02-16 00:17:33 +0000371/// Merge in template-related linkage and visibility for the given
372/// function template specialization.
373///
374/// We don't need a computation kind here because we can assume
375/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000376///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000377/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000378static void
379mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000380 const FunctionTemplateSpecializationInfo *specInfo,
381 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000382 bool considerVisibility =
383 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000384
385 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000386 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000387 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000388 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000389 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
390
391 // Merge information from the template arguments.
392 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000393 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000394 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000395}
396
John McCall5f46c482013-02-21 23:42:58 +0000397/// Does the given declaration have a direct visibility attribute
398/// that would match the given rules?
399static bool hasDirectVisibilityAttribute(const NamedDecl *D,
400 LVComputationKind computation) {
401 switch (computation) {
402 case LVForType:
403 case LVForExplicitType:
404 if (D->hasAttr<TypeVisibilityAttr>())
405 return true;
406 // fallthrough
407 case LVForValue:
408 case LVForExplicitValue:
409 if (D->hasAttr<VisibilityAttr>())
410 return true;
411 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000412 case LVForLinkageOnly:
413 return false;
John McCall5f46c482013-02-21 23:42:58 +0000414 }
415 llvm_unreachable("bad visibility computation kind");
416}
417
John McCalld041a9b2013-02-20 01:54:26 +0000418/// Should we consider visibility associated with the template
419/// arguments and parameters of the given class template specialization?
420static bool shouldConsiderTemplateVisibility(
421 const ClassTemplateSpecializationDecl *spec,
422 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000423 // Include visibility from the template parameters and arguments
424 // only if this is not an explicit instantiation or specialization
425 // with direct explicit visibility (and note that implicit
426 // instantiations won't have a direct attribute).
427 //
428 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000429 // for an explicit specialization when computing the visibility of a
430 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000431 //
432 // This is a bit complex; let's unpack it.
433 //
434 // An explicit class specialization is an independent, top-level
435 // declaration. As such, if it or any of its members has an
436 // explicit visibility attribute, that must directly express the
437 // user's intent, and we should honor it. The same logic applies to
438 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000439
440 // Fast path: if this is not an explicit instantiation or
441 // specialization, we always want to consider template-related
442 // visibility restrictions.
443 if (!spec->isExplicitInstantiationOrSpecialization())
444 return true;
445
446 // This is the 'member thereof' check.
447 if (spec->isExplicitSpecialization() &&
448 hasExplicitVisibilityAlready(computation))
449 return false;
450
John McCall5f46c482013-02-21 23:42:58 +0000451 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000452}
453
454/// Merge in template-related linkage and visibility for the given
455/// class template specialization.
456static void mergeTemplateLV(LinkageInfo &LV,
457 const ClassTemplateSpecializationDecl *spec,
458 LVComputationKind computation) {
459 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000460
461 // Merge information from the template parameters, but ignore
462 // visibility if we're only considering template arguments.
463
John McCalld041a9b2013-02-20 01:54:26 +0000464 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000465 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000466 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000467 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000468 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000469
470 // Merge information from the template arguments. We ignore
471 // template-argument visibility if we've got an explicit
472 // instantiation with a visibility attribute.
473 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000474 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000475 if (considerVisibility)
476 LV.mergeVisibility(argsLV);
477 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000478}
479
Larisse Voufo5899e192014-07-02 23:08:34 +0000480/// 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 Espindolac7c7ad52012-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 Espindola5cc78902012-07-13 23:26:43 +0000534 const LangOptions &Opts = D->getASTContext().getLangOpts();
535 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-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
Craig Topper36250ad2014-05-12 05:36:57 +0000551 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-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 Espindolafb9d4b42012-10-11 16:32:25 +0000557 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000558}
559
Rafael Espindola593537a2013-05-05 20:15:21 +0000560template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000561 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000562 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000563}
564
Richard Smith03c05032014-02-17 23:34:47 +0000565static bool isSingleLineLanguageLinkage(const Decl &D) {
Rafael Espindola327be3c2013-04-26 01:30:23 +0000566 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000567 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000568 return true;
569 return false;
570}
571
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000572static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000573 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000574 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-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 McCall8e7d6562010-08-26 03:08:43 +0000586 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000587 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000588
Richard Smithdc0ef452012-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000592 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000593 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000594 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000595 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000596 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000597 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000598
599 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000600 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000601 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-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 Jahanian8feee2d2011-06-16 20:14:50 +0000613 }
Alp Tokera2794f92014-01-22 07:29:52 +0000614 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-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 Gregorf73b2822009-11-25 22:24:25 +0000618
619 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000620 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000621 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
David Majnemer18fac3b2014-12-10 22:58:14 +0000622 } 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 Gregorf73b2822009-11-25 22:24:25 +0000627 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000628 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000629
Chandler Carruth9682a2fd2011-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 Espindola593537a2013-05-05 20:15:21 +0000633 if ((!Var || !isFirstInExternCContext(Var)) &&
634 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000635 return LinkageInfo::uniqueExternal();
636 }
John McCallb7139c42010-10-28 04:18:25 +0000637
John McCall457a04e2010-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 McCallc273f242010-10-30 11:50:40 +0000644 LinkageInfo LV;
645
John McCalld041a9b2013-02-20 01:54:26 +0000646 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000647 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000648 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000649 } else {
650 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000651 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-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 Blaikie05785d12013-02-20 22:23:23 +0000657 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000658 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000659 break;
660 }
661 }
662 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000663
John McCalldf25c432013-02-16 00:17:33 +0000664 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000665 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000666 // Use global type/value visibility as appropriate.
667 Visibility globalVisibility;
668 if (computation == LVForValue) {
Larisse Voufo404e1422015-02-04 02:34:32 +0000669 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000670 } else {
671 assert(computation == LVForType);
672 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
673 }
674 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-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 Espindolac7c7ad52012-07-13 14:25:36 +0000681 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000682
Douglas Gregorf73b2822009-11-25 22:24:25 +0000683 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000684
Douglas Gregorf73b2822009-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 McCall37bb6c92010-10-29 22:22:43 +0000690 // GCC applies the following optimization to variables and static
691 // data members, but not to functions:
692 //
John McCall457a04e2010-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 McCall5fe84122010-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 McCall457a04e2010-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 Espindola593537a2013-05-05 20:15:21 +0000711 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000712 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000713 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000714 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000715 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000716 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000717 }
718
John McCall23032652010-11-02 18:38:13 +0000719 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000720 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000721
Rafael Espindolad5ed0332012-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 Gregorf73b2822009-11-25 22:24:25 +0000725
Larisse Voufo5899e192014-07-02 23:08:34 +0000726 // 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 Gregorf73b2822009-11-25 22:24:25 +0000734 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000735 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-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 McCall457a04e2010-10-22 21:05:15 +0000740
John McCall23032652010-11-02 18:38:13 +0000741 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000742 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000743
Rafael Espindolaa508c5d2012-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 Gregorf73b2822009-11-25 22:24:25 +0000747
John McCallf768aa72011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000752 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-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 Valid2598e92013-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 Smith50f4afc2013-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 McCallf768aa72011-02-10 06:50:24 +0000767
John McCall5f46c482013-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 McCallb8c604a2011-06-27 23:06:04 +0000771 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000772 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000773 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000774 }
775
Douglas Gregorf73b2822009-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 McCall457a04e2010-10-22 21:05:15 +0000782 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
783 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000784 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000785 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000786
John McCall457a04e2010-10-22 21:05:15 +0000787 // If this is a class template specialization, consider the
John McCall5f46c482013-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 McCallb8c604a2011-06-27 23:06:04 +0000790 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000791 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000792 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000793 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000794
795 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000796 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000797 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000798 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000799 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000800 return LinkageInfo::none();
801 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000802
803 // - a template, unless it is a function template that has
804 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000805 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000806 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000807 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000808 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000809 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
810
Douglas Gregorf73b2822009-11-25 22:24:25 +0000811 // - a namespace (7.3), unless it is declared within an unnamed
812 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000813 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
814 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000815
John McCall457a04e2010-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 {
Richard Smith2516ba22014-08-11 18:35:44 +0000823 // FIXME: A typedef declaration has linkage if it gives a type a name for
824 // linkage purposes.
John McCallc273f242010-10-30 11:50:40 +0000825 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000826 }
827
828 // If we ended up with non-external linkage, visibility should
829 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000830 if (LV.getLinkage() != ExternalLinkage)
831 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000832
John McCall457a04e2010-10-22 21:05:15 +0000833 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000834}
835
John McCalldf25c432013-02-16 00:17:33 +0000836static LinkageInfo getLVForClassMember(const NamedDecl *D,
837 LVComputationKind computation) {
John McCall457a04e2010-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.
Richard Smith26d11be2014-01-08 01:51:59 +0000842 //
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 McCall8823c652010-08-13 08:35:10 +0000848 if (!(isa<CXXMethodDecl>(D) ||
849 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000850 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000851 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000852 isa<TagDecl>(D) ||
853 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000854 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000855
John McCall07072662010-11-02 01:45:15 +0000856 LinkageInfo LV;
857
John McCall07072662010-11-02 01:45:15 +0000858 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000859 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000860 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000861 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-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 Espindola4a5da442013-02-27 02:56:45 +0000867 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000868 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000869 }
Rafael Espindola53cf2192012-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 Ledru830885c2012-07-23 08:59:39 +0000873 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000874 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000875 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000876 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000877
John McCall5f46c482013-02-21 23:42:58 +0000878 LinkageInfo classLV =
879 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000880 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000881 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000882 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000883
Rafael Espindolae6190db2013-05-28 02:22:10 +0000884 if (!isExternallyVisible(classLV.getLinkage()))
885 return LinkageInfo::none();
886
887
John McCall5f46c482013-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.
Craig Topper36250ad2014-05-12 05:36:57 +0000892 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000893
John McCall8823c652010-08-13 08:35:10 +0000894 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-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.
Nico Weber38267342015-04-22 03:44:51 +0000897 // But only look at the type-as-written. If this function has an
898 // auto-deduced return type, we can't compute the linkage of that type
899 // because it could require looking at the linkage of this function, and we
900 // don't need this for correctness because the type is not part of the
901 // function's signature.
902 // FIXME: This is a hack. We should be able to solve this circularity and
903 // the one in getLVForNamespaceScopeDecl for Functions some other way.
Faisal Valid2598e92013-10-08 04:15:04 +0000904 {
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 McCall457a04e2010-10-22 21:05:15 +0000911 // If this is a method template specialization, use the linkage for
912 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000913 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000914 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000915 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-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 McCalle6e622e2010-11-01 01:29:57 +0000923 }
John McCall457a04e2010-10-22 21:05:15 +0000924
John McCall37bb6c92010-10-29 22:22:43 +0000925 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000926 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000927 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000928 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-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 McCall37bb6c92010-10-29 22:22:43 +0000939 }
940
John McCall37bb6c92010-10-29 22:22:43 +0000941 // Static data members.
942 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000943 if (const VarTemplateSpecializationDecl *spec
944 = dyn_cast<VarTemplateSpecializationDecl>(VD))
945 mergeTemplateLV(LV, spec, computation);
946
John McCall36cd5cc2010-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 Espindolaecf63c62013-05-29 04:55:30 +0000949 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000950 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
951 LV.mergeVisibility(typeLV);
952 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000953
954 if (isExplicitMemberSpecialization(VD)) {
955 explicitSpecSuppressor = VD;
956 }
John McCalldf25c432013-02-16 00:17:33 +0000957
958 // Template members.
959 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
960 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000961 (!LV.isVisibilityExplicit() &&
962 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000963 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000964 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000965 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000966 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-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 McCall37bb6c92010-10-29 22:22:43 +0000974 }
975
John McCall5f46c482013-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 Espindola4a5da442013-02-27 02:56:45 +0000983 // optimization: hasDVA() is true only with explicit visibility.
984 LV.isVisibilityExplicit() &&
985 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-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 McCall457a04e2010-10-22 21:05:15 +0000992 return LV;
John McCall8823c652010-08-13 08:35:10 +0000993}
994
David Blaikie68e081d2011-12-20 02:48:34 +0000995void NamedDecl::anchor() { }
996
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000997static LinkageInfo computeLVForDecl(const NamedDecl *D,
998 LVComputationKind computation);
999
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001000bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001001 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001002 return true;
John McCalld396b972011-02-08 19:01:05 +00001003
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001004 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +00001005 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001006}
1007
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001008ObjCStringFormatFamily 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 Espindola3ae00052013-05-13 00:12:11 +00001021Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001022 // We don't care about visibility here, so ask for the cheapest
1023 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001024 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001025}
1026
John McCallc273f242010-10-30 11:50:40 +00001027LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +00001028 LVComputationKind computation =
1029 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001030 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +00001031}
Ted Kremenek926d8602010-04-20 23:15:35 +00001032
Rafael Espindola9ad61122013-11-26 16:09:08 +00001033static Optional<Visibility>
1034getExplicitVisibilityAux(const NamedDecl *ND,
1035 NamedDecl::ExplicitVisibilityKind kind,
1036 bool IsMostRecent) {
1037 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1038
Rafael Espindola3a52c442013-02-26 19:33:14 +00001039 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001040 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001041 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001042
Rafael Espindola3a52c442013-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.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001045 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-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
Rafael Espindola9ad61122013-11-26 16:09:08 +00001055 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001056 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1057 kind);
1058
1059 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001060 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001061 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1062 if (MostRecent != ND)
1063 return getExplicitVisibilityAux(MostRecent, kind, true);
1064 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001065
Rafael Espindola9ad61122013-11-26 16:09:08 +00001066 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001067 if (Var->isStaticDataMember()) {
1068 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1069 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001070 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001071 }
1072
David Majnemer35b02bc2014-04-29 07:32:26 +00001073 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1074 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1075 kind);
1076
David Blaikie7a30dc52013-02-21 01:47:18 +00001077 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001078 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001079 // Also handle function template specializations.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001080 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-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 McCalld041a9b2013-02-20 01:54:26 +00001085 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1086 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001087
Rafael Espindola8093fdf2012-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 McCalld041a9b2013-02-20 01:54:26 +00001092 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001093
David Blaikie7a30dc52013-02-21 01:47:18 +00001094 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001095 }
1096
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001097 // The visibility of a template is stored in the templated decl.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001098 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001099 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001100
David Blaikie7a30dc52013-02-21 01:47:18 +00001101 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001102}
1103
Rafael Espindola9ad61122013-11-26 16:09:08 +00001104Optional<Visibility>
1105NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1106 return getExplicitVisibilityAux(this, kind, false);
1107}
1108
Eli Friedman7e346a82013-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 Vali98b8e182013-09-29 20:27:06 +00001118
Eli Friedman7e346a82013-07-01 20:22:57 +00001119 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1120 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001121
Eli Friedman7e346a82013-07-01 20:22:57 +00001122 return LinkageInfo::external();
1123}
1124
John McCalldf25c432013-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 Espindola593537a2013-05-05 20:15:21 +00001129 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001130 return LinkageInfo::uniqueExternal();
1131
1132 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001133 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001134 return LinkageInfo::internal();
1135
1136 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001137 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001138 if (Optional<Visibility> Vis =
1139 getExplicitVisibility(Function, computation))
John McCalldf25c432013-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 Espindola6ae7e502013-04-03 19:27:57 +00001151 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001152 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001153 return LinkageInfo::uniqueExternal();
1154
John McCalldf25c432013-02-16 00:17:33 +00001155 LinkageInfo LV;
1156 if (Var->getStorageClass() == SC_PrivateExtern)
1157 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001158 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001159 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001160 LV.mergeVisibility(*Vis, true);
1161 }
1162
Rafael Espindola6ae7e502013-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 McCalldf25c432013-02-16 00:17:33 +00001170 return LV;
1171 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001172
1173 if (!Var->isStaticLocal())
1174 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001175 }
1176
Rafael Espindolaa4184182013-06-17 20:04:51 +00001177 ASTContext &Context = D->getASTContext();
1178 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001179 return LinkageInfo::none();
1180
Eli Friedman7e346a82013-07-01 20:22:57 +00001181 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1182 if (!OuterD)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001183 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001184
Eli Friedman7e346a82013-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 Espindola52189362013-06-04 13:43:35 +00001189
Eli Friedman7e346a82013-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() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001195 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001196 return LinkageInfo::none();
1197
1198 LV = getLVForDecl(FD, computation);
1199 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001200 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001201 return LinkageInfo::none();
1202 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1203 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001204}
1205
Faisal Vali49b4c1f2013-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 Espindola9551d3b2013-05-28 19:43:11 +00001219static LinkageInfo computeLVForDecl(const NamedDecl *D,
1220 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001221 // Objective-C: treat all Objective-C declarations as having external
1222 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001223 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001224 default:
1225 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001226 case Decl::ParmVar:
1227 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001228 case Decl::TemplateTemplateParm: // count these as external
1229 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001230 case Decl::ObjCAtDefsField:
1231 case Decl::ObjCCategory:
1232 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001233 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001234 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001235 case Decl::ObjCMethod:
1236 case Decl::ObjCProperty:
1237 case Decl::ObjCPropertyImpl:
1238 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001239 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-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 Gregor6f88e5e2012-02-21 04:17:39 +00001248
Faisal Vali49b4c1f2013-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 Gregor6f88e5e2012-02-21 04:17:39 +00001267 }
1268
1269 break;
1270 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001271 }
1272
Douglas Gregorf73b2822009-11-25 22:24:25 +00001273 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001274 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001275 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-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 McCall033caa52010-10-29 00:29:13 +00001284 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001285 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-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 McCalldf25c432013-02-16 00:17:33 +00001298 if (D->getDeclContext()->isFunctionOrMethod())
1299 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001300
1301 // C++ [basic.link]p6:
1302 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001303 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001304}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001305
Rafael Espindola9551d3b2013-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
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001330 // computed also does.
Craig Topper36250ad2014-05-12 05:36:57 +00001331 NamedDecl *Old = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +00001332 for (auto I : D->redecls()) {
1333 NamedDecl *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001334 if (T == D)
1335 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001336 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-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 Gregor2ada0482009-02-04 17:27:36 +00001354std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001355 std::string QualName;
1356 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001357 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-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 Gregor2ada0482009-02-04 17:27:36 +00001367 const DeclContext *Ctx = getDeclContext();
1368
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001369 if (Ctx->isFunctionOrMethod()) {
1370 printName(OS);
1371 return;
1372 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001373
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001374 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-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 Kramer24ebf7c2013-02-23 13:53:57 +00001381 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001382
1383 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1384 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001385 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001386 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001387 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001388 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001389 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1390 TemplateArgs.data(),
1391 TemplateArgs.size(),
1392 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001393 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001394 if (P.SuppressUnwrittenScope &&
1395 (ND->isAnonymousNamespace() || ND->isInline()))
1396 continue;
Sam Weinig07d211e2009-12-24 23:15:03 +00001397 if (ND->isAnonymousNamespace())
David Blaikieabe1a392014-04-02 05:58:29 +00001398 OS << "(anonymous namespace)";
Sam Weinig07d211e2009-12-24 23:15:03 +00001399 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001400 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001401 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1402 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001403 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001404 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001405 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001406 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001407 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001408 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001409 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001410
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001411 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001412 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001413 unsigned NumParams = FD->getNumParams();
1414 for (unsigned i = 0; i < NumParams; ++i) {
1415 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001416 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001417 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001418 }
1419
1420 if (FT->isVariadic()) {
1421 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001422 OS << ", ";
1423 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001424 }
1425 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001426 OS << ')';
1427 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001428 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001429 }
1430 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001431 }
1432
John McCalla2a3f7d2010-03-16 21:48:18 +00001433 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001434 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001435 else
David Blaikieabe1a392014-04-02 05:58:29 +00001436 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001437}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001438
Benjamin Kramer24ebf7c2013-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 Gregor2ada0482009-02-04 17:27:36 +00001446}
1447
Richard Smithe8292b12015-02-10 03:28:10 +00001448static 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 Gregor8b9ccca2008-12-23 21:05:05 +00001490 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1491
Richard Smithfe620d22015-03-05 23:24:12 +00001492 // Never replace one imported declaration with another; we need both results
1493 // when re-exporting.
1494 if (OldD->isFromASTFile() && isFromASTFile())
1495 return false;
1496
Richard Smithe8292b12015-02-10 03:28:10 +00001497 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 Stump11289f42009-09-09 15:08:12 +00001506
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001507 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1508 // For function declarations, we keep track of redeclarations.
Richard Smithe8292b12015-02-10 03:28:10 +00001509 // 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 Gregor8b9ccca2008-12-23 21:05:05 +00001513
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001514 // For function templates, the underlying function declarations are linked.
Richard Smithe8292b12015-02-10 03:28:10 +00001515 if (const FunctionTemplateDecl *FunctionTemplate =
1516 dyn_cast<FunctionTemplateDecl>(this))
1517 return FunctionTemplate->getTemplatedDecl()->declarationReplaces(
1518 cast<FunctionTemplateDecl>(OldD)->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001519
Richard Smithe8292b12015-02-10 03:28:10 +00001520 // 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 Stump11289f42009-09-09 15:08:12 +00001527
Richard Smithe8292b12015-02-10 03:28:10 +00001528 // Using declarations can be overloaded if they introduce functions.
1529 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001530 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001531 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001532 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001533 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001534 }
Richard Smithe8292b12015-02-10 03:28:10 +00001535 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001536 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001537 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001538 Context.getCanonicalNestedNameSpecifier(
1539 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1540 }
1541
Richard Smithe8292b12015-02-10 03:28:10 +00001542 // 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();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001548
Richard Smithe8292b12015-02-10 03:28:10 +00001549 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 Gregor8b9ccca2008-12-23 21:05:05 +00001569}
1570
Douglas Gregoreddf4332009-02-24 20:03:32 +00001571bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001572 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001573}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001574
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001575NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001576 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-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 Carlsson6915bf62009-06-26 06:29:23 +00001584}
1585
John McCalla8ae2222010-04-06 21:38:20 +00001586bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001587 if (!isCXXClassMember())
1588 return false;
1589
John McCalla8ae2222010-04-06 21:38:20 +00001590 const NamedDecl *D = this;
1591 if (isa<UsingShadowDecl>(D))
1592 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1593
John McCall5e77d762013-04-16 07:28:30 +00001594 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001595 return true;
Alp Tokera2794f92014-01-22 07:29:52 +00001596 if (const CXXMethodDecl *MD =
1597 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1598 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001599 return false;
1600}
1601
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001602//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001603// DeclaratorDecl Implementation
1604//===----------------------------------------------------------------------===//
1605
Douglas Gregorec9c6ae2010-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 Kyrtzidis6032ef12009-08-21 00:31:54 +00001614SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001615 TypeSourceInfo *TSI = getTypeSourceInfo();
1616 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001617 return SourceLocation();
1618}
1619
Douglas Gregor14454802011-02-25 02:25:35 +00001620void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1621 if (QualifierLoc) {
John McCall3e11ebe2010-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 Gregor14454802011-02-25 02:25:35 +00001632 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001633 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001634 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001635 if (hasExtInfo()) {
Abramo Bagnara60804e12011-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 McCall3e11ebe2010-03-15 10:12:16 +00001646 }
1647 }
1648}
1649
Abramo Bagnara60804e12011-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 Gregorec9c6ae2010-07-06 18:42:40 +00001668SourceLocation DeclaratorDecl::getOuterLocStart() const {
1669 return getTemplateOrInnerLocStart(this);
1670}
1671
Abramo Bagnaraea947882011-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()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001715 // 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 Bagnaraea947882011-03-08 16:41:52 +00001718 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1719 }
1720 return SourceRange(getOuterLocStart(), RangeEnd);
1721}
1722
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001723void
Douglas Gregor20527e22010-06-15 17:44:38 +00001724QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1725 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001726 TemplateParameterList **TPLists) {
Craig Topper36250ad2014-05-12 05:36:57 +00001727 assert((NumTPLists == 0 || TPLists != nullptr) &&
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001728 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001729
1730 // Free previous template parameters (if any).
1731 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001732 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001733 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001734 NumTemplParamLists = 0;
1735 }
1736 // Set info on matched template parameter lists (if any).
1737 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001738 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001739 NumTemplParamLists = NumTPLists;
Benjamin Kramer67e6a542015-04-05 18:55:02 +00001740 std::copy(TPLists, TPLists + NumTPLists, TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001741 }
1742}
1743
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001744//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001745// VarDecl Implementation
1746//===----------------------------------------------------------------------===//
1747
Sebastian Redl833ef452010-01-26 22:01:41 +00001748const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1749 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001750 case SC_None: break;
Peter Collingbourne9a8f1532011-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 Redl833ef452010-01-26 22:01:41 +00001757 }
1758
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001759 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001760}
1761
Richard Smith053f6c62014-05-16 23:01:30 +00001762VarDecl::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() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001768 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1769 "VarDeclBitfields too large!");
1770 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1771 "ParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001772 AllBits = 0;
1773 VarDeclBits.SClass = SC;
1774 // Everything else is implicitly initialized to false.
1775}
1776
Abramo Bagnaradff19302011-03-08 08:55:46 +00001777VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1778 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001779 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001780 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001781 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001782}
1783
Douglas Gregor72172e92012-01-05 21:55:30 +00001784VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001785 return new (C, ID)
1786 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1787 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001788}
1789
Douglas Gregorbf62d642010-12-06 18:36:25 +00001790void VarDecl::setStorageClass(StorageClass SC) {
1791 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001792 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001793}
1794
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001795VarDecl::TLSKind VarDecl::getTLSKind() const {
1796 switch (VarDeclBits.TSCSpec) {
1797 case TSCS_unspecified:
David Majnemer1b5baff2015-05-14 05:19:23 +00001798 if (!hasAttr<ThreadAttr>())
1799 return TLS_None;
1800 return getASTContext().getLangOpts().isCompatibleWithMSVC(
1801 LangOptions::MSVC2015)
1802 ? TLS_Dynamic
1803 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001804 case TSCS___thread: // Fall through.
1805 case TSCS__Thread_local:
1806 return TLS_Static;
1807 case TSCS_thread_local:
1808 return TLS_Dynamic;
1809 }
1810 llvm_unreachable("Unknown thread storage class specifier!");
1811}
1812
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001813SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001814 if (const Expr *Init = getInit()) {
1815 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001816 // If Init is implicit, ignore its source range and fallback on
1817 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1818 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001819 return SourceRange(getOuterLocStart(), InitEnd);
1820 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001821 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001822}
1823
Rafael Espindola88510672013-01-04 21:18:45 +00001824template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001825static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001826 // C++ [dcl.link]p1: All function types, function names with external linkage,
1827 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001828 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001829 return NoLanguageLinkage;
1830
1831 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001832 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001833 ASTContext &Context = D.getASTContext();
1834 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001835 return CLanguageLinkage;
1836
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001837 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1838 // language linkage of the names of class members and the function type of
1839 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001840 const DeclContext *DC = D.getDeclContext();
1841 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001842 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001843
1844 // If the first decl is in an extern "C" context, any other redeclaration
1845 // will have C language linkage. If the first one is not in an extern "C"
1846 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001847 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001848 return CLanguageLinkage;
1849 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001850}
1851
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001852template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001853static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001854 // Since the context is ignored for class members, they can only have C++
1855 // language linkage or no language linkage.
1856 const DeclContext *DC = D.getDeclContext();
1857 if (DC->isRecord()) {
1858 assert(D.getASTContext().getLangOpts().CPlusPlus);
1859 return false;
1860 }
1861
1862 return D.getLanguageLinkage() == CLanguageLinkage;
1863}
1864
Rafael Espindolaf4187652013-02-14 01:18:37 +00001865LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001866 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001867}
1868
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001869bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001870 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001871}
1872
Rafael Espindola593537a2013-05-05 20:15:21 +00001873bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001874 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001875}
1876
1877bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001878 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001879}
1880
Rafael Espindola8db352d2013-10-17 15:37:26 +00001881VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001882
Nico Weber7f5015a2015-04-15 21:53:00 +00001883VarDecl::DefinitionKind
1884VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001885 // C++ [basic.def]p2:
1886 // A declaration is a definition unless [...] it contains the 'extern'
1887 // specifier or a linkage-specification and neither an initializer [...],
1888 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001889 // C++1y [temp.expl.spec]p15:
1890 // An explicit specialization of a static data member or an explicit
1891 // specialization of a static data member template is a definition if the
1892 // declaration includes an initializer; otherwise, it is a declaration.
1893 //
1894 // FIXME: How do you declare (but not define) a partial specialization of
1895 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001896 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001897 if (isOutOfLine() &&
1898 (hasInit() ||
1899 // If the first declaration is out-of-line, this may be an
1900 // instantiation of an out-of-line partial specialization of a variable
1901 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001902 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001903 ? getTemplateSpecializationKind() == TSK_Undeclared
1904 : getTemplateSpecializationKind() !=
1905 TSK_ExplicitSpecialization) ||
1906 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001907 return Definition;
1908 else
1909 return DeclarationOnly;
1910 }
1911 // C99 6.7p5:
1912 // A definition of an identifier is a declaration for that identifier that
1913 // [...] causes storage to be reserved for that object.
1914 // Note: that applies for all non-file-scope objects.
1915 // C99 6.9.2p1:
1916 // If the declaration of an identifier for an object has file scope and an
1917 // initializer, the declaration is an external definition for the identifier
1918 if (hasInit())
1919 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001920
David Majnemerdd0bed12015-05-14 05:19:20 +00001921 if (hasAttr<AliasAttr>())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001922 return Definition;
1923
David Majnemerdd0bed12015-05-14 05:19:20 +00001924 if (const auto *SAA = getAttr<SelectAnyAttr>())
1925 if (!SAA->isInherited())
1926 return Definition;
1927
Richard Smith8809a0c2013-09-27 20:14:12 +00001928 // A variable template specialization (other than a static data member
1929 // template or an explicit specialization) is a declaration until we
1930 // instantiate its initializer.
1931 if (isa<VarTemplateSpecializationDecl>(this) &&
1932 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1933 return DeclarationOnly;
1934
Nico Weber608e7682015-04-15 23:04:24 +00001935 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00001936 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001937
Rafael Espindolabff59562013-04-25 12:11:36 +00001938 // [dcl.link] p7:
1939 // A declaration directly contained in a linkage-specification is treated
1940 // as if it contains the extern specifier for the purpose of determining
1941 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00001942 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001943 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001944
Sebastian Redl35351a92010-01-31 22:27:38 +00001945 // C99 6.9.2p2:
1946 // A declaration of an object that has file scope without an initializer,
1947 // and without a storage class specifier or the scs 'static', constitutes
1948 // a tentative definition.
1949 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001950 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001951 return TentativeDefinition;
1952
1953 // What's left is (in C, block-scope) declarations without initializers or
1954 // external storage. These are definitions.
1955 return Definition;
1956}
1957
Sebastian Redl35351a92010-01-31 22:27:38 +00001958VarDecl *VarDecl::getActingDefinition() {
1959 DefinitionKind Kind = isThisDeclarationADefinition();
1960 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00001961 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001962
Craig Topper36250ad2014-05-12 05:36:57 +00001963 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001964 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001965 for (auto I : First->redecls()) {
1966 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001967 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00001968 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001969 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001970 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001971 }
1972 return LastTentative;
1973}
1974
Daniel Dunbar9d355812012-03-09 01:51:51 +00001975VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001976 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001977 for (auto I : First->redecls()) {
1978 if (I->isThisDeclarationADefinition(C) == Definition)
1979 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001980 }
Craig Topper36250ad2014-05-12 05:36:57 +00001981 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001982}
1983
Daniel Dunbar9d355812012-03-09 01:51:51 +00001984VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001985 DefinitionKind Kind = DeclarationOnly;
1986
Rafael Espindola8db352d2013-10-17 15:37:26 +00001987 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001988 for (auto I : First->redecls()) {
1989 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001990 if (Kind == Definition)
1991 break;
1992 }
John McCall37bb6c92010-10-29 22:22:43 +00001993
1994 return Kind;
1995}
1996
Sebastian Redl5ca79842010-02-01 20:16:42 +00001997const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00001998 for (auto I : redecls()) {
1999 if (auto Expr = I->getInit()) {
2000 D = I;
2001 return Expr;
2002 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002003 }
Craig Topper36250ad2014-05-12 05:36:57 +00002004 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002005}
2006
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002007bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002008 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002009 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002010
2011 if (!isStaticDataMember())
2012 return false;
2013
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002014 // If this static data member was instantiated from a static data member of
2015 // a class template, check whether that static data member was defined
2016 // out-of-line.
2017 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2018 return VD->isOutOfLine();
2019
2020 return false;
2021}
2022
Douglas Gregor1d957a32009-10-27 18:42:08 +00002023VarDecl *VarDecl::getOutOfLineDefinition() {
2024 if (!isStaticDataMember())
Craig Topper36250ad2014-05-12 05:36:57 +00002025 return nullptr;
2026
Aaron Ballman86c93902014-03-06 23:45:36 +00002027 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002028 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00002029 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00002030 }
Craig Topper36250ad2014-05-12 05:36:57 +00002031
2032 return nullptr;
Douglas Gregor1d957a32009-10-27 18:42:08 +00002033}
2034
Douglas Gregord5058122010-02-11 01:19:42 +00002035void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002036 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2037 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002038 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002039 }
2040
2041 Init = I;
2042}
2043
Daniel Dunbar9d355812012-03-09 01:51:51 +00002044bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002045 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002046
Richard Smith35ecb362012-03-02 04:14:40 +00002047 if (!Lang.CPlusPlus)
2048 return false;
2049
2050 // In C++11, any variable of reference type can be used in a constant
2051 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002052 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002053 return true;
2054
2055 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002056 // not require the variable to be non-volatile, but we consider this to be a
2057 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002058 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002059 return false;
2060
2061 // In C++, const, non-volatile variables of integral or enumeration types
2062 // can be used in constant expressions.
2063 if (getType()->isIntegralOrEnumerationType())
2064 return true;
2065
Richard Smith35ecb362012-03-02 04:14:40 +00002066 // Additionally, in C++11, non-volatile constexpr variables can be used in
2067 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002068 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002069}
2070
Richard Smithd0b4dd62011-12-19 06:19:21 +00002071/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2072/// form, which contains extra information on the evaluated value of the
2073/// initializer.
2074EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2075 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
2076 if (!Eval) {
2077 Stmt *S = Init.get<Stmt *>();
Manuel Klimeka7328992013-06-03 13:51:33 +00002078 // Note: EvaluatedStmt contains an APValue, which usually holds
2079 // resources not allocated from the ASTContext. We need to do some
2080 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2081 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002082 Eval = new (getASTContext()) EvaluatedStmt;
2083 Eval->Value = S;
2084 Init = Eval;
2085 }
2086 return Eval;
2087}
2088
Richard Smithdafff942012-01-14 04:30:29 +00002089APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002090 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002091 return evaluateValue(Notes);
2092}
2093
Manuel Klimeka7328992013-06-03 13:51:33 +00002094namespace {
2095// Destroy an APValue that was allocated in an ASTContext.
2096void DestroyAPValue(void* UntypedValue) {
2097 static_cast<APValue*>(UntypedValue)->~APValue();
2098}
2099} // namespace
2100
Richard Smithdafff942012-01-14 04:30:29 +00002101APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002102 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002103 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2104
2105 // We only produce notes indicating why an initializer is non-constant the
2106 // first time it is evaluated. FIXME: The notes won't always be emitted the
2107 // first time we try evaluation, so might not be produced at all.
2108 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002109 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002110
2111 const Expr *Init = cast<Expr>(Eval->Value);
2112 assert(!Init->isValueDependent());
2113
2114 if (Eval->IsEvaluating) {
2115 // FIXME: Produce a diagnostic for self-initialization.
2116 Eval->CheckedICE = true;
2117 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002118 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002119 }
2120
2121 Eval->IsEvaluating = true;
2122
2123 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2124 this, Notes);
2125
Manuel Klimeka7328992013-06-03 13:51:33 +00002126 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2127 // or that it's empty (so that there's nothing to clean up) if evaluation
2128 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002129 if (!Result)
2130 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002131 else if (Eval->Evaluated.needsCleanup())
2132 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002133
2134 Eval->IsEvaluating = false;
2135 Eval->WasEvaluated = true;
2136
2137 // In C++11, we have determined whether the initializer was a constant
2138 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002139 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002140 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002141 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002142 }
2143
Craig Topper36250ad2014-05-12 05:36:57 +00002144 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002145}
2146
2147bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002148 // Initializers of weak variables are never ICEs.
2149 if (isWeak())
2150 return false;
2151
Richard Smithd0b4dd62011-12-19 06:19:21 +00002152 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2153 if (Eval->CheckedICE)
2154 // We have already checked whether this subexpression is an
2155 // integral constant expression.
2156 return Eval->IsICE;
2157
2158 const Expr *Init = cast<Expr>(Eval->Value);
2159 assert(!Init->isValueDependent());
2160
2161 // In C++11, evaluate the initializer to check whether it's a constant
2162 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002163 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002164 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002165 evaluateValue(Notes);
2166 return Eval->IsICE;
2167 }
2168
2169 // It's an ICE whether or not the definition we found is
2170 // out-of-line. See DR 721 and the discussion in Clang PR
2171 // 6206 for details.
2172
2173 if (Eval->CheckingICE)
2174 return false;
2175 Eval->CheckingICE = true;
2176
2177 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2178 Eval->CheckingICE = false;
2179 Eval->CheckedICE = true;
2180 return Eval->IsICE;
2181}
2182
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002183VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002184 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002185 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002186
2187 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002188}
2189
Douglas Gregor3c74d412009-10-14 20:14:33 +00002190TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002191 if (const VarTemplateSpecializationDecl *Spec =
2192 dyn_cast<VarTemplateSpecializationDecl>(this))
2193 return Spec->getSpecializationKind();
2194
Sebastian Redl35351a92010-01-31 22:27:38 +00002195 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002196 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002197
Douglas Gregor86d142a2009-10-08 07:24:58 +00002198 return TSK_Undeclared;
2199}
2200
Richard Smith8809a0c2013-09-27 20:14:12 +00002201SourceLocation VarDecl::getPointOfInstantiation() const {
2202 if (const VarTemplateSpecializationDecl *Spec =
2203 dyn_cast<VarTemplateSpecializationDecl>(this))
2204 return Spec->getPointOfInstantiation();
2205
2206 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2207 return MSI->getPointOfInstantiation();
2208
2209 return SourceLocation();
2210}
2211
Larisse Voufo39a1e502013-08-06 01:03:05 +00002212VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2213 return getASTContext().getTemplateOrSpecializationInfo(this)
2214 .dyn_cast<VarTemplateDecl *>();
2215}
2216
2217void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2218 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2219}
2220
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002221MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002222 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002223 // FIXME: Remove ?
2224 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2225 return getASTContext().getTemplateOrSpecializationInfo(this)
2226 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002227 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002228}
2229
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002230void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2231 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002232 assert((isa<VarTemplateSpecializationDecl>(this) ||
2233 getMemberSpecializationInfo()) &&
2234 "not a variable or static data member template specialization");
2235
Larisse Voufo39a1e502013-08-06 01:03:05 +00002236 if (VarTemplateSpecializationDecl *Spec =
2237 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2238 Spec->setSpecializationKind(TSK);
2239 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2240 Spec->getPointOfInstantiation().isInvalid())
2241 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002242 }
2243
2244 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2245 MSI->setTemplateSpecializationKind(TSK);
2246 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2247 MSI->getPointOfInstantiation().isInvalid())
2248 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002249 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002250}
2251
2252void
2253VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2254 TemplateSpecializationKind TSK) {
2255 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2256 "Previous template or instantiation?");
2257 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002258}
2259
Sebastian Redl833ef452010-01-26 22:01:41 +00002260//===----------------------------------------------------------------------===//
2261// ParmVarDecl Implementation
2262//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002263
Sebastian Redl833ef452010-01-26 22:01:41 +00002264ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002265 SourceLocation StartLoc,
2266 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002267 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002268 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002269 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002270 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002271}
2272
Reid Kleckner8a365022013-06-24 17:51:48 +00002273QualType ParmVarDecl::getOriginalType() const {
2274 TypeSourceInfo *TSI = getTypeSourceInfo();
2275 QualType T = TSI ? TSI->getType() : getType();
2276 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2277 return DT->getOriginalType();
2278 return T;
2279}
2280
Douglas Gregor72172e92012-01-05 21:55:30 +00002281ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002282 return new (C, ID)
2283 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2284 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002285}
2286
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002287SourceRange ParmVarDecl::getSourceRange() const {
2288 if (!hasInheritedDefaultArg()) {
2289 SourceRange ArgRange = getDefaultArgRange();
2290 if (ArgRange.isValid())
2291 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2292 }
2293
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002294 // DeclaratorDecl considers the range of postfix types as overlapping with the
2295 // declaration name, but this is not the case with parameters in ObjC methods.
2296 if (isa<ObjCMethodDecl>(getDeclContext()))
2297 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2298
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002299 return DeclaratorDecl::getSourceRange();
2300}
2301
Sebastian Redl833ef452010-01-26 22:01:41 +00002302Expr *ParmVarDecl::getDefaultArg() {
2303 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2304 assert(!hasUninstantiatedDefaultArg() &&
2305 "Default argument is not yet instantiated!");
2306
2307 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00002308 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002309 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002310
Sebastian Redl833ef452010-01-26 22:01:41 +00002311 return Arg;
2312}
2313
Sebastian Redl833ef452010-01-26 22:01:41 +00002314SourceRange ParmVarDecl::getDefaultArgRange() const {
2315 if (const Expr *E = getInit())
2316 return E->getSourceRange();
2317
2318 if (hasUninstantiatedDefaultArg())
2319 return getUninstantiatedDefaultArg()->getSourceRange();
2320
2321 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002322}
2323
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002324bool ParmVarDecl::isParameterPack() const {
2325 return isa<PackExpansionType>(getType());
2326}
2327
Ted Kremenek540017e2011-10-06 05:00:56 +00002328void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2329 getASTContext().setParameterIndex(this, parameterIndex);
2330 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2331}
2332
2333unsigned ParmVarDecl::getParameterIndexLarge() const {
2334 return getASTContext().getParameterIndex(this);
2335}
2336
Nuno Lopes394ec982008-12-17 23:39:55 +00002337//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002338// FunctionDecl Implementation
2339//===----------------------------------------------------------------------===//
2340
Benjamin Kramer9170e912013-02-22 15:46:01 +00002341void FunctionDecl::getNameForDiagnostic(
2342 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2343 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002344 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2345 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002346 TemplateSpecializationType::PrintTemplateArgumentList(
2347 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002348}
2349
Ted Kremenek186a0742010-04-29 16:49:01 +00002350bool FunctionDecl::isVariadic() const {
2351 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2352 return FT->isVariadic();
2353 return false;
2354}
2355
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002356bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002357 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002358 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002359 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002360 return true;
2361 }
2362 }
2363
2364 return false;
2365}
2366
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002367bool FunctionDecl::hasTrivialBody() const
2368{
2369 Stmt *S = getBody();
2370 if (!S) {
2371 // Since we don't have a body for this function, we don't know if it's
2372 // trivial or not.
2373 return false;
2374 }
2375
2376 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2377 return true;
2378 return false;
2379}
2380
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002381bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002382 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002383 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2384 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002385 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002386 return true;
2387 }
2388 }
2389
2390 return false;
2391}
2392
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002393Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002394 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002395 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002396
2397 if (Definition->Body)
2398 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002399
Craig Topper36250ad2014-05-12 05:36:57 +00002400 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002401}
2402
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002403void FunctionDecl::setBody(Stmt *B) {
2404 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002405 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002406 EndRangeLoc = B->getLocEnd();
2407}
2408
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002409void FunctionDecl::setPure(bool P) {
2410 IsPure = P;
2411 if (P)
2412 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2413 Parent->markedVirtualFunctionPure();
2414}
2415
Richard Smith8d0dc312013-07-21 23:12:18 +00002416template<std::size_t Len>
2417static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2418 IdentifierInfo *II = ND->getIdentifier();
2419 return II && II->isStr(Str);
2420}
2421
Douglas Gregor16618f22009-09-12 00:17:51 +00002422bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002423 const TranslationUnitDecl *tunit =
2424 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2425 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002426 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002427 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002428}
2429
David Majnemerc729b0b2013-09-16 22:44:20 +00002430bool FunctionDecl::isMSVCRTEntryPoint() const {
2431 const TranslationUnitDecl *TUnit =
2432 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2433 if (!TUnit)
2434 return false;
2435
2436 // Even though we aren't really targeting MSVCRT if we are freestanding,
2437 // semantic analysis for these functions remains the same.
2438
2439 // MSVCRT entry points only exist on MSVCRT targets.
2440 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2441 return false;
2442
2443 // Nameless functions like constructors cannot be entry points.
2444 if (!getIdentifier())
2445 return false;
2446
2447 return llvm::StringSwitch<bool>(getName())
2448 .Cases("main", // an ANSI console app
2449 "wmain", // a Unicode console App
2450 "WinMain", // an ANSI GUI app
2451 "wWinMain", // a Unicode GUI app
2452 "DllMain", // a DLL
2453 true)
2454 .Default(false);
2455}
2456
John McCall53ffd372011-05-15 17:49:20 +00002457bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2458 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2459 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2460 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2461 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2462 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2463
Richard Smithf6004412014-01-19 23:25:37 +00002464 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2465 return false;
John McCall53ffd372011-05-15 17:49:20 +00002466
2467 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002468 if (proto->getNumParams() != 2 || proto->isVariadic())
2469 return false;
John McCall53ffd372011-05-15 17:49:20 +00002470
2471 ASTContext &Context =
2472 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2473 ->getASTContext();
2474
2475 // The result type and first argument type are constant across all
2476 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002477 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002478}
2479
Richard Smith8d0dc312013-07-21 23:12:18 +00002480bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2481 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2482 return false;
2483 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2484 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2485 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2486 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2487 return false;
2488
2489 if (isa<CXXRecordDecl>(getDeclContext()))
2490 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002491
2492 // This can only fail for an invalid 'operator new' declaration.
2493 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2494 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002495
2496 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
Nick Lewycky6fb99b92014-06-07 00:43:57 +00002497 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002498 return false;
2499
2500 // If this is a single-parameter function, it must be a replaceable global
2501 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002502 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002503 return true;
2504
2505 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002506 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002507 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002508 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002509 if (Ctx.getLangOpts().SizedDeallocation &&
2510 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002511 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002512 if (!Ty->isReferenceType())
2513 return false;
2514 Ty = Ty->getPointeeType();
2515 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2516 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002517 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Richard Trieuc771d5d2014-05-28 02:16:01 +00002518 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
Richard Smith8d0dc312013-07-21 23:12:18 +00002519}
2520
Rafael Espindolaf4187652013-02-14 01:18:37 +00002521LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002522 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002523}
2524
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002525bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002526 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002527}
2528
Rafael Espindola593537a2013-05-05 20:15:21 +00002529bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002530 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002531}
2532
2533bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002534 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002535}
2536
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002537bool FunctionDecl::isGlobal() const {
2538 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2539 return Method->isStatic();
2540
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002541 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002542 return false;
2543
Mike Stump11289f42009-09-09 15:08:12 +00002544 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002545 DC->isNamespace();
2546 DC = DC->getParent()) {
2547 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2548 if (!Namespace->getDeclName())
2549 return false;
2550 break;
2551 }
2552 }
2553
2554 return true;
2555}
2556
Richard Smith10876ef2013-01-17 01:30:42 +00002557bool FunctionDecl::isNoReturn() const {
2558 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002559 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002560 getType()->getAs<FunctionType>()->getNoReturnAttr();
2561}
2562
Sebastian Redl833ef452010-01-26 22:01:41 +00002563void
2564FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002565 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002566
2567 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2568 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002569 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002570 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002571 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002572 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002573
Axel Naumannfbc7b982011-11-08 18:21:06 +00002574 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002575 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002576}
2577
Rafael Espindola8db352d2013-10-17 15:37:26 +00002578FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002579
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002580/// \brief Returns a value indicating whether this function
2581/// corresponds to a builtin function.
2582///
2583/// The function corresponds to a built-in function if it is
2584/// declared at translation scope or within an extern "C" block and
2585/// its name matches with the name of a builtin. The returned value
2586/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002587/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002588/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002589unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002590 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002591 return 0;
2592
2593 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002594 if (!BuiltinID)
2595 return 0;
2596
2597 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002598 if (Context.getLangOpts().CPlusPlus) {
2599 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2600 getFirstDecl()->getDeclContext());
2601 // In C++, the first declaration of a builtin is always inside an implicit
2602 // extern "C".
2603 // FIXME: A recognised library function may not be directly in an extern "C"
2604 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002605 if (!LinkageDecl) {
2606 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2607 Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2608 isInStdNamespace())
2609 return Builtin::BI__GetExceptionInfo;
2610 return 0;
2611 }
2612 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002613 return 0;
2614 }
2615
2616 // If the function is marked "overloadable", it has a different mangled name
2617 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002618 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002619 return 0;
2620
Douglas Gregore711f702009-02-14 18:57:46 +00002621 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2622 return BuiltinID;
2623
2624 // This function has the name of a known C library
2625 // function. Determine whether it actually refers to the C library
2626 // function or whether it just has the same name.
2627
Douglas Gregora908e7f2009-02-17 03:23:10 +00002628 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002629 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002630 return 0;
2631
Warren Hunt445d83e2013-11-01 23:46:51 +00002632 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002633}
2634
2635
Chris Lattner47c0d002009-04-25 06:03:53 +00002636/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002637/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002638/// after it has been created.
2639unsigned FunctionDecl::getNumParams() const {
Reid Kleckner0503a872013-12-05 01:23:43 +00002640 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002641 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002642}
2643
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002644void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002645 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002646 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002647 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002648
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002649 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002650 if (!NewParamInfo.empty()) {
2651 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2652 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002653 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002654}
Chris Lattner41943152007-01-25 04:52:46 +00002655
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002656void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002657 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2658
2659 if (!NewDecls.empty()) {
2660 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2661 std::copy(NewDecls.begin(), NewDecls.end(), A);
Craig Topper5fc8fc22014-08-27 06:28:36 +00002662 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
Serge Pavlova8261472014-06-25 17:09:41 +00002663 // Move declarations introduced in prototype to the function context.
2664 for (auto I : NewDecls) {
2665 DeclContext *DC = I->getDeclContext();
2666 // Forward-declared reference to an enumeration is not added to
2667 // declaration scope, so skip declaration that is absent from its
2668 // declaration contexts.
2669 if (DC->containsDecl(I)) {
2670 DC->removeDecl(I);
2671 I->setDeclContext(this);
2672 addDecl(I);
2673 }
2674 }
James Molloy6f8780b2012-02-29 10:24:19 +00002675 }
2676}
2677
Chris Lattner58258242008-04-10 02:22:51 +00002678/// getMinRequiredArguments - Returns the minimum number of arguments
2679/// needed to call this function. This may be fewer than the number of
2680/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002681/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002682unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002683 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002684 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002685
Richard Smith91151782014-04-01 19:18:16 +00002686 unsigned NumRequiredArgs = 0;
2687 for (auto *Param : params())
2688 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2689 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002690 return NumRequiredArgs;
2691}
2692
David Majnemer54e3ba52014-04-02 23:17:29 +00002693/// \brief The combination of the extern and inline keywords under MSVC forces
2694/// the function to be required.
2695///
2696/// Note: This function assumes that we will only get called when isInlined()
2697/// would return true for this FunctionDecl.
2698bool FunctionDecl::isMSExternInline() const {
2699 assert(isInlined() && "expected to get called on an inlined function!");
2700
2701 const ASTContext &Context = getASTContext();
Hans Wennborgb0f2f142014-05-15 22:07:49 +00002702 if (!Context.getLangOpts().MSVCCompat && !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002703 return false;
2704
David Majnemer73768702015-03-20 00:02:27 +00002705 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2706 FD = FD->getPreviousDecl())
David Majnemer54e3ba52014-04-02 23:17:29 +00002707 if (FD->getStorageClass() == SC_Extern)
2708 return true;
2709
2710 return false;
2711}
2712
2713static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2714 if (Redecl->getStorageClass() != SC_Extern)
2715 return false;
2716
2717 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2718 FD = FD->getPreviousDecl())
2719 if (FD->getStorageClass() == SC_Extern)
2720 return false;
2721
2722 return true;
2723}
2724
Eli Friedman1b125c32012-02-07 03:50:18 +00002725static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2726 // Only consider file-scope declarations in this test.
2727 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2728 return false;
2729
2730 // Only consider explicit declarations; the presence of a builtin for a
2731 // libcall shouldn't affect whether a definition is externally visible.
2732 if (Redecl->isImplicit())
2733 return false;
2734
2735 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2736 return true; // Not an inline definition
2737
2738 return false;
2739}
2740
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002741/// \brief For a function declaration in C or C++, determine whether this
2742/// declaration causes the definition to be externally visible.
2743///
David Majnemer54e3ba52014-04-02 23:17:29 +00002744/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002745/// of redeclarations of the given functions causes
2746/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002747bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2748 assert(!doesThisDeclarationHaveABody() &&
2749 "Must have a declaration without a body.");
2750
2751 ASTContext &Context = getASTContext();
2752
David Majnemer54e3ba52014-04-02 23:17:29 +00002753 if (Context.getLangOpts().MSVCCompat) {
2754 const FunctionDecl *Definition;
2755 if (hasBody(Definition) && Definition->isInlined() &&
2756 redeclForcesDefMSVC(this))
2757 return true;
2758 }
2759
David Blaikiebbafb8a2012-03-11 07:00:24 +00002760 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002761 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2762 // an externally visible definition.
2763 //
2764 // FIXME: What happens if gnu_inline gets added on after the first
2765 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002766 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002767 return false;
2768
2769 const FunctionDecl *Prev = this;
2770 bool FoundBody = false;
2771 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002772 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002773
2774 if (Prev->Body) {
2775 // If it's not the case that both 'inline' and 'extern' are
2776 // specified on the definition, then it is always externally visible.
2777 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002778 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002779 return false;
2780 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002781 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002782 return false;
2783 }
2784 }
2785 return FoundBody;
2786 }
2787
David Blaikiebbafb8a2012-03-11 07:00:24 +00002788 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002789 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002790
2791 // C99 6.7.4p6:
2792 // [...] If all of the file scope declarations for a function in a
2793 // translation unit include the inline function specifier without extern,
2794 // then the definition in that translation unit is an inline definition.
2795 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002796 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002797 const FunctionDecl *Prev = this;
2798 bool FoundBody = false;
2799 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002800 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002801 if (RedeclForcesDefC99(Prev))
2802 return false;
2803 }
2804 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002805}
2806
Alp Tokerd0787eb2014-07-02 01:47:15 +00002807SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2808 const TypeSourceInfo *TSI = getTypeSourceInfo();
2809 if (!TSI)
2810 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00002811 FunctionTypeLoc FTL =
2812 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2813 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00002814 return SourceRange();
2815
Alp Tokerf5b10792014-07-02 12:55:58 +00002816 // Skip self-referential return types.
2817 const SourceManager &SM = getASTContext().getSourceManager();
2818 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2819 SourceLocation Boundary = getNameInfo().getLocStart();
2820 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2821 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2822 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00002823
Alp Tokerf5b10792014-07-02 12:55:58 +00002824 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00002825}
2826
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002827bool FunctionDecl::hasUnusedResultAttr() const {
2828 QualType RetType = getReturnType();
2829 if (RetType->isRecordType()) {
2830 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
2831 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(this);
2832 if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
2833 !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
2834 return true;
2835 }
2836 return hasAttr<WarnUnusedResultAttr>();
2837}
2838
Richard Smithf3814ad2013-01-25 00:08:28 +00002839/// \brief For an inline function definition in C, or for a gnu_inline function
2840/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002841///
2842/// Inline function definitions are always available for inlining optimizations.
2843/// However, depending on the language dialect, declaration specifiers, and
2844/// attributes, the definition of an inline function may or may not be
2845/// "externally" visible to other translation units in the program.
2846///
2847/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002848/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002849/// inline definition becomes externally visible (C99 6.7.4p6).
2850///
2851/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2852/// definition, we use the GNU semantics for inline, which are nearly the
2853/// opposite of C99 semantics. In particular, "inline" by itself will create
2854/// an externally visible symbol, but "extern inline" will not create an
2855/// externally visible symbol.
2856bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002857 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002858 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002859 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002860
David Blaikiebbafb8a2012-03-11 07:00:24 +00002861 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002862 // Note: If you change the logic here, please change
2863 // doesDeclarationForceExternallyVisibleDefinition as well.
2864 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002865 // If it's not the case that both 'inline' and 'extern' are
2866 // specified on the definition, then this inline definition is
2867 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002868 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002869 return true;
2870
2871 // If any declaration is 'inline' but not 'extern', then this definition
2872 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002873 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002874 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002875 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002876 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002877 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002878
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002879 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002880 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002881
Richard Smithf3814ad2013-01-25 00:08:28 +00002882 // The rest of this function is C-only.
2883 assert(!Context.getLangOpts().CPlusPlus &&
2884 "should not use C inline rules in C++");
2885
Douglas Gregor299d76e2009-09-13 07:46:26 +00002886 // C99 6.7.4p6:
2887 // [...] If all of the file scope declarations for a function in a
2888 // translation unit include the inline function specifier without extern,
2889 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002890 for (auto Redecl : redecls()) {
2891 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002892 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002893 }
2894
2895 // C99 6.7.4p6:
2896 // An inline definition does not provide an external definition for the
2897 // function, and does not forbid an external definition in another
2898 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002899 return false;
2900}
2901
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002902/// getOverloadedOperator - Which C++ overloaded operator this
2903/// function represents, if any.
2904OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002905 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2906 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002907 else
2908 return OO_None;
2909}
2910
Alexis Huntc88db062010-01-13 09:01:02 +00002911/// getLiteralIdentifier - The literal suffix identifier this function
2912/// represents, if any.
2913const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2914 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2915 return getDeclName().getCXXLiteralIdentifier();
2916 else
Craig Topper36250ad2014-05-12 05:36:57 +00002917 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00002918}
2919
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002920FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2921 if (TemplateOrSpecialization.isNull())
2922 return TK_NonTemplate;
2923 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2924 return TK_FunctionTemplate;
2925 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2926 return TK_MemberSpecialization;
2927 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2928 return TK_FunctionTemplateSpecialization;
2929 if (TemplateOrSpecialization.is
2930 <DependentFunctionTemplateSpecializationInfo*>())
2931 return TK_DependentFunctionTemplateSpecialization;
2932
David Blaikie83d382b2011-09-23 05:06:16 +00002933 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002934}
2935
Douglas Gregord801b062009-10-07 23:56:10 +00002936FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002937 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002938 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002939
2940 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00002941}
2942
2943void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002944FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2945 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002946 TemplateSpecializationKind TSK) {
2947 assert(TemplateOrSpecialization.isNull() &&
2948 "Member function is already a specialization");
2949 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002950 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002951 TemplateOrSpecialization = Info;
2952}
2953
Douglas Gregorafca3b42009-10-27 20:53:28 +00002954bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002955 // If the function is invalid, it can't be implicitly instantiated.
2956 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002957 return false;
2958
2959 switch (getTemplateSpecializationKind()) {
2960 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002961 case TSK_ExplicitInstantiationDefinition:
2962 return false;
2963
2964 case TSK_ImplicitInstantiation:
2965 return true;
2966
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002967 // It is possible to instantiate TSK_ExplicitSpecialization kind
2968 // if the FunctionDecl has a class scope specialization pattern.
2969 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00002970 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002971
Douglas Gregorafca3b42009-10-27 20:53:28 +00002972 case TSK_ExplicitInstantiationDeclaration:
2973 // Handled below.
2974 break;
2975 }
2976
2977 // Find the actual template from which we will instantiate.
2978 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002979 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002980 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002981 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002982
2983 // C++0x [temp.explicit]p9:
2984 // Except for inline functions, other explicit instantiation declarations
2985 // have the effect of suppressing the implicit instantiation of the entity
2986 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002987 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002988 return true;
2989
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002990 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002991}
2992
2993bool FunctionDecl::isTemplateInstantiation() const {
2994 switch (getTemplateSpecializationKind()) {
2995 case TSK_Undeclared:
2996 case TSK_ExplicitSpecialization:
2997 return false;
2998 case TSK_ImplicitInstantiation:
2999 case TSK_ExplicitInstantiationDeclaration:
3000 case TSK_ExplicitInstantiationDefinition:
3001 return true;
3002 }
3003 llvm_unreachable("All TSK values handled.");
3004}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003005
3006FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003007 // Handle class scope explicit specialization special case.
3008 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3009 return getClassScopeSpecializationPattern();
Faisal Valib90b2112014-04-03 16:32:21 +00003010
3011 // If this is a generic lambda call operator specialization, its
3012 // instantiation pattern is always its primary template's pattern
3013 // even if its primary template was instantiated from another
3014 // member template (which happens with nested generic lambdas).
3015 // Since a lambda's call operator's body is transformed eagerly,
3016 // we don't have to go hunting for a prototype definition template
3017 // (i.e. instantiated-from-member-template) to use as an instantiation
3018 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003019
Faisal Valib90b2112014-04-03 16:32:21 +00003020 if (isGenericLambdaCallOperatorSpecialization(
3021 dyn_cast<CXXMethodDecl>(this))) {
3022 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3023 "generated from a primary call operator "
3024 "template");
3025 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3026 "A generic lambda call operator template must always have a body - "
3027 "even if instantiated from a prototype (i.e. as written) member "
3028 "template");
3029 return getPrimaryTemplate()->getTemplatedDecl();
3030 }
3031
Douglas Gregorafca3b42009-10-27 20:53:28 +00003032 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3033 while (Primary->getInstantiatedFromMemberTemplate()) {
3034 // If we have hit a point where the user provided a specialization of
3035 // this template, we're done looking.
3036 if (Primary->isMemberSpecialization())
3037 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003038 Primary = Primary->getInstantiatedFromMemberTemplate();
3039 }
3040
3041 return Primary->getTemplatedDecl();
3042 }
3043
3044 return getInstantiatedFromMemberFunction();
3045}
3046
Douglas Gregor70d83e22009-06-29 17:30:29 +00003047FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003048 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003049 = TemplateOrSpecialization
3050 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003051 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003052 }
Craig Topper36250ad2014-05-12 05:36:57 +00003053 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003054}
3055
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003056FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3057 return getASTContext().getClassScopeSpecializationPattern(this);
3058}
3059
Douglas Gregor70d83e22009-06-29 17:30:29 +00003060const TemplateArgumentList *
3061FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003062 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003063 = TemplateOrSpecialization
3064 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003065 return Info->TemplateArguments;
3066 }
Craig Topper36250ad2014-05-12 05:36:57 +00003067 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003068}
3069
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003070const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003071FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3072 if (FunctionTemplateSpecializationInfo *Info
3073 = TemplateOrSpecialization
3074 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3075 return Info->TemplateArgumentsAsWritten;
3076 }
Craig Topper36250ad2014-05-12 05:36:57 +00003077 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003078}
3079
Mike Stump11289f42009-09-09 15:08:12 +00003080void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003081FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3082 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003083 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003084 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003085 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003086 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3087 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003088 assert(TSK != TSK_Undeclared &&
3089 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003090 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003091 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003092 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003093 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3094 TemplateArgs,
3095 TemplateArgsAsWritten,
3096 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003097 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003098 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003099}
3100
John McCallb9c78482010-04-08 09:05:18 +00003101void
3102FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3103 const UnresolvedSetImpl &Templates,
3104 const TemplateArgumentListInfo &TemplateArgs) {
3105 assert(TemplateOrSpecialization.isNull());
3106 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
3107 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00003108 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00003109 void *Buffer = Context.Allocate(Size);
3110 DependentFunctionTemplateSpecializationInfo *Info =
3111 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
3112 TemplateArgs);
3113 TemplateOrSpecialization = Info;
3114}
3115
3116DependentFunctionTemplateSpecializationInfo::
3117DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3118 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003119 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
Benjamin Kramer1d4ffd72015-04-02 12:25:07 +00003120 static_assert(sizeof(*this) % llvm::AlignOf<void *>::Alignment == 0,
3121 "Trailing data is unaligned!");
John McCallb9c78482010-04-08 09:05:18 +00003122
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003123 d.NumTemplates = Ts.size();
3124 d.NumArgs = TArgs.size();
3125
John McCallb9c78482010-04-08 09:05:18 +00003126 FunctionTemplateDecl **TsArray =
3127 const_cast<FunctionTemplateDecl**>(getTemplates());
3128 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3129 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3130
3131 TemplateArgumentLoc *ArgsArray =
3132 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
3133 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3134 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3135}
3136
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003137TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003138 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003139 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003140 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003141 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003142 if (FTSInfo)
3143 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003144
Douglas Gregord801b062009-10-07 23:56:10 +00003145 MemberSpecializationInfo *MSInfo
3146 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3147 if (MSInfo)
3148 return MSInfo->getTemplateSpecializationKind();
3149
3150 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003151}
3152
Mike Stump11289f42009-09-09 15:08:12 +00003153void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003154FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3155 SourceLocation PointOfInstantiation) {
3156 if (FunctionTemplateSpecializationInfo *FTSInfo
3157 = TemplateOrSpecialization.dyn_cast<
3158 FunctionTemplateSpecializationInfo*>()) {
3159 FTSInfo->setTemplateSpecializationKind(TSK);
3160 if (TSK != TSK_ExplicitSpecialization &&
3161 PointOfInstantiation.isValid() &&
3162 FTSInfo->getPointOfInstantiation().isInvalid())
3163 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3164 } else if (MemberSpecializationInfo *MSInfo
3165 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3166 MSInfo->setTemplateSpecializationKind(TSK);
3167 if (TSK != TSK_ExplicitSpecialization &&
3168 PointOfInstantiation.isValid() &&
3169 MSInfo->getPointOfInstantiation().isInvalid())
3170 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3171 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003172 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003173}
3174
3175SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003176 if (FunctionTemplateSpecializationInfo *FTSInfo
3177 = TemplateOrSpecialization.dyn_cast<
3178 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003179 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003180 else if (MemberSpecializationInfo *MSInfo
3181 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003182 return MSInfo->getPointOfInstantiation();
3183
3184 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003185}
3186
Douglas Gregor6411b922009-09-11 20:15:17 +00003187bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003188 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003189 return true;
3190
3191 // If this function was instantiated from a member function of a
3192 // class template, check whether that member function was defined out-of-line.
3193 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3194 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003195 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003196 return Definition->isOutOfLine();
3197 }
3198
3199 // If this function was instantiated from a function template,
3200 // check whether that function template was defined out-of-line.
3201 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3202 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003203 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003204 return Definition->isOutOfLine();
3205 }
3206
3207 return false;
3208}
3209
Abramo Bagnaraea947882011-03-08 16:41:52 +00003210SourceRange FunctionDecl::getSourceRange() const {
3211 return SourceRange(getOuterLocStart(), EndRangeLoc);
3212}
3213
Anna Zaks28db7ce2012-01-18 02:45:01 +00003214unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003215 IdentifierInfo *FnInfo = getIdentifier();
3216
3217 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003218 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003219
3220 // Builtin handling.
3221 switch (getBuiltinID()) {
3222 case Builtin::BI__builtin_memset:
3223 case Builtin::BI__builtin___memset_chk:
3224 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003225 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003226
3227 case Builtin::BI__builtin_memcpy:
3228 case Builtin::BI__builtin___memcpy_chk:
3229 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003230 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003231
3232 case Builtin::BI__builtin_memmove:
3233 case Builtin::BI__builtin___memmove_chk:
3234 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003235 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003236
3237 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003238 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003239 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003240
Anna Zaks201d4892012-01-13 21:52:01 +00003241 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003242 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003243 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003244
3245 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003246 case Builtin::BImemcmp:
3247 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003248
3249 case Builtin::BI__builtin_strncpy:
3250 case Builtin::BI__builtin___strncpy_chk:
3251 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003252 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003253
3254 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003255 case Builtin::BIstrncmp:
3256 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003257
3258 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003259 case Builtin::BIstrncasecmp:
3260 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003261
3262 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003263 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003264 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003265 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003266
3267 case Builtin::BI__builtin_strndup:
3268 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003269 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003270
Anna Zaks314cd092012-02-01 19:08:57 +00003271 case Builtin::BI__builtin_strlen:
3272 case Builtin::BIstrlen:
3273 return Builtin::BIstrlen;
3274
Anna Zaks201d4892012-01-13 21:52:01 +00003275 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003276 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003277 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003278 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003279 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003280 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003281 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003282 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003283 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003284 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003285 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003286 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003287 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003288 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003289 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003290 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003291 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003292 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003293 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003294 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003295 else if (FnInfo->isStr("strlen"))
3296 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003297 }
3298 break;
3299 }
Anna Zaks22122702012-01-17 00:37:07 +00003300 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003301}
3302
Chris Lattner59a25942008-03-31 00:36:02 +00003303//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003304// FieldDecl Implementation
3305//===----------------------------------------------------------------------===//
3306
Jay Foad39c79802011-01-12 09:06:06 +00003307FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003308 SourceLocation StartLoc, SourceLocation IdLoc,
3309 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003310 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003311 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003312 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3313 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003314}
3315
Douglas Gregor72172e92012-01-05 21:55:30 +00003316FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003317 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3318 SourceLocation(), nullptr, QualType(), nullptr,
3319 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003320}
3321
Sebastian Redl833ef452010-01-26 22:01:41 +00003322bool FieldDecl::isAnonymousStructOrUnion() const {
3323 if (!isImplicit() || getDeclName())
3324 return false;
3325
3326 if (const RecordType *Record = getType()->getAs<RecordType>())
3327 return Record->getDecl()->isAnonymousStructOrUnion();
3328
3329 return false;
3330}
3331
Richard Smithcaf33902011-10-10 18:28:20 +00003332unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3333 assert(isBitField() && "not a bitfield");
John McCallc90c1492014-10-10 18:44:34 +00003334 Expr *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
Richard Smithcaf33902011-10-10 18:28:20 +00003335 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3336}
3337
John McCall4e819612011-01-20 07:57:12 +00003338unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003339 const FieldDecl *Canonical = getCanonicalDecl();
3340 if (Canonical != this)
3341 return Canonical->getFieldIndex();
3342
John McCall4e819612011-01-20 07:57:12 +00003343 if (CachedFieldIndex) return CachedFieldIndex - 1;
3344
Richard Smithd62306a2011-11-10 06:34:14 +00003345 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003346 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003347
Hans Wennborga302cd92014-08-21 16:06:57 +00003348 for (auto *Field : RD->fields()) {
3349 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3350 ++Index;
3351 }
John McCall4e819612011-01-20 07:57:12 +00003352
Richard Smithd62306a2011-11-10 06:34:14 +00003353 assert(CachedFieldIndex && "failed to find field in parent");
3354 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003355}
3356
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003357SourceRange FieldDecl::getSourceRange() const {
John McCallc90c1492014-10-10 18:44:34 +00003358 switch (InitStorage.getInt()) {
3359 // All three of these cases store an optional Expr*.
3360 case ISK_BitWidthOrNothing:
3361 case ISK_InClassCopyInit:
3362 case ISK_InClassListInit:
3363 if (const Expr *E = static_cast<const Expr *>(InitStorage.getPointer()))
3364 return SourceRange(getInnerLocStart(), E->getLocEnd());
3365 // FALLTHROUGH
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003366
John McCallc90c1492014-10-10 18:44:34 +00003367 case ISK_CapturedVLAType:
3368 return DeclaratorDecl::getSourceRange();
3369 }
3370 llvm_unreachable("bad init storage kind");
Alexey Bataev39c81e22014-08-28 04:28:19 +00003371}
3372
3373void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003374 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003375 "capturing type in non-lambda or captured record.");
John McCallc90c1492014-10-10 18:44:34 +00003376 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3377 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003378 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003379 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3380 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003381}
3382
Sebastian Redl833ef452010-01-26 22:01:41 +00003383//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003384// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003385//===----------------------------------------------------------------------===//
3386
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003387SourceLocation TagDecl::getOuterLocStart() const {
3388 return getTemplateOrInnerLocStart(this);
3389}
3390
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003391SourceRange TagDecl::getSourceRange() const {
3392 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003393 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003394}
3395
Rafael Espindola8db352d2013-10-17 15:37:26 +00003396TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003397
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003398void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer50ce8352013-09-17 23:57:10 +00003399 NamedDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003400 if (const Type *T = getTypeForDecl()) {
3401 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003402 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003403 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003404 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003405}
3406
Douglas Gregordee1be82009-01-17 00:42:38 +00003407void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003408 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003409
David Blaikie095deba2012-11-14 01:52:05 +00003410 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003411 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003412 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003413 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003414 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003415 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003416}
3417
3418void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003419 assert((!isa<CXXRecordDecl>(this) ||
3420 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3421 "definition completed but not started");
3422
John McCallf937c022011-10-07 06:10:15 +00003423 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003424 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003425
3426 if (ASTMutationListener *L = getASTMutationListener())
3427 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003428}
3429
John McCallf937c022011-10-07 06:10:15 +00003430TagDecl *TagDecl::getDefinition() const {
3431 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003432 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003433
3434 // If it's possible for us to have an out-of-date definition, check now.
3435 if (MayHaveOutOfDateDef) {
3436 if (IdentifierInfo *II = getIdentifier()) {
3437 if (II->isOutOfDate()) {
3438 updateOutOfDate(*II);
3439 }
3440 }
3441 }
3442
Andrew Trickba266ee2010-10-19 21:54:32 +00003443 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3444 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003445
Aaron Ballman86c93902014-03-06 23:45:36 +00003446 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003447 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003448 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003449
Craig Topper36250ad2014-05-12 05:36:57 +00003450 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003451}
3452
Douglas Gregor14454802011-02-25 02:25:35 +00003453void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3454 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003455 // Make sure the extended qualifier info is allocated.
3456 if (!hasExtInfo())
David Majnemer50ce8352013-09-17 23:57:10 +00003457 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003458 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003459 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003460 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003461 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003462 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003463 if (getExtInfo()->NumTemplParamLists == 0) {
3464 getASTContext().Deallocate(getExtInfo());
Craig Topper36250ad2014-05-12 05:36:57 +00003465 NamedDeclOrQualifier = (TypedefNameDecl*)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003466 }
3467 else
3468 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003469 }
3470 }
3471}
3472
Abramo Bagnara60804e12011-03-18 15:16:37 +00003473void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3474 unsigned NumTPLists,
3475 TemplateParameterList **TPLists) {
3476 assert(NumTPLists > 0);
3477 // Make sure the extended decl info is allocated.
3478 if (!hasExtInfo())
3479 // Allocate external info struct.
David Majnemer50ce8352013-09-17 23:57:10 +00003480 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003481 // Set the template parameter lists info.
3482 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3483}
3484
Ted Kremenek21475702008-09-05 17:16:31 +00003485//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003486// EnumDecl Implementation
3487//===----------------------------------------------------------------------===//
3488
David Blaikie68e081d2011-12-20 02:48:34 +00003489void EnumDecl::anchor() { }
3490
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003491EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3492 SourceLocation StartLoc, SourceLocation IdLoc,
3493 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003494 EnumDecl *PrevDecl, bool IsScoped,
3495 bool IsScopedUsingClassTag, bool IsFixed) {
Richard Smith053f6c62014-05-16 23:01:30 +00003496 EnumDecl *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
Richard Smithf7981722013-11-22 09:01:48 +00003497 IsScoped, IsScopedUsingClassTag,
3498 IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003499 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003500 C.getTypeDeclType(Enum, PrevDecl);
3501 return Enum;
3502}
3503
Douglas Gregor72172e92012-01-05 21:55:30 +00003504EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003505 EnumDecl *Enum =
3506 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3507 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003508 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3509 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003510}
3511
Alp Tokerb9fa5122014-01-06 11:31:18 +00003512SourceRange EnumDecl::getIntegerTypeRange() const {
3513 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3514 return TI->getTypeLoc().getSourceRange();
3515 return SourceRange();
3516}
3517
Douglas Gregord5058122010-02-11 01:19:42 +00003518void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003519 QualType NewPromotionType,
3520 unsigned NumPositiveBits,
3521 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003522 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003523 if (!IntegerType)
3524 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003525 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003526 setNumPositiveBits(NumPositiveBits);
3527 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003528 TagDecl::completeDefinition();
3529}
3530
Richard Smith7d137e32012-03-23 03:33:32 +00003531TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3532 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3533 return MSI->getTemplateSpecializationKind();
3534
3535 return TSK_Undeclared;
3536}
3537
3538void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3539 SourceLocation PointOfInstantiation) {
3540 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3541 assert(MSI && "Not an instantiated member enumeration?");
3542 MSI->setTemplateSpecializationKind(TSK);
3543 if (TSK != TSK_ExplicitSpecialization &&
3544 PointOfInstantiation.isValid() &&
3545 MSI->getPointOfInstantiation().isInvalid())
3546 MSI->setPointOfInstantiation(PointOfInstantiation);
3547}
3548
Richard Smith4b38ded2012-03-14 23:13:10 +00003549EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3550 if (SpecializationInfo)
3551 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3552
Craig Topper36250ad2014-05-12 05:36:57 +00003553 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003554}
3555
3556void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3557 TemplateSpecializationKind TSK) {
3558 assert(!SpecializationInfo && "Member enum is already a specialization");
3559 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3560}
3561
Sebastian Redl833ef452010-01-26 22:01:41 +00003562//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003563// RecordDecl Implementation
3564//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003565
Richard Smith053f6c62014-05-16 23:01:30 +00003566RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3567 DeclContext *DC, SourceLocation StartLoc,
3568 SourceLocation IdLoc, IdentifierInfo *Id,
3569 RecordDecl *PrevDecl)
3570 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003571 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003572 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003573 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003574 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003575 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003576 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003577}
3578
Jay Foad39c79802011-01-12 09:06:06 +00003579RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003580 SourceLocation StartLoc, SourceLocation IdLoc,
3581 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003582 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3583 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003584 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3585
Ted Kremenek21475702008-09-05 17:16:31 +00003586 C.getTypeDeclType(R, PrevDecl);
3587 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003588}
3589
Douglas Gregor72172e92012-01-05 21:55:30 +00003590RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003591 RecordDecl *R =
3592 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3593 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003594 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3595 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003596}
3597
Douglas Gregordfcad112009-03-25 15:59:44 +00003598bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003599 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003600 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3601}
3602
Alexey Bataev39c81e22014-08-28 04:28:19 +00003603bool RecordDecl::isLambda() const {
3604 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3605 return RD->isLambda();
3606 return false;
3607}
3608
Alexey Bataev330de032014-10-29 12:21:55 +00003609bool RecordDecl::isCapturedRecord() const {
3610 return hasAttr<CapturedRecordAttr>();
3611}
3612
3613void RecordDecl::setCapturedRecord() {
3614 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3615}
3616
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003617RecordDecl::field_iterator RecordDecl::field_begin() const {
3618 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3619 LoadFieldsFromExternalStorage();
3620
3621 return field_iterator(decl_iterator(FirstDecl));
3622}
3623
Douglas Gregorb11aad82011-02-19 18:51:44 +00003624/// completeDefinition - Notes that the definition of this type is now
3625/// complete.
3626void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003627 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003628 TagDecl::completeDefinition();
3629}
3630
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003631/// isMsStruct - Get whether or not this record uses ms_struct layout.
3632/// This which can be turned on with an attribute, pragma, or the
3633/// -mms-bitfields command-line option.
3634bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003635 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003636}
3637
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003638static bool isFieldOrIndirectField(Decl::Kind K) {
3639 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3640}
3641
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003642void RecordDecl::LoadFieldsFromExternalStorage() const {
3643 ExternalASTSource *Source = getASTContext().getExternalSource();
3644 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3645
3646 // Notify that we have a RecordDecl doing some initialization.
3647 ExternalASTSource::Deserializing TheFields(Source);
3648
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003649 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003650 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003651 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3652 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003653 case ELR_Success:
3654 break;
3655
3656 case ELR_AlreadyLoaded:
3657 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003658 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003659 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003660
3661#ifndef NDEBUG
3662 // Check that all decls we got were FieldDecls.
3663 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003664 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003665#endif
3666
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003667 if (Decls.empty())
3668 return;
3669
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003670 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003671 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003672}
3673
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003674bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3675 ASTContext &Context = getASTContext();
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003676 if (!Context.getLangOpts().Sanitize.has(SanitizerKind::Address) ||
Alexey Samsonova0416102014-11-11 01:26:14 +00003677 !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003678 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003679 const auto &Blacklist = Context.getSanitizerBlacklist();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003680 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003681 // We may be able to relax some of these requirements.
3682 int ReasonToReject = -1;
3683 if (!CXXRD || CXXRD->isExternCContext())
3684 ReasonToReject = 0; // is not C++.
3685 else if (CXXRD->hasAttr<PackedAttr>())
3686 ReasonToReject = 1; // is packed.
3687 else if (CXXRD->isUnion())
3688 ReasonToReject = 2; // is a union.
3689 else if (CXXRD->isTriviallyCopyable())
3690 ReasonToReject = 3; // is trivially copyable.
3691 else if (CXXRD->hasTrivialDestructor())
3692 ReasonToReject = 4; // has trivial destructor.
3693 else if (CXXRD->isStandardLayout())
3694 ReasonToReject = 5; // is standard layout.
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003695 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003696 ReasonToReject = 6; // is in a blacklisted file.
3697 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3698 "field-padding"))
3699 ReasonToReject = 7; // is blacklisted.
3700
3701 if (EmitRemark) {
3702 if (ReasonToReject >= 0)
3703 Context.getDiagnostics().Report(
3704 getLocation(),
3705 diag::remark_sanitize_address_insert_extra_padding_rejected)
3706 << getQualifiedNameAsString() << ReasonToReject;
3707 else
3708 Context.getDiagnostics().Report(
3709 getLocation(),
3710 diag::remark_sanitize_address_insert_extra_padding_accepted)
3711 << getQualifiedNameAsString();
3712 }
3713 return ReasonToReject < 0;
3714}
3715
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003716const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3717 for (const auto *I : fields()) {
3718 if (I->getIdentifier())
3719 return I;
3720
3721 if (const RecordType *RT = I->getType()->getAs<RecordType>())
3722 if (const FieldDecl *NamedDataMember =
3723 RT->getDecl()->findFirstNamedDataMember())
3724 return NamedDataMember;
3725 }
3726
3727 // We didn't find a named data member.
3728 return nullptr;
3729}
3730
3731
Steve Naroff415d3d52008-10-08 17:01:13 +00003732//===----------------------------------------------------------------------===//
3733// BlockDecl Implementation
3734//===----------------------------------------------------------------------===//
3735
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003736void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003737 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003738
Steve Naroffc4b30e52009-03-13 16:56:44 +00003739 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003740 if (!NewParamInfo.empty()) {
3741 NumParams = NewParamInfo.size();
3742 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3743 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003744 }
3745}
3746
John McCall351762c2011-02-07 10:33:21 +00003747void BlockDecl::setCaptures(ASTContext &Context,
3748 const Capture *begin,
3749 const Capture *end,
3750 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003751 CapturesCXXThis = capturesCXXThis;
3752
3753 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003754 NumCaptures = 0;
Craig Topper36250ad2014-05-12 05:36:57 +00003755 Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00003756 return;
3757 }
3758
John McCall351762c2011-02-07 10:33:21 +00003759 NumCaptures = end - begin;
3760
3761 // Avoid new Capture[] because we don't want to provide a default
3762 // constructor.
3763 size_t allocationSize = NumCaptures * sizeof(Capture);
3764 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3765 memcpy(buffer, begin, allocationSize);
3766 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003767}
Sebastian Redl833ef452010-01-26 22:01:41 +00003768
John McCallce45f882011-06-15 22:51:16 +00003769bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003770 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003771 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003772 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003773 return true;
3774
3775 return false;
3776}
3777
Douglas Gregor70226da2010-12-21 16:27:07 +00003778SourceRange BlockDecl::getSourceRange() const {
3779 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3780}
Sebastian Redl833ef452010-01-26 22:01:41 +00003781
3782//===----------------------------------------------------------------------===//
3783// Other Decl Allocation/Deallocation Method Implementations
3784//===----------------------------------------------------------------------===//
3785
David Blaikie68e081d2011-12-20 02:48:34 +00003786void TranslationUnitDecl::anchor() { }
3787
Sebastian Redl833ef452010-01-26 22:01:41 +00003788TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00003789 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003790}
3791
Richard Smithf19e1272015-03-07 00:04:49 +00003792void ExternCContextDecl::anchor() { }
3793
3794ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
3795 TranslationUnitDecl *DC) {
3796 return new (C, DC) ExternCContextDecl(DC);
3797}
3798
David Blaikie68e081d2011-12-20 02:48:34 +00003799void LabelDecl::anchor() { }
3800
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003801LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003802 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00003803 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003804}
3805
3806LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3807 SourceLocation IdentL, IdentifierInfo *II,
3808 SourceLocation GnuLabelL) {
3809 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00003810 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003811}
3812
Douglas Gregor72172e92012-01-05 21:55:30 +00003813LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003814 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3815 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003816}
3817
Ehsan Akhgari31097582014-09-22 02:21:54 +00003818void LabelDecl::setMSAsmLabel(StringRef Name) {
3819 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3820 memcpy(Buffer, Name.data(), Name.size());
3821 Buffer[Name.size()] = '\0';
3822 MSAsmName = Buffer;
3823}
3824
David Blaikie68e081d2011-12-20 02:48:34 +00003825void ValueDecl::anchor() { }
3826
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003827bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00003828 for (const auto *I : attrs())
3829 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003830 return true;
3831
3832 return isWeakImported();
3833}
3834
David Blaikie68e081d2011-12-20 02:48:34 +00003835void ImplicitParamDecl::anchor() { }
3836
Sebastian Redl833ef452010-01-26 22:01:41 +00003837ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003838 SourceLocation IdLoc,
3839 IdentifierInfo *Id,
3840 QualType Type) {
Richard Smith053f6c62014-05-16 23:01:30 +00003841 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003842}
3843
Richard Smithf7981722013-11-22 09:01:48 +00003844ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003845 unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003846 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00003847 QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003848}
3849
Sebastian Redl833ef452010-01-26 22:01:41 +00003850FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003851 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003852 const DeclarationNameInfo &NameInfo,
3853 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003854 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003855 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003856 bool hasWrittenPrototype,
3857 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003858 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00003859 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3860 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003861 New->HasWrittenPrototype = hasWrittenPrototype;
3862 return New;
3863}
3864
Douglas Gregor72172e92012-01-05 21:55:30 +00003865FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003866 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003867 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00003868 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003869}
3870
Sebastian Redl833ef452010-01-26 22:01:41 +00003871BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003872 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003873}
3874
Douglas Gregor72172e92012-01-05 21:55:30 +00003875BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003876 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003877}
3878
Ben Langmuir37943a72013-05-03 19:00:33 +00003879CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3880 unsigned NumParams) {
Richard Smithf7981722013-11-22 09:01:48 +00003881 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3882 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003883}
3884
Ben Langmuirce914fc2013-05-03 19:20:19 +00003885CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00003886 unsigned NumParams) {
3887 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
Craig Topper36250ad2014-05-12 05:36:57 +00003888 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00003889}
3890
Sebastian Redl833ef452010-01-26 22:01:41 +00003891EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3892 SourceLocation L,
3893 IdentifierInfo *Id, QualType T,
3894 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00003895 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00003896}
3897
Douglas Gregor72172e92012-01-05 21:55:30 +00003898EnumConstantDecl *
3899EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003900 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
3901 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00003902}
3903
David Blaikie68e081d2011-12-20 02:48:34 +00003904void IndirectFieldDecl::anchor() { }
3905
Benjamin Kramer39593702010-11-21 14:11:41 +00003906IndirectFieldDecl *
3907IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3908 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3909 unsigned CHS) {
Richard Smithf7981722013-11-22 09:01:48 +00003910 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003911}
3912
Douglas Gregor72172e92012-01-05 21:55:30 +00003913IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3914 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003915 return new (C, ID) IndirectFieldDecl(nullptr, SourceLocation(),
3916 DeclarationName(), QualType(), nullptr,
3917 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003918}
3919
Douglas Gregorbe996932010-09-01 20:41:53 +00003920SourceRange EnumConstantDecl::getSourceRange() const {
3921 SourceLocation End = getLocation();
3922 if (Init)
3923 End = Init->getLocEnd();
3924 return SourceRange(getLocation(), End);
3925}
3926
David Blaikie68e081d2011-12-20 02:48:34 +00003927void TypeDecl::anchor() { }
3928
Sebastian Redl833ef452010-01-26 22:01:41 +00003929TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003930 SourceLocation StartLoc, SourceLocation IdLoc,
3931 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00003932 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003933}
3934
David Blaikie68e081d2011-12-20 02:48:34 +00003935void TypedefNameDecl::anchor() { }
3936
Richard Smitha5230222015-03-27 01:37:43 +00003937TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName() const {
3938 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>())
3939 if (TT->getDecl()->getTypedefNameForAnonDecl() == this)
3940 return TT->getDecl();
3941
3942 return nullptr;
3943}
3944
Douglas Gregor72172e92012-01-05 21:55:30 +00003945TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003946 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003947 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00003948}
3949
Richard Smithdda56e42011-04-15 14:24:37 +00003950TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3951 SourceLocation StartLoc,
3952 SourceLocation IdLoc, IdentifierInfo *Id,
3953 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00003954 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00003955}
3956
Douglas Gregor72172e92012-01-05 21:55:30 +00003957TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003958 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
3959 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00003960}
3961
Abramo Bagnaraea947882011-03-08 16:41:52 +00003962SourceRange TypedefDecl::getSourceRange() const {
3963 SourceLocation RangeEnd = getLocation();
3964 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3965 if (typeIsPostfix(TInfo->getType()))
3966 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3967 }
3968 return SourceRange(getLocStart(), RangeEnd);
3969}
3970
Richard Smithdda56e42011-04-15 14:24:37 +00003971SourceRange TypeAliasDecl::getSourceRange() const {
3972 SourceLocation RangeEnd = getLocStart();
3973 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3974 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3975 return SourceRange(getLocStart(), RangeEnd);
3976}
3977
David Blaikie68e081d2011-12-20 02:48:34 +00003978void FileScopeAsmDecl::anchor() { }
3979
Sebastian Redl833ef452010-01-26 22:01:41 +00003980FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003981 StringLiteral *Str,
3982 SourceLocation AsmLoc,
3983 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003984 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003985}
Douglas Gregorba345522011-12-02 23:23:56 +00003986
Richard Smithf7981722013-11-22 09:01:48 +00003987FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003988 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003989 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
3990 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00003991}
3992
Michael Han84324352013-02-22 17:15:32 +00003993void EmptyDecl::anchor() {}
3994
3995EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003996 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00003997}
3998
3999EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004000 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004001}
4002
Douglas Gregorba345522011-12-02 23:23:56 +00004003//===----------------------------------------------------------------------===//
4004// ImportDecl Implementation
4005//===----------------------------------------------------------------------===//
4006
4007/// \brief Retrieve the number of module identifiers needed to name the given
4008/// module.
4009static unsigned getNumModuleIdentifiers(Module *Mod) {
4010 unsigned Result = 1;
4011 while (Mod->Parent) {
4012 Mod = Mod->Parent;
4013 ++Result;
4014 }
4015 return Result;
4016}
4017
Douglas Gregor22d09742012-01-03 18:04:46 +00004018ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004019 Module *Imported,
4020 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004021 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004022 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004023{
4024 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4025 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
4026 memcpy(StoredLocs, IdentifierLocs.data(),
4027 IdentifierLocs.size() * sizeof(SourceLocation));
4028}
4029
Douglas Gregor22d09742012-01-03 18:04:46 +00004030ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004031 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004032 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004033 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004034{
4035 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
4036}
4037
Richard Smithf7981722013-11-22 09:01:48 +00004038ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004039 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004040 ArrayRef<SourceLocation> IdentifierLocs) {
Richard Smithf7981722013-11-22 09:01:48 +00004041 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
4042 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004043}
4044
Richard Smithf7981722013-11-22 09:01:48 +00004045ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004046 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004047 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004048 SourceLocation EndLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004049 ImportDecl *Import =
4050 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
4051 Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004052 Import->setImplicit();
4053 return Import;
4054}
4055
Douglas Gregor72172e92012-01-05 21:55:30 +00004056ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4057 unsigned NumLocations) {
Richard Smithf7981722013-11-22 09:01:48 +00004058 return new (C, ID, NumLocations * sizeof(SourceLocation))
4059 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004060}
4061
4062ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4063 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004064 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004065
4066 const SourceLocation *StoredLocs
4067 = reinterpret_cast<const SourceLocation *>(this + 1);
Craig Topper5fc8fc22014-08-27 06:28:36 +00004068 return llvm::makeArrayRef(StoredLocs,
4069 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004070}
4071
4072SourceRange ImportDecl::getSourceRange() const {
4073 if (!ImportedAndComplete.getInt())
4074 return SourceRange(getLocation(),
4075 *reinterpret_cast<const SourceLocation *>(this + 1));
4076
4077 return SourceRange(getLocation(), getIdentifierLocs().back());
4078}