blob: a61af50c480e4bcb14068a001c0072a680d71a1c [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000024#include "clang/AST/Stmt.h"
25#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000027#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000028#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000029#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000030#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000031#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Richard Smith0b87e072013-10-07 08:02:11 +000036Decl *clang::getPrimaryMergedDecl(Decl *D) {
37 return D->getASTContext().getPrimaryMergedDecl(D);
38}
39
Chris Lattner88f70d62008-03-15 05:43:15 +000040//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000041// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000042//===----------------------------------------------------------------------===//
43
John McCalldf25c432013-02-16 00:17:33 +000044// Visibility rules aren't rigorously externally specified, but here
45// are the basic principles behind what we implement:
46//
47// 1. An explicit visibility attribute is generally a direct expression
48// of the user's intent and should be honored. Only the innermost
49// visibility attribute applies. If no visibility attribute applies,
50// global visibility settings are considered.
51//
52// 2. There is one caveat to the above: on or in a template pattern,
53// an explicit visibility attribute is just a default rule, and
54// visibility can be decreased by the visibility of template
55// arguments. But this, too, has an exception: an attribute on an
56// explicit specialization or instantiation causes all the visibility
57// restrictions of the template arguments to be ignored.
58//
59// 3. A variable that does not otherwise have explicit visibility can
60// be restricted by the visibility of its type.
61//
62// 4. A visibility restriction is explicit if it comes from an
63// attribute (or something like it), not a global visibility setting.
64// When emitting a reference to an external symbol, visibility
65// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000066//
67// 5. When computing the visibility of a non-type, including a
68// non-type member of a class, only non-type visibility restrictions
69// are considered: the 'visibility' attribute, global value-visibility
70// settings, and a few special cases like __private_extern.
71//
72// 6. When computing the visibility of a type, including a type member
73// of a class, only type visibility restrictions are considered:
74// the 'type_visibility' attribute and global type-visibility settings.
75// However, a 'visibility' attribute counts as a 'type_visibility'
76// attribute on any declaration that only has the former.
77//
78// The visibility of a "secondary" entity, like a template argument,
79// is computed using the kind of that entity, not the kind of the
80// primary entity for which we are computing visibility. For example,
81// the visibility of a specialization of either of these templates:
82// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
83// template <class T, bool (&compare)(T, X)> class matcher;
84// is restricted according to the type visibility of the argument 'T',
85// the type visibility of 'bool(&)(T,X)', and the value visibility of
86// the argument function 'compare'. That 'has_match' is a value
87// and 'matcher' is a type only matters when looking for attributes
88// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +000089
John McCall5f46c482013-02-21 23:42:58 +000090const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +000091const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +000092
John McCalldf25c432013-02-16 00:17:33 +000093/// Kinds of LV computation. The linkage side of the computation is
94/// always the same, but different things can change how visibility is
95/// computed.
96enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +000097 /// Do an LV computation for, ultimately, a type.
98 /// Visibility may be restricted by type visibility settings and
99 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000100 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000101
John McCall5f46c482013-02-21 23:42:58 +0000102 /// Do an LV computation for, ultimately, a non-type declaration.
103 /// Visibility may be restricted by value visibility settings and
104 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000105 LVForValue = NamedDecl::VisibilityForValue,
106
John McCall5f46c482013-02-21 23:42:58 +0000107 /// Do an LV computation for, ultimately, a type that already has
108 /// some sort of explicit visibility. Visibility may only be
109 /// restricted by the visibility of template arguments.
110 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000111
John McCall5f46c482013-02-21 23:42:58 +0000112 /// Do an LV computation for, ultimately, a non-type declaration
113 /// that already has some sort of explicit visibility. Visibility
114 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000115 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
116
117 /// Do an LV computation when we only care about the linkage.
118 LVForLinkageOnly =
119 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000120};
121
John McCalld041a9b2013-02-20 01:54:26 +0000122/// Does this computation kind permit us to consider additional
123/// visibility settings from attributes and the like?
124static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000125 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000126}
127
128/// Given an LVComputationKind, return one of the same type/value sort
129/// that records that it already has explicit visibility.
130static LVComputationKind
131withExplicitVisibilityAlready(LVComputationKind oldKind) {
132 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000133 static_cast<LVComputationKind>(unsigned(oldKind) |
134 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000135 assert(oldKind != LVForType || newKind == LVForExplicitType);
136 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
137 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
138 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
139 return newKind;
140}
141
David Blaikie05785d12013-02-20 22:23:23 +0000142static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
143 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000144 assert(!hasExplicitVisibilityAlready(kind) &&
145 "asking for explicit visibility when we shouldn't be");
146 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
147}
148
John McCalldf25c432013-02-16 00:17:33 +0000149/// Is the given declaration a "type" or a "value" for the purposes of
150/// visibility computation?
151static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000152 return isa<TypeDecl>(D) ||
153 isa<ClassTemplateDecl>(D) ||
154 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000155}
156
John McCall5f46c482013-02-21 23:42:58 +0000157/// Does the given declaration have member specialization information,
158/// and if so, is it an explicit specialization?
159template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000160std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000161isExplicitMemberSpecialization(const T *D) {
162 if (const MemberSpecializationInfo *member =
163 D->getMemberSpecializationInfo()) {
164 return member->isExplicitSpecialization();
165 }
166 return false;
167}
168
169/// For templates, this question is easier: a member template can't be
170/// explicitly instantiated, so there's a single bit indicating whether
171/// or not this is an explicit member specialization.
172static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
173 return D->isMemberSpecialization();
174}
175
John McCalld041a9b2013-02-20 01:54:26 +0000176/// Given a visibility attribute, return the explicit visibility
177/// associated with it.
178template <class T>
179static Visibility getVisibilityFromAttr(const T *attr) {
180 switch (attr->getVisibility()) {
181 case T::Default:
182 return DefaultVisibility;
183 case T::Hidden:
184 return HiddenVisibility;
185 case T::Protected:
186 return ProtectedVisibility;
187 }
188 llvm_unreachable("bad visibility kind");
189}
190
John McCalldf25c432013-02-16 00:17:33 +0000191/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000192static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000193 NamedDecl::ExplicitVisibilityKind kind) {
194 // If we're ultimately computing the visibility of a type, look for
195 // a 'type_visibility' attribute before looking for 'visibility'.
196 if (kind == NamedDecl::VisibilityForType) {
197 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
198 return getVisibilityFromAttr(A);
199 }
200 }
201
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000202 // If this declaration has an explicit visibility attribute, use it.
203 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000204 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000205 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000206
207 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
208 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000209 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000210 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
211 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000212 return DefaultVisibility;
213 }
214
David Blaikie7a30dc52013-02-21 01:47:18 +0000215 return None;
John McCall457a04e2010-10-22 21:05:15 +0000216}
217
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000218static LinkageInfo
219getLVForType(const Type &T, LVComputationKind computation) {
220 if (computation == LVForLinkageOnly)
221 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
222 return T.getLinkageAndVisibility();
223}
224
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000225/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000226/// template parameter list. For visibility purposes, template
227/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000228static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000229getLVForTemplateParameterList(const TemplateParameterList *params,
230 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000231 LinkageInfo LV;
232 for (TemplateParameterList::const_iterator P = params->begin(),
233 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000234 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000235
236 // Template type parameters are the most common and never
237 // contribute to visibility, pack or not.
238 if (isa<TemplateTypeParmDecl>(*P))
239 continue;
240
241 // Non-type template parameters can be restricted by the value type, e.g.
242 // template <enum X> class A { ... };
243 // We have to be careful here, though, because we can be dealing with
244 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000245 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000246 // Handle the non-pack case first.
247 if (!NTTP->isExpandedParameterPack()) {
248 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000249 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000250 }
251 continue;
252 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000253
John McCalldf25c432013-02-16 00:17:33 +0000254 // Look at all the types in an expanded pack.
255 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
256 QualType type = NTTP->getExpansionType(i);
257 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000258 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000259 }
John McCalldf25c432013-02-16 00:17:33 +0000260 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000261 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000262
John McCalldf25c432013-02-16 00:17:33 +0000263 // Template template parameters can be restricted by their
264 // template parameters, recursively.
265 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
266
267 // Handle the non-pack case first.
268 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000269 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
270 computation));
John McCalldf25c432013-02-16 00:17:33 +0000271 continue;
272 }
273
274 // Look at all expansions in an expanded pack.
275 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
276 i != n; ++i) {
277 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000278 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279 }
280 }
281
John McCall457a04e2010-10-22 21:05:15 +0000282 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000283}
284
Rafael Espindola19de5612013-01-12 06:42:30 +0000285/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000286static LinkageInfo getLVForDecl(const NamedDecl *D,
287 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000288
Eli Friedman7e346a82013-07-01 20:22:57 +0000289static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
290 const Decl *Ret = NULL;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000291 const DeclContext *DC = D->getDeclContext();
292 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000293 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
294 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000295 DC = DC->getParent();
296 }
297 return Ret;
298}
299
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300/// \brief Get the most restrictive linkage for the types and
301/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000302///
303/// Note that we don't take an LVComputationKind because we always
304/// want to honor the visibility of template arguments in the same way.
305static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000306getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args,
307 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000308 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000309
John McCalldf25c432013-02-16 00:17:33 +0000310 for (unsigned i = 0, e = args.size(); i != e; ++i) {
311 const TemplateArgument &arg = args[i];
312 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000313 case TemplateArgument::Null:
314 case TemplateArgument::Integral:
315 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000316 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000317
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000318 case TemplateArgument::Type:
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000319 LV.merge(getLVForType(*arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000320 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321
322 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000323 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
324 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000325 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000326 }
327 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000328
329 case TemplateArgument::NullPtr:
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000330 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000331 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000332
333 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000334 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000335 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000336 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000337 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000338 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000339
340 case TemplateArgument::Pack:
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000341 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000342 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000343 }
John McCalldf25c432013-02-16 00:17:33 +0000344 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000345 }
346
John McCall457a04e2010-10-22 21:05:15 +0000347 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000348}
349
Rafael Espindola2f869a32012-01-14 00:30:36 +0000350static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000351getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
352 LVComputationKind computation) {
353 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000354}
355
John McCall5f46c482013-02-21 23:42:58 +0000356static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
357 const FunctionTemplateSpecializationInfo *specInfo) {
358 // Include visibility from the template parameters and arguments
359 // only if this is not an explicit instantiation or specialization
360 // with direct explicit visibility. (Implicit instantiations won't
361 // have a direct attribute.)
362 if (!specInfo->isExplicitInstantiationOrSpecialization())
363 return true;
364
365 return !fn->hasAttr<VisibilityAttr>();
366}
367
John McCalldf25c432013-02-16 00:17:33 +0000368/// Merge in template-related linkage and visibility for the given
369/// function template specialization.
370///
371/// We don't need a computation kind here because we can assume
372/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000373///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000374/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000375static void
376mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000377 const FunctionTemplateSpecializationInfo *specInfo,
378 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000379 bool considerVisibility =
380 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000381
382 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000383 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000384 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000385 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000386 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
387
388 // Merge information from the template arguments.
389 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000390 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000391 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000392}
393
John McCall5f46c482013-02-21 23:42:58 +0000394/// Does the given declaration have a direct visibility attribute
395/// that would match the given rules?
396static bool hasDirectVisibilityAttribute(const NamedDecl *D,
397 LVComputationKind computation) {
398 switch (computation) {
399 case LVForType:
400 case LVForExplicitType:
401 if (D->hasAttr<TypeVisibilityAttr>())
402 return true;
403 // fallthrough
404 case LVForValue:
405 case LVForExplicitValue:
406 if (D->hasAttr<VisibilityAttr>())
407 return true;
408 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000409 case LVForLinkageOnly:
410 return false;
John McCall5f46c482013-02-21 23:42:58 +0000411 }
412 llvm_unreachable("bad visibility computation kind");
413}
414
John McCalld041a9b2013-02-20 01:54:26 +0000415/// Should we consider visibility associated with the template
416/// arguments and parameters of the given class template specialization?
417static bool shouldConsiderTemplateVisibility(
418 const ClassTemplateSpecializationDecl *spec,
419 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000420 // Include visibility from the template parameters and arguments
421 // only if this is not an explicit instantiation or specialization
422 // with direct explicit visibility (and note that implicit
423 // instantiations won't have a direct attribute).
424 //
425 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000426 // for an explicit specialization when computing the visibility of a
427 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000428 //
429 // This is a bit complex; let's unpack it.
430 //
431 // An explicit class specialization is an independent, top-level
432 // declaration. As such, if it or any of its members has an
433 // explicit visibility attribute, that must directly express the
434 // user's intent, and we should honor it. The same logic applies to
435 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000436
437 // Fast path: if this is not an explicit instantiation or
438 // specialization, we always want to consider template-related
439 // visibility restrictions.
440 if (!spec->isExplicitInstantiationOrSpecialization())
441 return true;
442
443 // This is the 'member thereof' check.
444 if (spec->isExplicitSpecialization() &&
445 hasExplicitVisibilityAlready(computation))
446 return false;
447
John McCall5f46c482013-02-21 23:42:58 +0000448 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000449}
450
451/// Merge in template-related linkage and visibility for the given
452/// class template specialization.
453static void mergeTemplateLV(LinkageInfo &LV,
454 const ClassTemplateSpecializationDecl *spec,
455 LVComputationKind computation) {
456 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000457
458 // Merge information from the template parameters, but ignore
459 // visibility if we're only considering template arguments.
460
John McCalld041a9b2013-02-20 01:54:26 +0000461 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000462 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000463 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000464 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000465 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000466
467 // Merge information from the template arguments. We ignore
468 // template-argument visibility if we've got an explicit
469 // instantiation with a visibility attribute.
470 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000471 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000472 if (considerVisibility)
473 LV.mergeVisibility(argsLV);
474 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000475}
476
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000477static bool useInlineVisibilityHidden(const NamedDecl *D) {
478 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000479 const LangOptions &Opts = D->getASTContext().getLangOpts();
480 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000481 return false;
482
483 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
484 if (!FD)
485 return false;
486
487 TemplateSpecializationKind TSK = TSK_Undeclared;
488 if (FunctionTemplateSpecializationInfo *spec
489 = FD->getTemplateSpecializationInfo()) {
490 TSK = spec->getTemplateSpecializationKind();
491 } else if (MemberSpecializationInfo *MSI =
492 FD->getMemberSpecializationInfo()) {
493 TSK = MSI->getTemplateSpecializationKind();
494 }
495
496 const FunctionDecl *Def = 0;
497 // InlineVisibilityHidden only applies to definitions, and
498 // isInlined() only gives meaningful answers on definitions
499 // anyway.
500 return TSK != TSK_ExplicitInstantiationDeclaration &&
501 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000502 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000503}
504
Rafael Espindola593537a2013-05-05 20:15:21 +0000505template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000506 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000507 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000508}
509
Richard Smith03c05032014-02-17 23:34:47 +0000510static bool isSingleLineLanguageLinkage(const Decl &D) {
Rafael Espindola327be3c2013-04-26 01:30:23 +0000511 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000512 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000513 return true;
514 return false;
515}
516
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000517static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000518 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000519 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000520 "Not a name having namespace scope");
521 ASTContext &Context = D->getASTContext();
522
523 // C++ [basic.link]p3:
524 // A name having namespace scope (3.3.6) has internal linkage if it
525 // is the name of
526 // - an object, reference, function or function template that is
527 // explicitly declared static; or,
528 // (This bullet corresponds to C99 6.2.2p3.)
529 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
530 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000531 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000532 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000533
Richard Smithdc0ef452012-10-19 06:37:48 +0000534 // - a non-volatile object or reference that is explicitly declared const
535 // or constexpr and neither explicitly declared extern nor previously
536 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000537 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000538 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000539 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000540 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000541 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000542 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000543
544 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000545 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000546 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000547 return LinkageInfo::internal();
548 }
549
550 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
551 PrevVar = PrevVar->getPreviousDecl()) {
552 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
553 Var->getStorageClass() == SC_None)
554 return PrevVar->getLinkageAndVisibility();
555 // Explicitly declared static.
556 if (PrevVar->getStorageClass() == SC_Static)
557 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000558 }
Alp Tokera2794f92014-01-22 07:29:52 +0000559 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000560 // C++ [temp]p4:
561 // A non-member function template can have internal linkage; any
562 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000563
564 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000565 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000566 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000567 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000568 // - a data member of an anonymous union.
569 assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
570 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000571
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000572 if (D->isInAnonymousNamespace()) {
573 const VarDecl *Var = dyn_cast<VarDecl>(D);
574 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindola593537a2013-05-05 20:15:21 +0000575 if ((!Var || !isFirstInExternCContext(Var)) &&
576 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000577 return LinkageInfo::uniqueExternal();
578 }
John McCallb7139c42010-10-28 04:18:25 +0000579
John McCall457a04e2010-10-22 21:05:15 +0000580 // Set up the defaults.
581
582 // C99 6.2.2p5:
583 // If the declaration of an identifier for an object has file
584 // scope and no storage-class specifier, its linkage is
585 // external.
John McCallc273f242010-10-30 11:50:40 +0000586 LinkageInfo LV;
587
John McCalld041a9b2013-02-20 01:54:26 +0000588 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000589 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000590 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000591 } else {
592 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000593 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000594 for (const DeclContext *DC = D->getDeclContext();
595 !isa<TranslationUnitDecl>(DC);
596 DC = DC->getParent()) {
597 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
598 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000599 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000600 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000601 break;
602 }
603 }
604 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000605
John McCalldf25c432013-02-16 00:17:33 +0000606 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000607 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000608 // Use global type/value visibility as appropriate.
609 Visibility globalVisibility;
610 if (computation == LVForValue) {
611 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
612 } else {
613 assert(computation == LVForType);
614 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
615 }
616 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000617
618 // If we're paying attention to global visibility, apply
619 // -finline-visibility-hidden if this is an inline method.
620 if (useInlineVisibilityHidden(D))
621 LV.mergeVisibility(HiddenVisibility, true);
622 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000623 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000624
Douglas Gregorf73b2822009-11-25 22:24:25 +0000625 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000626
Douglas Gregorf73b2822009-11-25 22:24:25 +0000627 // A name having namespace scope has external linkage if it is the
628 // name of
629 //
630 // - an object or reference, unless it has internal linkage; or
631 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000632 // GCC applies the following optimization to variables and static
633 // data members, but not to functions:
634 //
John McCall457a04e2010-10-22 21:05:15 +0000635 // Modify the variable's LV by the LV of its type unless this is
636 // C or extern "C". This follows from [basic.link]p9:
637 // A type without linkage shall not be used as the type of a
638 // variable or function with external linkage unless
639 // - the entity has C language linkage, or
640 // - the entity is declared within an unnamed namespace, or
641 // - the entity is not used or is defined in the same
642 // translation unit.
643 // and [basic.link]p10:
644 // ...the types specified by all declarations referring to a
645 // given variable or function shall be identical...
646 // C does not have an equivalent rule.
647 //
John McCall5fe84122010-10-26 04:59:26 +0000648 // Ignore this if we've got an explicit attribute; the user
649 // probably knows what they're doing.
650 //
John McCall457a04e2010-10-22 21:05:15 +0000651 // Note that we don't want to make the variable non-external
652 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000653 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000654 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000655 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000656 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000657 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000658 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000659 }
660
John McCall23032652010-11-02 18:38:13 +0000661 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000662 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000663
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000664 // Note that Sema::MergeVarDecl already takes care of implementing
665 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
666 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000667
Douglas Gregorf73b2822009-11-25 22:24:25 +0000668 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000669 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000670 // In theory, we can modify the function's LV by the LV of its
671 // type unless it has C linkage (see comment above about variables
672 // for justification). In practice, GCC doesn't do this, so it's
673 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000674
John McCall23032652010-11-02 18:38:13 +0000675 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000676 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000677
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000678 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
679 // merging storage classes and visibility attributes, so we don't have to
680 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000681
John McCallf768aa72011-02-10 06:50:24 +0000682 // In C++, then if the type of the function uses a type with
683 // unique-external linkage, it's not legally usable from outside
684 // this translation unit. However, we should use the C linkage
685 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000686 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000687 !Function->isInExternCContext()) {
688 // Only look at the type-as-written. If this function has an auto-deduced
689 // return type, we can't compute the linkage of that type because it could
690 // require looking at the linkage of this function, and we don't need this
691 // for correctness because the type is not part of the function's
692 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000693 // FIXME: This is a hack. We should be able to solve this circularity and
694 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000695 QualType TypeAsWritten = Function->getType();
696 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
697 TypeAsWritten = TSI->getType();
698 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
699 return LinkageInfo::uniqueExternal();
700 }
John McCallf768aa72011-02-10 06:50:24 +0000701
John McCall5f46c482013-02-21 23:42:58 +0000702 // Consider LV from the template and the template arguments.
703 // We're at file scope, so we do not need to worry about nested
704 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000705 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000706 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000707 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000708 }
709
Douglas Gregorf73b2822009-11-25 22:24:25 +0000710 // - a named class (Clause 9), or an unnamed class defined in a
711 // typedef declaration in which the class has the typedef name
712 // for linkage purposes (7.1.3); or
713 // - a named enumeration (7.2), or an unnamed enumeration
714 // defined in a typedef declaration in which the enumeration
715 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000716 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
717 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000718 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000719 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000720
John McCall457a04e2010-10-22 21:05:15 +0000721 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000722 // linkage of the template and template arguments. We're at file
723 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000724 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000725 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000726 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000727 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000728
729 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000730 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000731 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000732 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000733 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000734 return LinkageInfo::none();
735 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000736
737 // - a template, unless it is a function template that has
738 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000739 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000740 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000741 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000742 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000743 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
744
Douglas Gregorf73b2822009-11-25 22:24:25 +0000745 // - a namespace (7.3), unless it is declared within an unnamed
746 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000747 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
748 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000749
John McCall457a04e2010-10-22 21:05:15 +0000750 // By extension, we assign external linkage to Objective-C
751 // interfaces.
752 } else if (isa<ObjCInterfaceDecl>(D)) {
753 // fallout
754
755 // Everything not covered here has no linkage.
756 } else {
John McCallc273f242010-10-30 11:50:40 +0000757 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000758 }
759
760 // If we ended up with non-external linkage, visibility should
761 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000762 if (LV.getLinkage() != ExternalLinkage)
763 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000764
John McCall457a04e2010-10-22 21:05:15 +0000765 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000766}
767
John McCalldf25c432013-02-16 00:17:33 +0000768static LinkageInfo getLVForClassMember(const NamedDecl *D,
769 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000770 // Only certain class members have linkage. Note that fields don't
771 // really have linkage, but it's convenient to say they do for the
772 // purposes of calculating linkage of pointer-to-data-member
773 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000774 //
775 // Templates also don't officially have linkage, but since we ignore
776 // the C++ standard and look at template arguments when determining
777 // linkage and visibility of a template specialization, we might hit
778 // a template template argument that way. If we do, we need to
779 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000780 if (!(isa<CXXMethodDecl>(D) ||
781 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000782 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000783 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000784 isa<TagDecl>(D) ||
785 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000786 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000787
John McCall07072662010-11-02 01:45:15 +0000788 LinkageInfo LV;
789
John McCall07072662010-11-02 01:45:15 +0000790 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000791 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000792 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000793 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000794 // If we're paying attention to global visibility, apply
795 // -finline-visibility-hidden if this is an inline method.
796 //
797 // Note that we do this before merging information about
798 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000799 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000800 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000801 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000802
803 // If this class member has an explicit visibility attribute, the only
804 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000805 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000806 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000807 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000808 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000809
John McCall5f46c482013-02-21 23:42:58 +0000810 LinkageInfo classLV =
811 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000812 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000813 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000814 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000815
Rafael Espindolae6190db2013-05-28 02:22:10 +0000816 if (!isExternallyVisible(classLV.getLinkage()))
817 return LinkageInfo::none();
818
819
John McCall5f46c482013-02-21 23:42:58 +0000820 // Otherwise, don't merge in classLV yet, because in certain cases
821 // we need to completely ignore the visibility from it.
822
823 // Specifically, if this decl exists and has an explicit attribute.
824 const NamedDecl *explicitSpecSuppressor = 0;
825
John McCall8823c652010-08-13 08:35:10 +0000826 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000827 // If the type of the function uses a type with unique-external
828 // linkage, it's not legally usable from outside this translation unit.
Faisal Valid2598e92013-10-08 04:15:04 +0000829 // But only look at the type-as-written. If this function has an auto-deduced
830 // return type, we can't compute the linkage of that type because it could
831 // require looking at the linkage of this function, and we don't need this
832 // for correctness because the type is not part of the function's
833 // signature.
834 // FIXME: This is a hack. We should be able to solve this circularity and the
835 // one in getLVForNamespaceScopeDecl for Functions some other way.
836 {
837 QualType TypeAsWritten = MD->getType();
838 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
839 TypeAsWritten = TSI->getType();
840 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
841 return LinkageInfo::uniqueExternal();
842 }
John McCall457a04e2010-10-22 21:05:15 +0000843 // If this is a method template specialization, use the linkage for
844 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000845 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000846 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000847 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000848 if (spec->isExplicitSpecialization()) {
849 explicitSpecSuppressor = MD;
850 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
851 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
852 }
853 } else if (isExplicitMemberSpecialization(MD)) {
854 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000855 }
John McCall457a04e2010-10-22 21:05:15 +0000856
John McCall37bb6c92010-10-29 22:22:43 +0000857 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000858 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000859 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000860 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000861 if (spec->isExplicitSpecialization()) {
862 explicitSpecSuppressor = spec;
863 } else {
864 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
865 if (isExplicitMemberSpecialization(temp)) {
866 explicitSpecSuppressor = temp->getTemplatedDecl();
867 }
868 }
869 } else if (isExplicitMemberSpecialization(RD)) {
870 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000871 }
872
John McCall37bb6c92010-10-29 22:22:43 +0000873 // Static data members.
874 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000875 // Modify the variable's linkage by its type, but ignore the
876 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000877 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000878 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
879 LV.mergeVisibility(typeLV);
880 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000881
882 if (isExplicitMemberSpecialization(VD)) {
883 explicitSpecSuppressor = VD;
884 }
John McCalldf25c432013-02-16 00:17:33 +0000885
886 // Template members.
887 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
888 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000889 (!LV.isVisibilityExplicit() &&
890 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000891 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000892 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000893 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000894 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000895
896 if (const RedeclarableTemplateDecl *redeclTemp =
897 dyn_cast<RedeclarableTemplateDecl>(temp)) {
898 if (isExplicitMemberSpecialization(redeclTemp)) {
899 explicitSpecSuppressor = temp->getTemplatedDecl();
900 }
901 }
John McCall37bb6c92010-10-29 22:22:43 +0000902 }
903
John McCall5f46c482013-02-21 23:42:58 +0000904 // We should never be looking for an attribute directly on a template.
905 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
906
907 // If this member is an explicit member specialization, and it has
908 // an explicit attribute, ignore visibility from the parent.
909 bool considerClassVisibility = true;
910 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000911 // optimization: hasDVA() is true only with explicit visibility.
912 LV.isVisibilityExplicit() &&
913 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000914 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
915 considerClassVisibility = false;
916 }
917
918 // Finally, merge in information from the class.
919 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000920 return LV;
John McCall8823c652010-08-13 08:35:10 +0000921}
922
David Blaikie68e081d2011-12-20 02:48:34 +0000923void NamedDecl::anchor() { }
924
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000925static LinkageInfo computeLVForDecl(const NamedDecl *D,
926 LVComputationKind computation);
927
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000928bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +0000929 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000930 return true;
John McCalld396b972011-02-08 19:01:05 +0000931
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000932 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +0000933 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +0000934}
935
Rafael Espindola3ae00052013-05-13 00:12:11 +0000936Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +0000937 // We don't care about visibility here, so ask for the cheapest
938 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000939 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +0000940}
941
John McCallc273f242010-10-30 11:50:40 +0000942LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000943 LVComputationKind computation =
944 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000945 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +0000946}
Ted Kremenek926d8602010-04-20 23:15:35 +0000947
Rafael Espindola9ad61122013-11-26 16:09:08 +0000948static Optional<Visibility>
949getExplicitVisibilityAux(const NamedDecl *ND,
950 NamedDecl::ExplicitVisibilityKind kind,
951 bool IsMostRecent) {
952 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
953
Rafael Espindola3a52c442013-02-26 19:33:14 +0000954 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000955 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +0000956 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000957
Rafael Espindola3a52c442013-02-26 19:33:14 +0000958 // If this is a member class of a specialization of a class template
959 // and the corresponding decl has explicit visibility, use that.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000960 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +0000961 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
962 if (InstantiatedFrom)
963 return getVisibilityOf(InstantiatedFrom, kind);
964 }
965
966 // If there wasn't explicit visibility there, and this is a
967 // specialization of a class template, check for visibility
968 // on the pattern.
969 if (const ClassTemplateSpecializationDecl *spec
Rafael Espindola9ad61122013-11-26 16:09:08 +0000970 = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +0000971 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
972 kind);
973
974 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +0000975 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +0000976 const NamedDecl *MostRecent = ND->getMostRecentDecl();
977 if (MostRecent != ND)
978 return getExplicitVisibilityAux(MostRecent, kind, true);
979 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000980
Rafael Espindola9ad61122013-11-26 16:09:08 +0000981 if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +0000982 if (Var->isStaticDataMember()) {
983 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
984 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000985 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000986 }
987
David Blaikie7a30dc52013-02-21 01:47:18 +0000988 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +0000989 }
Rafael Espindola3a52c442013-02-26 19:33:14 +0000990 // Also handle function template specializations.
Rafael Espindola9ad61122013-11-26 16:09:08 +0000991 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000992 // If the function is a specialization of a template with an
993 // explicit visibility attribute, use that.
994 if (FunctionTemplateSpecializationInfo *templateInfo
995 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +0000996 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
997 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000998
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000999 // If the function is a member of a specialization of a class template
1000 // and the corresponding decl has explicit visibility, use that.
1001 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1002 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001003 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001004
David Blaikie7a30dc52013-02-21 01:47:18 +00001005 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001006 }
1007
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001008 // The visibility of a template is stored in the templated decl.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001009 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001010 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001011
David Blaikie7a30dc52013-02-21 01:47:18 +00001012 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001013}
1014
Rafael Espindola9ad61122013-11-26 16:09:08 +00001015Optional<Visibility>
1016NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1017 return getExplicitVisibilityAux(this, kind, false);
1018}
1019
Eli Friedman7e346a82013-07-01 20:22:57 +00001020static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1021 LVComputationKind computation) {
1022 // This lambda has its linkage/visibility determined by its owner.
1023 if (ContextDecl) {
1024 if (isa<ParmVarDecl>(ContextDecl))
1025 DC = ContextDecl->getDeclContext()->getRedeclContext();
1026 else
1027 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1028 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001029
Eli Friedman7e346a82013-07-01 20:22:57 +00001030 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1031 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001032
Eli Friedman7e346a82013-07-01 20:22:57 +00001033 return LinkageInfo::external();
1034}
1035
John McCalldf25c432013-02-16 00:17:33 +00001036static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1037 LVComputationKind computation) {
1038 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1039 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001040 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001041 return LinkageInfo::uniqueExternal();
1042
1043 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001044 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001045 return LinkageInfo::internal();
1046
1047 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001048 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001049 if (Optional<Visibility> Vis =
1050 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001051 LV.mergeVisibility(*Vis, true);
1052 }
1053
1054 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1055 // merging storage classes and visibility attributes, so we don't have to
1056 // look at previous decls in here.
1057
1058 return LV;
1059 }
1060
1061 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001062 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001063 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001064 return LinkageInfo::uniqueExternal();
1065
John McCalldf25c432013-02-16 00:17:33 +00001066 LinkageInfo LV;
1067 if (Var->getStorageClass() == SC_PrivateExtern)
1068 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001069 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001070 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001071 LV.mergeVisibility(*Vis, true);
1072 }
1073
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001074 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1075 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1076 if (PrevLV.getLinkage())
1077 LV.setLinkage(PrevLV.getLinkage());
1078 LV.mergeVisibility(PrevLV);
1079 }
1080
John McCalldf25c432013-02-16 00:17:33 +00001081 return LV;
1082 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001083
1084 if (!Var->isStaticLocal())
1085 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001086 }
1087
Rafael Espindolaa4184182013-06-17 20:04:51 +00001088 ASTContext &Context = D->getASTContext();
1089 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001090 return LinkageInfo::none();
1091
Eli Friedman7e346a82013-07-01 20:22:57 +00001092 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1093 if (!OuterD)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001094 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001095
Eli Friedman7e346a82013-07-01 20:22:57 +00001096 LinkageInfo LV;
1097 if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1098 if (!BD->getBlockManglingNumber())
1099 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001100
Eli Friedman7e346a82013-07-01 20:22:57 +00001101 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1102 BD->getBlockManglingContextDecl(), computation);
1103 } else {
1104 const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1105 if (!FD->isInlined() &&
1106 FD->getTemplateSpecializationKind() == TSK_Undeclared)
1107 return LinkageInfo::none();
1108
1109 LV = getLVForDecl(FD, computation);
1110 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001111 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001112 return LinkageInfo::none();
1113 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1114 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001115}
1116
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001117static inline const CXXRecordDecl*
1118getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1119 const CXXRecordDecl *Ret = Record;
1120 while (Record && Record->isLambda()) {
1121 Ret = Record;
1122 if (!Record->getParent()) break;
1123 // Get the Containing Class of this Lambda Class
1124 Record = dyn_cast_or_null<CXXRecordDecl>(
1125 Record->getParent()->getParent());
1126 }
1127 return Ret;
1128}
1129
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001130static LinkageInfo computeLVForDecl(const NamedDecl *D,
1131 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001132 // Objective-C: treat all Objective-C declarations as having external
1133 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001134 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001135 default:
1136 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001137 case Decl::ParmVar:
1138 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001139 case Decl::TemplateTemplateParm: // count these as external
1140 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001141 case Decl::ObjCAtDefsField:
1142 case Decl::ObjCCategory:
1143 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001144 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001145 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001146 case Decl::ObjCMethod:
1147 case Decl::ObjCProperty:
1148 case Decl::ObjCPropertyImpl:
1149 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001150 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001151
1152 case Decl::CXXRecord: {
1153 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1154 if (Record->isLambda()) {
1155 if (!Record->getLambdaManglingNumber()) {
1156 // This lambda has no mangling number, so it's internal.
1157 return LinkageInfo::internal();
1158 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001159
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001160 // This lambda has its linkage/visibility determined:
1161 // - either by the outermost lambda if that lambda has no mangling
1162 // number.
1163 // - or by the parent of the outer most lambda
1164 // This prevents infinite recursion in settings such as nested lambdas
1165 // used in NSDMI's, for e.g.
1166 // struct L {
1167 // int t{};
1168 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1169 // };
1170 const CXXRecordDecl *OuterMostLambda =
1171 getOutermostEnclosingLambda(Record);
1172 if (!OuterMostLambda->getLambdaManglingNumber())
1173 return LinkageInfo::internal();
1174
1175 return getLVForClosure(
1176 OuterMostLambda->getDeclContext()->getRedeclContext(),
1177 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001178 }
1179
1180 break;
1181 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001182 }
1183
Douglas Gregorf73b2822009-11-25 22:24:25 +00001184 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001185 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001186 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001187
1188 // C++ [basic.link]p5:
1189 // In addition, a member function, static data member, a named
1190 // class or enumeration of class scope, or an unnamed class or
1191 // enumeration defined in a class-scope typedef declaration such
1192 // that the class or enumeration has the typedef name for linkage
1193 // purposes (7.1.3), has external linkage if the name of the class
1194 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001195 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001196 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001197
1198 // C++ [basic.link]p6:
1199 // The name of a function declared in block scope and the name of
1200 // an object declared by a block scope extern declaration have
1201 // linkage. If there is a visible declaration of an entity with
1202 // linkage having the same name and type, ignoring entities
1203 // declared outside the innermost enclosing namespace scope, the
1204 // block scope declaration declares that same entity and receives
1205 // the linkage of the previous declaration. If there is more than
1206 // one such matching entity, the program is ill-formed. Otherwise,
1207 // if no matching entity is found, the block scope entity receives
1208 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001209 if (D->getDeclContext()->isFunctionOrMethod())
1210 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001211
1212 // C++ [basic.link]p6:
1213 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001214 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001215}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001216
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001217namespace clang {
1218class LinkageComputer {
1219public:
1220 static LinkageInfo getLVForDecl(const NamedDecl *D,
1221 LVComputationKind computation) {
1222 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1223 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1224
1225 LinkageInfo LV = computeLVForDecl(D, computation);
1226 if (D->hasCachedLinkage())
1227 assert(D->getCachedLinkage() == LV.getLinkage());
1228
1229 D->setCachedLinkage(LV.getLinkage());
1230
1231#ifndef NDEBUG
1232 // In C (because of gnu inline) and in c++ with microsoft extensions an
1233 // static can follow an extern, so we can have two decls with different
1234 // linkages.
1235 const LangOptions &Opts = D->getASTContext().getLangOpts();
1236 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1237 return LV;
1238
1239 // We have just computed the linkage for this decl. By induction we know
1240 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001241 // computed also does.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001242 NamedDecl *Old = NULL;
Aaron Ballman86c93902014-03-06 23:45:36 +00001243 for (auto I : D->redecls()) {
1244 NamedDecl *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001245 if (T == D)
1246 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001247 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001248 Old = T;
1249 break;
1250 }
1251 }
1252 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1253#endif
1254
1255 return LV;
1256 }
1257};
1258}
1259
1260static LinkageInfo getLVForDecl(const NamedDecl *D,
1261 LVComputationKind computation) {
1262 return clang::LinkageComputer::getLVForDecl(D, computation);
1263}
1264
Douglas Gregor2ada0482009-02-04 17:27:36 +00001265std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001266 std::string QualName;
1267 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001268 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001269 return OS.str();
1270}
1271
1272void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1273 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1274}
1275
1276void NamedDecl::printQualifiedName(raw_ostream &OS,
1277 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001278 const DeclContext *Ctx = getDeclContext();
1279
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001280 if (Ctx->isFunctionOrMethod()) {
1281 printName(OS);
1282 return;
1283 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001284
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001285 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001286 ContextsTy Contexts;
1287
1288 // Collect contexts.
1289 while (Ctx && isa<NamedDecl>(Ctx)) {
1290 Contexts.push_back(Ctx);
1291 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001292 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001293
1294 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1295 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001296 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001297 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001298 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001299 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001300 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1301 TemplateArgs.data(),
1302 TemplateArgs.size(),
1303 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001304 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001305 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001306 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001307 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001308 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001309 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1310 if (!RD->getIdentifier())
1311 OS << "<anonymous " << RD->getKindName() << '>';
1312 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001313 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001314 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001315 const FunctionProtoType *FT = 0;
1316 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001317 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001318
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001319 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001320 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001321 unsigned NumParams = FD->getNumParams();
1322 for (unsigned i = 0; i < NumParams; ++i) {
1323 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001324 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001325 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001326 }
1327
1328 if (FT->isVariadic()) {
1329 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001330 OS << ", ";
1331 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001332 }
1333 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001334 OS << ')';
1335 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001336 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001337 }
1338 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001339 }
1340
John McCalla2a3f7d2010-03-16 21:48:18 +00001341 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001342 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001343 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001344 OS << "<anonymous>";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001345}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001346
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001347void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1348 const PrintingPolicy &Policy,
1349 bool Qualified) const {
1350 if (Qualified)
1351 printQualifiedName(OS, Policy);
1352 else
1353 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001354}
1355
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001356bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001357 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1358
Douglas Gregor889ceb72009-02-03 19:21:40 +00001359 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1360 // We want to keep it, unless it nominates same namespace.
1361 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001362 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1363 ->getOriginalNamespace() ==
1364 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1365 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001368 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1369 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001370 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001371
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001372 // For function templates, the underlying function declarations are linked.
1373 if (const FunctionTemplateDecl *FunctionTemplate
1374 = dyn_cast<FunctionTemplateDecl>(this))
1375 if (const FunctionTemplateDecl *OldFunctionTemplate
1376 = dyn_cast<FunctionTemplateDecl>(OldD))
1377 return FunctionTemplate->getTemplatedDecl()
1378 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001379
Steve Naroffc4173fa2009-02-22 19:35:57 +00001380 // For method declarations, we keep track of redeclarations.
1381 if (isa<ObjCMethodDecl>(this))
1382 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001383
John McCall9f3059a2009-10-09 21:13:30 +00001384 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1385 return true;
1386
John McCall3f746822009-11-17 05:59:44 +00001387 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1388 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1389 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1390
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001391 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1392 ASTContext &Context = getASTContext();
1393 return Context.getCanonicalNestedNameSpecifier(
1394 cast<UsingDecl>(this)->getQualifier()) ==
1395 Context.getCanonicalNestedNameSpecifier(
1396 cast<UsingDecl>(OldD)->getQualifier());
1397 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001398
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001399 if (isa<UnresolvedUsingValueDecl>(this) &&
1400 isa<UnresolvedUsingValueDecl>(OldD)) {
1401 ASTContext &Context = getASTContext();
1402 return Context.getCanonicalNestedNameSpecifier(
1403 cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1404 Context.getCanonicalNestedNameSpecifier(
1405 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1406 }
1407
Douglas Gregorb59643b2012-01-03 23:26:26 +00001408 // A typedef of an Objective-C class type can replace an Objective-C class
1409 // declaration or definition, and vice versa.
1410 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1411 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1412 return true;
1413
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001414 // For non-function declarations, if the declarations are of the
1415 // same kind then this must be a redeclaration, or semantic analysis
1416 // would not have given us the new declaration.
1417 return this->getKind() == OldD->getKind();
1418}
1419
Douglas Gregoreddf4332009-02-24 20:03:32 +00001420bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001421 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001422}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001423
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001424NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001425 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001426 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1427 ND = UD->getTargetDecl();
1428
1429 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1430 return AD->getClassInterface();
1431
1432 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001433}
1434
John McCalla8ae2222010-04-06 21:38:20 +00001435bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001436 if (!isCXXClassMember())
1437 return false;
1438
John McCalla8ae2222010-04-06 21:38:20 +00001439 const NamedDecl *D = this;
1440 if (isa<UsingShadowDecl>(D))
1441 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1442
John McCall5e77d762013-04-16 07:28:30 +00001443 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001444 return true;
Alp Tokera2794f92014-01-22 07:29:52 +00001445 if (const CXXMethodDecl *MD =
1446 dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1447 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001448 return false;
1449}
1450
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001451//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001452// DeclaratorDecl Implementation
1453//===----------------------------------------------------------------------===//
1454
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001455template <typename DeclT>
1456static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1457 if (decl->getNumTemplateParameterLists() > 0)
1458 return decl->getTemplateParameterList(0)->getTemplateLoc();
1459 else
1460 return decl->getInnerLocStart();
1461}
1462
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001463SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001464 TypeSourceInfo *TSI = getTypeSourceInfo();
1465 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001466 return SourceLocation();
1467}
1468
Douglas Gregor14454802011-02-25 02:25:35 +00001469void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1470 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001471 // Make sure the extended decl info is allocated.
1472 if (!hasExtInfo()) {
1473 // Save (non-extended) type source info pointer.
1474 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1475 // Allocate external info struct.
1476 DeclInfo = new (getASTContext()) ExtInfo;
1477 // Restore savedTInfo into (extended) decl info.
1478 getExtInfo()->TInfo = savedTInfo;
1479 }
1480 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001481 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001482 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001483 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001484 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001485 if (getExtInfo()->NumTemplParamLists == 0) {
1486 // Save type source info pointer.
1487 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1488 // Deallocate the extended decl info.
1489 getASTContext().Deallocate(getExtInfo());
1490 // Restore savedTInfo into (non-extended) decl info.
1491 DeclInfo = savedTInfo;
1492 }
1493 else
1494 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001495 }
1496 }
1497}
1498
Abramo Bagnara60804e12011-03-18 15:16:37 +00001499void
1500DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1501 unsigned NumTPLists,
1502 TemplateParameterList **TPLists) {
1503 assert(NumTPLists > 0);
1504 // Make sure the extended decl info is allocated.
1505 if (!hasExtInfo()) {
1506 // Save (non-extended) type source info pointer.
1507 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1508 // Allocate external info struct.
1509 DeclInfo = new (getASTContext()) ExtInfo;
1510 // Restore savedTInfo into (extended) decl info.
1511 getExtInfo()->TInfo = savedTInfo;
1512 }
1513 // Set the template parameter lists info.
1514 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1515}
1516
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001517SourceLocation DeclaratorDecl::getOuterLocStart() const {
1518 return getTemplateOrInnerLocStart(this);
1519}
1520
Abramo Bagnaraea947882011-03-08 16:41:52 +00001521namespace {
1522
1523// Helper function: returns true if QT is or contains a type
1524// having a postfix component.
1525bool typeIsPostfix(clang::QualType QT) {
1526 while (true) {
1527 const Type* T = QT.getTypePtr();
1528 switch (T->getTypeClass()) {
1529 default:
1530 return false;
1531 case Type::Pointer:
1532 QT = cast<PointerType>(T)->getPointeeType();
1533 break;
1534 case Type::BlockPointer:
1535 QT = cast<BlockPointerType>(T)->getPointeeType();
1536 break;
1537 case Type::MemberPointer:
1538 QT = cast<MemberPointerType>(T)->getPointeeType();
1539 break;
1540 case Type::LValueReference:
1541 case Type::RValueReference:
1542 QT = cast<ReferenceType>(T)->getPointeeType();
1543 break;
1544 case Type::PackExpansion:
1545 QT = cast<PackExpansionType>(T)->getPattern();
1546 break;
1547 case Type::Paren:
1548 case Type::ConstantArray:
1549 case Type::DependentSizedArray:
1550 case Type::IncompleteArray:
1551 case Type::VariableArray:
1552 case Type::FunctionProto:
1553 case Type::FunctionNoProto:
1554 return true;
1555 }
1556 }
1557}
1558
1559} // namespace
1560
1561SourceRange DeclaratorDecl::getSourceRange() const {
1562 SourceLocation RangeEnd = getLocation();
1563 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001564 // If the declaration has no name or the type extends past the name take the
1565 // end location of the type.
1566 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001567 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1568 }
1569 return SourceRange(getOuterLocStart(), RangeEnd);
1570}
1571
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001572void
Douglas Gregor20527e22010-06-15 17:44:38 +00001573QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1574 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001575 TemplateParameterList **TPLists) {
1576 assert((NumTPLists == 0 || TPLists != 0) &&
1577 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001578
1579 // Free previous template parameters (if any).
1580 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001581 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001582 TemplParamLists = 0;
1583 NumTemplParamLists = 0;
1584 }
1585 // Set info on matched template parameter lists (if any).
1586 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001587 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001588 NumTemplParamLists = NumTPLists;
1589 for (unsigned i = NumTPLists; i-- > 0; )
1590 TemplParamLists[i] = TPLists[i];
1591 }
1592}
1593
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001594//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001595// VarDecl Implementation
1596//===----------------------------------------------------------------------===//
1597
Sebastian Redl833ef452010-01-26 22:01:41 +00001598const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1599 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001600 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001601 case SC_Auto: return "auto";
1602 case SC_Extern: return "extern";
1603 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1604 case SC_PrivateExtern: return "__private_extern__";
1605 case SC_Register: return "register";
1606 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001607 }
1608
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001609 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001610}
1611
Larisse Voufo39a1e502013-08-06 01:03:05 +00001612VarDecl::VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1613 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1614 TypeSourceInfo *TInfo, StorageClass SC)
1615 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001616 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1617 "VarDeclBitfields too large!");
1618 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1619 "ParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001620 AllBits = 0;
1621 VarDeclBits.SClass = SC;
1622 // Everything else is implicitly initialized to false.
1623}
1624
Abramo Bagnaradff19302011-03-08 08:55:46 +00001625VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1626 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001627 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001628 StorageClass S) {
Richard Smithf7981722013-11-22 09:01:48 +00001629 return new (C, DC) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001630}
1631
Douglas Gregor72172e92012-01-05 21:55:30 +00001632VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00001633 return new (C, ID) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1634 QualType(), 0, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001635}
1636
Douglas Gregorbf62d642010-12-06 18:36:25 +00001637void VarDecl::setStorageClass(StorageClass SC) {
1638 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001639 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001640}
1641
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001642SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001643 if (const Expr *Init = getInit()) {
1644 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001645 // If Init is implicit, ignore its source range and fallback on
1646 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1647 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001648 return SourceRange(getOuterLocStart(), InitEnd);
1649 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001650 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001651}
1652
Rafael Espindola88510672013-01-04 21:18:45 +00001653template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001654static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001655 // C++ [dcl.link]p1: All function types, function names with external linkage,
1656 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001657 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001658 return NoLanguageLinkage;
1659
1660 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001661 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001662 ASTContext &Context = D.getASTContext();
1663 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001664 return CLanguageLinkage;
1665
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001666 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1667 // language linkage of the names of class members and the function type of
1668 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001669 const DeclContext *DC = D.getDeclContext();
1670 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001671 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001672
1673 // If the first decl is in an extern "C" context, any other redeclaration
1674 // will have C language linkage. If the first one is not in an extern "C"
1675 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001676 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001677 return CLanguageLinkage;
1678 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001679}
1680
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001681template<typename T>
1682static bool isExternCTemplate(const T &D) {
1683 // Since the context is ignored for class members, they can only have C++
1684 // language linkage or no language linkage.
1685 const DeclContext *DC = D.getDeclContext();
1686 if (DC->isRecord()) {
1687 assert(D.getASTContext().getLangOpts().CPlusPlus);
1688 return false;
1689 }
1690
1691 return D.getLanguageLinkage() == CLanguageLinkage;
1692}
1693
Rafael Espindolaf4187652013-02-14 01:18:37 +00001694LanguageLinkage VarDecl::getLanguageLinkage() const {
1695 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001696}
1697
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001698bool VarDecl::isExternC() const {
1699 return isExternCTemplate(*this);
1700}
1701
Rafael Espindola593537a2013-05-05 20:15:21 +00001702bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001703 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001704}
1705
1706bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001707 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001708}
1709
Rafael Espindola8db352d2013-10-17 15:37:26 +00001710VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001711
Daniel Dunbar9d355812012-03-09 01:51:51 +00001712VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1713 ASTContext &C) const
1714{
Sebastian Redl35351a92010-01-31 22:27:38 +00001715 // C++ [basic.def]p2:
1716 // A declaration is a definition unless [...] it contains the 'extern'
1717 // specifier or a linkage-specification and neither an initializer [...],
1718 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001719 // C++1y [temp.expl.spec]p15:
1720 // An explicit specialization of a static data member or an explicit
1721 // specialization of a static data member template is a definition if the
1722 // declaration includes an initializer; otherwise, it is a declaration.
1723 //
1724 // FIXME: How do you declare (but not define) a partial specialization of
1725 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001726 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001727 if (isOutOfLine() &&
1728 (hasInit() ||
1729 // If the first declaration is out-of-line, this may be an
1730 // instantiation of an out-of-line partial specialization of a variable
1731 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001732 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001733 ? getTemplateSpecializationKind() == TSK_Undeclared
1734 : getTemplateSpecializationKind() !=
1735 TSK_ExplicitSpecialization) ||
1736 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001737 return Definition;
1738 else
1739 return DeclarationOnly;
1740 }
1741 // C99 6.7p5:
1742 // A definition of an identifier is a declaration for that identifier that
1743 // [...] causes storage to be reserved for that object.
1744 // Note: that applies for all non-file-scope objects.
1745 // C99 6.9.2p1:
1746 // If the declaration of an identifier for an object has file scope and an
1747 // initializer, the declaration is an external definition for the identifier
1748 if (hasInit())
1749 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001750
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001751 if (hasAttr<AliasAttr>())
1752 return Definition;
1753
Richard Smith8809a0c2013-09-27 20:14:12 +00001754 // A variable template specialization (other than a static data member
1755 // template or an explicit specialization) is a declaration until we
1756 // instantiate its initializer.
1757 if (isa<VarTemplateSpecializationDecl>(this) &&
1758 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1759 return DeclarationOnly;
1760
Sebastian Redl35351a92010-01-31 22:27:38 +00001761 if (hasExternalStorage())
1762 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001763
Rafael Espindolabff59562013-04-25 12:11:36 +00001764 // [dcl.link] p7:
1765 // A declaration directly contained in a linkage-specification is treated
1766 // as if it contains the extern specifier for the purpose of determining
1767 // the linkage of the declared name and whether it is a definition.
Richard Smith03c05032014-02-17 23:34:47 +00001768 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001769 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001770
Sebastian Redl35351a92010-01-31 22:27:38 +00001771 // C99 6.9.2p2:
1772 // A declaration of an object that has file scope without an initializer,
1773 // and without a storage class specifier or the scs 'static', constitutes
1774 // a tentative definition.
1775 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001776 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001777 return TentativeDefinition;
1778
1779 // What's left is (in C, block-scope) declarations without initializers or
1780 // external storage. These are definitions.
1781 return Definition;
1782}
1783
Sebastian Redl35351a92010-01-31 22:27:38 +00001784VarDecl *VarDecl::getActingDefinition() {
1785 DefinitionKind Kind = isThisDeclarationADefinition();
1786 if (Kind != TentativeDefinition)
1787 return 0;
1788
Chris Lattner48eb14d2010-06-14 18:31:46 +00001789 VarDecl *LastTentative = 0;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001790 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001791 for (auto I : First->redecls()) {
1792 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001793 if (Kind == Definition)
1794 return 0;
1795 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001796 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001797 }
1798 return LastTentative;
1799}
1800
Daniel Dunbar9d355812012-03-09 01:51:51 +00001801VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00001802 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001803 for (auto I : First->redecls()) {
1804 if (I->isThisDeclarationADefinition(C) == Definition)
1805 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00001806 }
1807 return 0;
1808}
1809
Daniel Dunbar9d355812012-03-09 01:51:51 +00001810VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001811 DefinitionKind Kind = DeclarationOnly;
1812
Rafael Espindola8db352d2013-10-17 15:37:26 +00001813 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001814 for (auto I : First->redecls()) {
1815 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001816 if (Kind == Definition)
1817 break;
1818 }
John McCall37bb6c92010-10-29 22:22:43 +00001819
1820 return Kind;
1821}
1822
Sebastian Redl5ca79842010-02-01 20:16:42 +00001823const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00001824 for (auto I : redecls()) {
1825 if (auto Expr = I->getInit()) {
1826 D = I;
1827 return Expr;
1828 }
Sebastian Redl833ef452010-01-26 22:01:41 +00001829 }
1830 return 0;
1831}
1832
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001833bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001834 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001835 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001836
1837 if (!isStaticDataMember())
1838 return false;
1839
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001840 // If this static data member was instantiated from a static data member of
1841 // a class template, check whether that static data member was defined
1842 // out-of-line.
1843 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1844 return VD->isOutOfLine();
1845
1846 return false;
1847}
1848
Douglas Gregor1d957a32009-10-27 18:42:08 +00001849VarDecl *VarDecl::getOutOfLineDefinition() {
1850 if (!isStaticDataMember())
1851 return 0;
1852
Aaron Ballman86c93902014-03-06 23:45:36 +00001853 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00001854 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00001855 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00001856 }
1857
1858 return 0;
1859}
1860
Douglas Gregord5058122010-02-11 01:19:42 +00001861void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001862 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1863 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001864 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001865 }
1866
1867 Init = I;
1868}
1869
Daniel Dunbar9d355812012-03-09 01:51:51 +00001870bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001871 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001872
Richard Smith35ecb362012-03-02 04:14:40 +00001873 if (!Lang.CPlusPlus)
1874 return false;
1875
1876 // In C++11, any variable of reference type can be used in a constant
1877 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001878 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001879 return true;
1880
1881 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001882 // not require the variable to be non-volatile, but we consider this to be a
1883 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001884 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001885 return false;
1886
1887 // In C++, const, non-volatile variables of integral or enumeration types
1888 // can be used in constant expressions.
1889 if (getType()->isIntegralOrEnumerationType())
1890 return true;
1891
Richard Smith35ecb362012-03-02 04:14:40 +00001892 // Additionally, in C++11, non-volatile constexpr variables can be used in
1893 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001894 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001895}
1896
Richard Smithd0b4dd62011-12-19 06:19:21 +00001897/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1898/// form, which contains extra information on the evaluated value of the
1899/// initializer.
1900EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1901 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1902 if (!Eval) {
1903 Stmt *S = Init.get<Stmt *>();
Manuel Klimeka7328992013-06-03 13:51:33 +00001904 // Note: EvaluatedStmt contains an APValue, which usually holds
1905 // resources not allocated from the ASTContext. We need to do some
1906 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
1907 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00001908 Eval = new (getASTContext()) EvaluatedStmt;
1909 Eval->Value = S;
1910 Init = Eval;
1911 }
1912 return Eval;
1913}
1914
Richard Smithdafff942012-01-14 04:30:29 +00001915APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001916 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001917 return evaluateValue(Notes);
1918}
1919
Manuel Klimeka7328992013-06-03 13:51:33 +00001920namespace {
1921// Destroy an APValue that was allocated in an ASTContext.
1922void DestroyAPValue(void* UntypedValue) {
1923 static_cast<APValue*>(UntypedValue)->~APValue();
1924}
1925} // namespace
1926
Richard Smithdafff942012-01-14 04:30:29 +00001927APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001928 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001929 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1930
1931 // We only produce notes indicating why an initializer is non-constant the
1932 // first time it is evaluated. FIXME: The notes won't always be emitted the
1933 // first time we try evaluation, so might not be produced at all.
1934 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001935 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001936
1937 const Expr *Init = cast<Expr>(Eval->Value);
1938 assert(!Init->isValueDependent());
1939
1940 if (Eval->IsEvaluating) {
1941 // FIXME: Produce a diagnostic for self-initialization.
1942 Eval->CheckedICE = true;
1943 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001944 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001945 }
1946
1947 Eval->IsEvaluating = true;
1948
1949 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1950 this, Notes);
1951
Manuel Klimeka7328992013-06-03 13:51:33 +00001952 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
1953 // or that it's empty (so that there's nothing to clean up) if evaluation
1954 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00001955 if (!Result)
1956 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00001957 else if (Eval->Evaluated.needsCleanup())
1958 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001959
1960 Eval->IsEvaluating = false;
1961 Eval->WasEvaluated = true;
1962
1963 // In C++11, we have determined whether the initializer was a constant
1964 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001965 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001966 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001967 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001968 }
1969
Richard Smithdafff942012-01-14 04:30:29 +00001970 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001971}
1972
1973bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001974 // Initializers of weak variables are never ICEs.
1975 if (isWeak())
1976 return false;
1977
Richard Smithd0b4dd62011-12-19 06:19:21 +00001978 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1979 if (Eval->CheckedICE)
1980 // We have already checked whether this subexpression is an
1981 // integral constant expression.
1982 return Eval->IsICE;
1983
1984 const Expr *Init = cast<Expr>(Eval->Value);
1985 assert(!Init->isValueDependent());
1986
1987 // In C++11, evaluate the initializer to check whether it's a constant
1988 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001989 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001990 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001991 evaluateValue(Notes);
1992 return Eval->IsICE;
1993 }
1994
1995 // It's an ICE whether or not the definition we found is
1996 // out-of-line. See DR 721 and the discussion in Clang PR
1997 // 6206 for details.
1998
1999 if (Eval->CheckingICE)
2000 return false;
2001 Eval->CheckingICE = true;
2002
2003 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2004 Eval->CheckingICE = false;
2005 Eval->CheckedICE = true;
2006 return Eval->IsICE;
2007}
2008
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002009VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002010 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002011 return cast<VarDecl>(MSI->getInstantiatedFrom());
2012
2013 return 0;
2014}
2015
Douglas Gregor3c74d412009-10-14 20:14:33 +00002016TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002017 if (const VarTemplateSpecializationDecl *Spec =
2018 dyn_cast<VarTemplateSpecializationDecl>(this))
2019 return Spec->getSpecializationKind();
2020
Sebastian Redl35351a92010-01-31 22:27:38 +00002021 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002022 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002023
Douglas Gregor86d142a2009-10-08 07:24:58 +00002024 return TSK_Undeclared;
2025}
2026
Richard Smith8809a0c2013-09-27 20:14:12 +00002027SourceLocation VarDecl::getPointOfInstantiation() const {
2028 if (const VarTemplateSpecializationDecl *Spec =
2029 dyn_cast<VarTemplateSpecializationDecl>(this))
2030 return Spec->getPointOfInstantiation();
2031
2032 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2033 return MSI->getPointOfInstantiation();
2034
2035 return SourceLocation();
2036}
2037
Larisse Voufo39a1e502013-08-06 01:03:05 +00002038VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2039 return getASTContext().getTemplateOrSpecializationInfo(this)
2040 .dyn_cast<VarTemplateDecl *>();
2041}
2042
2043void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2044 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2045}
2046
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002047MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002048 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002049 // FIXME: Remove ?
2050 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2051 return getASTContext().getTemplateOrSpecializationInfo(this)
2052 .dyn_cast<MemberSpecializationInfo *>();
Richard Smithb71782b2013-08-01 04:12:04 +00002053 return 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002054}
2055
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002056void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2057 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002058 assert((isa<VarTemplateSpecializationDecl>(this) ||
2059 getMemberSpecializationInfo()) &&
2060 "not a variable or static data member template specialization");
2061
Larisse Voufo39a1e502013-08-06 01:03:05 +00002062 if (VarTemplateSpecializationDecl *Spec =
2063 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2064 Spec->setSpecializationKind(TSK);
2065 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2066 Spec->getPointOfInstantiation().isInvalid())
2067 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002068 }
2069
2070 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2071 MSI->setTemplateSpecializationKind(TSK);
2072 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2073 MSI->getPointOfInstantiation().isInvalid())
2074 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002075 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002076}
2077
2078void
2079VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2080 TemplateSpecializationKind TSK) {
2081 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2082 "Previous template or instantiation?");
2083 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002084}
2085
Sebastian Redl833ef452010-01-26 22:01:41 +00002086//===----------------------------------------------------------------------===//
2087// ParmVarDecl Implementation
2088//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002089
Sebastian Redl833ef452010-01-26 22:01:41 +00002090ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002091 SourceLocation StartLoc,
2092 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002093 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002094 StorageClass S, Expr *DefArg) {
Richard Smithf7981722013-11-22 09:01:48 +00002095 return new (C, DC) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
2096 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002097}
2098
Reid Kleckner8a365022013-06-24 17:51:48 +00002099QualType ParmVarDecl::getOriginalType() const {
2100 TypeSourceInfo *TSI = getTypeSourceInfo();
2101 QualType T = TSI ? TSI->getType() : getType();
2102 if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2103 return DT->getOriginalType();
2104 return T;
2105}
2106
Douglas Gregor72172e92012-01-05 21:55:30 +00002107ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00002108 return new (C, ID) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
2109 0, QualType(), 0, SC_None, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00002110}
2111
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002112SourceRange ParmVarDecl::getSourceRange() const {
2113 if (!hasInheritedDefaultArg()) {
2114 SourceRange ArgRange = getDefaultArgRange();
2115 if (ArgRange.isValid())
2116 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2117 }
2118
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002119 // DeclaratorDecl considers the range of postfix types as overlapping with the
2120 // declaration name, but this is not the case with parameters in ObjC methods.
2121 if (isa<ObjCMethodDecl>(getDeclContext()))
2122 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2123
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002124 return DeclaratorDecl::getSourceRange();
2125}
2126
Sebastian Redl833ef452010-01-26 22:01:41 +00002127Expr *ParmVarDecl::getDefaultArg() {
2128 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2129 assert(!hasUninstantiatedDefaultArg() &&
2130 "Default argument is not yet instantiated!");
2131
2132 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00002133 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002134 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002135
Sebastian Redl833ef452010-01-26 22:01:41 +00002136 return Arg;
2137}
2138
Sebastian Redl833ef452010-01-26 22:01:41 +00002139SourceRange ParmVarDecl::getDefaultArgRange() const {
2140 if (const Expr *E = getInit())
2141 return E->getSourceRange();
2142
2143 if (hasUninstantiatedDefaultArg())
2144 return getUninstantiatedDefaultArg()->getSourceRange();
2145
2146 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002147}
2148
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002149bool ParmVarDecl::isParameterPack() const {
2150 return isa<PackExpansionType>(getType());
2151}
2152
Ted Kremenek540017e2011-10-06 05:00:56 +00002153void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2154 getASTContext().setParameterIndex(this, parameterIndex);
2155 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2156}
2157
2158unsigned ParmVarDecl::getParameterIndexLarge() const {
2159 return getASTContext().getParameterIndex(this);
2160}
2161
Nuno Lopes394ec982008-12-17 23:39:55 +00002162//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002163// FunctionDecl Implementation
2164//===----------------------------------------------------------------------===//
2165
Benjamin Kramer9170e912013-02-22 15:46:01 +00002166void FunctionDecl::getNameForDiagnostic(
2167 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2168 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002169 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2170 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002171 TemplateSpecializationType::PrintTemplateArgumentList(
2172 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002173}
2174
Ted Kremenek186a0742010-04-29 16:49:01 +00002175bool FunctionDecl::isVariadic() const {
2176 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2177 return FT->isVariadic();
2178 return false;
2179}
2180
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002181bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002182 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002183 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002184 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002185 return true;
2186 }
2187 }
2188
2189 return false;
2190}
2191
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002192bool FunctionDecl::hasTrivialBody() const
2193{
2194 Stmt *S = getBody();
2195 if (!S) {
2196 // Since we don't have a body for this function, we don't know if it's
2197 // trivial or not.
2198 return false;
2199 }
2200
2201 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2202 return true;
2203 return false;
2204}
2205
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002206bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002207 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002208 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2209 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002210 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002211 return true;
2212 }
2213 }
2214
2215 return false;
2216}
2217
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002218Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002219 if (!hasBody(Definition))
2220 return 0;
2221
2222 if (Definition->Body)
2223 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002224
2225 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002226}
2227
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002228void FunctionDecl::setBody(Stmt *B) {
2229 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002230 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002231 EndRangeLoc = B->getLocEnd();
2232}
2233
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002234void FunctionDecl::setPure(bool P) {
2235 IsPure = P;
2236 if (P)
2237 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2238 Parent->markedVirtualFunctionPure();
2239}
2240
Richard Smith8d0dc312013-07-21 23:12:18 +00002241template<std::size_t Len>
2242static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2243 IdentifierInfo *II = ND->getIdentifier();
2244 return II && II->isStr(Str);
2245}
2246
Douglas Gregor16618f22009-09-12 00:17:51 +00002247bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002248 const TranslationUnitDecl *tunit =
2249 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2250 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002251 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002252 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002253}
2254
David Majnemerc729b0b2013-09-16 22:44:20 +00002255bool FunctionDecl::isMSVCRTEntryPoint() const {
2256 const TranslationUnitDecl *TUnit =
2257 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2258 if (!TUnit)
2259 return false;
2260
2261 // Even though we aren't really targeting MSVCRT if we are freestanding,
2262 // semantic analysis for these functions remains the same.
2263
2264 // MSVCRT entry points only exist on MSVCRT targets.
2265 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2266 return false;
2267
2268 // Nameless functions like constructors cannot be entry points.
2269 if (!getIdentifier())
2270 return false;
2271
2272 return llvm::StringSwitch<bool>(getName())
2273 .Cases("main", // an ANSI console app
2274 "wmain", // a Unicode console App
2275 "WinMain", // an ANSI GUI app
2276 "wWinMain", // a Unicode GUI app
2277 "DllMain", // a DLL
2278 true)
2279 .Default(false);
2280}
2281
John McCall53ffd372011-05-15 17:49:20 +00002282bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2283 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2284 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2285 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2286 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2287 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2288
Richard Smithf6004412014-01-19 23:25:37 +00002289 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2290 return false;
John McCall53ffd372011-05-15 17:49:20 +00002291
2292 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002293 if (proto->getNumParams() != 2 || proto->isVariadic())
2294 return false;
John McCall53ffd372011-05-15 17:49:20 +00002295
2296 ASTContext &Context =
2297 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2298 ->getASTContext();
2299
2300 // The result type and first argument type are constant across all
2301 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002302 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002303}
2304
Richard Smith8d0dc312013-07-21 23:12:18 +00002305static bool isNamespaceStd(const DeclContext *DC) {
2306 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC->getRedeclContext());
2307 return ND && isNamed(ND, "std") &&
2308 ND->getParent()->getRedeclContext()->isTranslationUnit();
2309}
2310
2311bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2312 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2313 return false;
2314 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2315 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2316 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2317 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2318 return false;
2319
2320 if (isa<CXXRecordDecl>(getDeclContext()))
2321 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002322
2323 // This can only fail for an invalid 'operator new' declaration.
2324 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2325 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002326
2327 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002328 if (FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002329 return false;
2330
2331 // If this is a single-parameter function, it must be a replaceable global
2332 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002333 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002334 return true;
2335
2336 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002337 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002338 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002339 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002340 if (Ctx.getLangOpts().SizedDeallocation &&
2341 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002342 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002343 if (!Ty->isReferenceType())
2344 return false;
2345 Ty = Ty->getPointeeType();
2346 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2347 return false;
2348 // FIXME: Recognise nothrow_t in an inline namespace inside std?
2349 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2350 return RD && isNamed(RD, "nothrow_t") && isNamespaceStd(RD->getDeclContext());
2351}
2352
Richard Smithb47c36f2013-11-05 09:12:18 +00002353FunctionDecl *
2354FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2355 ASTContext &Ctx = getASTContext();
2356 if (!Ctx.getLangOpts().SizedDeallocation)
2357 return 0;
2358
2359 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2360 return 0;
2361 if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2362 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2363 return 0;
2364 if (isa<CXXRecordDecl>(getDeclContext()))
2365 return 0;
Richard Smithf6004412014-01-19 23:25:37 +00002366
2367 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2368 return 0;
Richard Smithb47c36f2013-11-05 09:12:18 +00002369
2370 if (getNumParams() != 2 || isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00002371 !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
Richard Smithb47c36f2013-11-05 09:12:18 +00002372 Ctx.getSizeType()))
2373 return 0;
2374
2375 // This is a sized deallocation function. Find the corresponding unsized
2376 // deallocation function.
2377 lookup_const_result R = getDeclContext()->lookup(getDeclName());
2378 for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2379 ++RI)
2380 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2381 if (FD->getNumParams() == 1 && !FD->isVariadic())
2382 return FD;
2383 return 0;
2384}
2385
Rafael Espindolaf4187652013-02-14 01:18:37 +00002386LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindolaf4187652013-02-14 01:18:37 +00002387 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002388}
2389
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002390bool FunctionDecl::isExternC() const {
2391 return isExternCTemplate(*this);
2392}
2393
Rafael Espindola593537a2013-05-05 20:15:21 +00002394bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002395 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002396}
2397
2398bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002399 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002400}
2401
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002402bool FunctionDecl::isGlobal() const {
2403 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2404 return Method->isStatic();
2405
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002406 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002407 return false;
2408
Mike Stump11289f42009-09-09 15:08:12 +00002409 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002410 DC->isNamespace();
2411 DC = DC->getParent()) {
2412 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2413 if (!Namespace->getDeclName())
2414 return false;
2415 break;
2416 }
2417 }
2418
2419 return true;
2420}
2421
Richard Smith10876ef2013-01-17 01:30:42 +00002422bool FunctionDecl::isNoReturn() const {
2423 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002424 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002425 getType()->getAs<FunctionType>()->getNoReturnAttr();
2426}
2427
Sebastian Redl833ef452010-01-26 22:01:41 +00002428void
2429FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002430 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002431
2432 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2433 FunctionTemplateDecl *PrevFunTmpl
2434 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2435 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002436 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002437 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002438
Axel Naumannfbc7b982011-11-08 18:21:06 +00002439 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002440 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002441}
2442
2443const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002444 return getFirstDecl();
Sebastian Redl833ef452010-01-26 22:01:41 +00002445}
2446
Rafael Espindola8db352d2013-10-17 15:37:26 +00002447FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002448
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002449/// \brief Returns a value indicating whether this function
2450/// corresponds to a builtin function.
2451///
2452/// The function corresponds to a built-in function if it is
2453/// declared at translation scope or within an extern "C" block and
2454/// its name matches with the name of a builtin. The returned value
2455/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002456/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002457/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002458unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002459 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002460 return 0;
2461
2462 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002463 if (!BuiltinID)
2464 return 0;
2465
2466 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002467 if (Context.getLangOpts().CPlusPlus) {
2468 const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2469 getFirstDecl()->getDeclContext());
2470 // In C++, the first declaration of a builtin is always inside an implicit
2471 // extern "C".
2472 // FIXME: A recognised library function may not be directly in an extern "C"
2473 // declaration, for instance "extern "C" { namespace std { decl } }".
2474 if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2475 return 0;
2476 }
2477
2478 // If the function is marked "overloadable", it has a different mangled name
2479 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002480 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002481 return 0;
2482
Douglas Gregore711f702009-02-14 18:57:46 +00002483 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2484 return BuiltinID;
2485
2486 // This function has the name of a known C library
2487 // function. Determine whether it actually refers to the C library
2488 // function or whether it just has the same name.
2489
Douglas Gregora908e7f2009-02-17 03:23:10 +00002490 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002491 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002492 return 0;
2493
Warren Hunt445d83e2013-11-01 23:46:51 +00002494 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002495}
2496
2497
Chris Lattner47c0d002009-04-25 06:03:53 +00002498/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002499/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002500/// after it has been created.
2501unsigned FunctionDecl::getNumParams() const {
Reid Kleckner0503a872013-12-05 01:23:43 +00002502 const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002503 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002504}
2505
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002506void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002507 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002508 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002509 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002510
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002511 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002512 if (!NewParamInfo.empty()) {
2513 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2514 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002515 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002516}
Chris Lattner41943152007-01-25 04:52:46 +00002517
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002518void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002519 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2520
2521 if (!NewDecls.empty()) {
2522 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2523 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002524 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002525 }
2526}
2527
Chris Lattner58258242008-04-10 02:22:51 +00002528/// getMinRequiredArguments - Returns the minimum number of arguments
2529/// needed to call this function. This may be fewer than the number of
2530/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002531/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002532unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002533 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002534 return getNumParams();
2535
Douglas Gregor7825bf32011-01-06 22:09:01 +00002536 unsigned NumRequiredArgs = getNumParams();
2537
2538 // If the last parameter is a parameter pack, we don't need an argument for
2539 // it.
2540 if (NumRequiredArgs > 0 &&
2541 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2542 --NumRequiredArgs;
2543
2544 // If this parameter has a default argument, we don't need an argument for
2545 // it.
2546 while (NumRequiredArgs > 0 &&
2547 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002548 --NumRequiredArgs;
2549
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002550 // We might have parameter packs before the end. These can't be deduced,
2551 // but they can still handle multiple arguments.
2552 unsigned ArgIdx = NumRequiredArgs;
2553 while (ArgIdx > 0) {
2554 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2555 NumRequiredArgs = ArgIdx;
2556
2557 --ArgIdx;
2558 }
2559
Chris Lattner58258242008-04-10 02:22:51 +00002560 return NumRequiredArgs;
2561}
2562
Eli Friedman1b125c32012-02-07 03:50:18 +00002563static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2564 // Only consider file-scope declarations in this test.
2565 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2566 return false;
2567
2568 // Only consider explicit declarations; the presence of a builtin for a
2569 // libcall shouldn't affect whether a definition is externally visible.
2570 if (Redecl->isImplicit())
2571 return false;
2572
2573 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2574 return true; // Not an inline definition
2575
2576 return false;
2577}
2578
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002579/// \brief For a function declaration in C or C++, determine whether this
2580/// declaration causes the definition to be externally visible.
2581///
Eli Friedman1b125c32012-02-07 03:50:18 +00002582/// Specifically, this determines if adding the current declaration to the set
2583/// of redeclarations of the given functions causes
2584/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002585bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2586 assert(!doesThisDeclarationHaveABody() &&
2587 "Must have a declaration without a body.");
2588
2589 ASTContext &Context = getASTContext();
2590
David Blaikiebbafb8a2012-03-11 07:00:24 +00002591 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002592 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2593 // an externally visible definition.
2594 //
2595 // FIXME: What happens if gnu_inline gets added on after the first
2596 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002597 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002598 return false;
2599
2600 const FunctionDecl *Prev = this;
2601 bool FoundBody = false;
2602 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002603 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002604
2605 if (Prev->Body) {
2606 // If it's not the case that both 'inline' and 'extern' are
2607 // specified on the definition, then it is always externally visible.
2608 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002609 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002610 return false;
2611 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002612 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002613 return false;
2614 }
2615 }
2616 return FoundBody;
2617 }
2618
David Blaikiebbafb8a2012-03-11 07:00:24 +00002619 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002620 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002621
2622 // C99 6.7.4p6:
2623 // [...] If all of the file scope declarations for a function in a
2624 // translation unit include the inline function specifier without extern,
2625 // then the definition in that translation unit is an inline definition.
2626 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002627 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002628 const FunctionDecl *Prev = this;
2629 bool FoundBody = false;
2630 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002631 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002632 if (RedeclForcesDefC99(Prev))
2633 return false;
2634 }
2635 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002636}
2637
Richard Smithf3814ad2013-01-25 00:08:28 +00002638/// \brief For an inline function definition in C, or for a gnu_inline function
2639/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002640///
2641/// Inline function definitions are always available for inlining optimizations.
2642/// However, depending on the language dialect, declaration specifiers, and
2643/// attributes, the definition of an inline function may or may not be
2644/// "externally" visible to other translation units in the program.
2645///
2646/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002647/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002648/// inline definition becomes externally visible (C99 6.7.4p6).
2649///
2650/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2651/// definition, we use the GNU semantics for inline, which are nearly the
2652/// opposite of C99 semantics. In particular, "inline" by itself will create
2653/// an externally visible symbol, but "extern inline" will not create an
2654/// externally visible symbol.
2655bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002656 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002657 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002658 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002659
David Blaikiebbafb8a2012-03-11 07:00:24 +00002660 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002661 // Note: If you change the logic here, please change
2662 // doesDeclarationForceExternallyVisibleDefinition as well.
2663 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002664 // If it's not the case that both 'inline' and 'extern' are
2665 // specified on the definition, then this inline definition is
2666 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002667 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002668 return true;
2669
2670 // If any declaration is 'inline' but not 'extern', then this definition
2671 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002672 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002673 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002674 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002675 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002676 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002677
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002678 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002679 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002680
Richard Smithf3814ad2013-01-25 00:08:28 +00002681 // The rest of this function is C-only.
2682 assert(!Context.getLangOpts().CPlusPlus &&
2683 "should not use C inline rules in C++");
2684
Douglas Gregor299d76e2009-09-13 07:46:26 +00002685 // C99 6.7.4p6:
2686 // [...] If all of the file scope declarations for a function in a
2687 // translation unit include the inline function specifier without extern,
2688 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002689 for (auto Redecl : redecls()) {
2690 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002691 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002692 }
2693
2694 // C99 6.7.4p6:
2695 // An inline definition does not provide an external definition for the
2696 // function, and does not forbid an external definition in another
2697 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002698 return false;
2699}
2700
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002701/// getOverloadedOperator - Which C++ overloaded operator this
2702/// function represents, if any.
2703OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002704 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2705 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002706 else
2707 return OO_None;
2708}
2709
Alexis Huntc88db062010-01-13 09:01:02 +00002710/// getLiteralIdentifier - The literal suffix identifier this function
2711/// represents, if any.
2712const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2713 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2714 return getDeclName().getCXXLiteralIdentifier();
2715 else
2716 return 0;
2717}
2718
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002719FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2720 if (TemplateOrSpecialization.isNull())
2721 return TK_NonTemplate;
2722 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2723 return TK_FunctionTemplate;
2724 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2725 return TK_MemberSpecialization;
2726 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2727 return TK_FunctionTemplateSpecialization;
2728 if (TemplateOrSpecialization.is
2729 <DependentFunctionTemplateSpecializationInfo*>())
2730 return TK_DependentFunctionTemplateSpecialization;
2731
David Blaikie83d382b2011-09-23 05:06:16 +00002732 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002733}
2734
Douglas Gregord801b062009-10-07 23:56:10 +00002735FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002736 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002737 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2738
2739 return 0;
2740}
2741
2742void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002743FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2744 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002745 TemplateSpecializationKind TSK) {
2746 assert(TemplateOrSpecialization.isNull() &&
2747 "Member function is already a specialization");
2748 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002749 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002750 TemplateOrSpecialization = Info;
2751}
2752
Douglas Gregorafca3b42009-10-27 20:53:28 +00002753bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002754 // If the function is invalid, it can't be implicitly instantiated.
2755 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002756 return false;
2757
2758 switch (getTemplateSpecializationKind()) {
2759 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002760 case TSK_ExplicitInstantiationDefinition:
2761 return false;
2762
2763 case TSK_ImplicitInstantiation:
2764 return true;
2765
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002766 // It is possible to instantiate TSK_ExplicitSpecialization kind
2767 // if the FunctionDecl has a class scope specialization pattern.
2768 case TSK_ExplicitSpecialization:
2769 return getClassScopeSpecializationPattern() != 0;
2770
Douglas Gregorafca3b42009-10-27 20:53:28 +00002771 case TSK_ExplicitInstantiationDeclaration:
2772 // Handled below.
2773 break;
2774 }
2775
2776 // Find the actual template from which we will instantiate.
2777 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002778 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002779 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002780 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002781
2782 // C++0x [temp.explicit]p9:
2783 // Except for inline functions, other explicit instantiation declarations
2784 // have the effect of suppressing the implicit instantiation of the entity
2785 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002786 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002787 return true;
2788
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002789 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002790}
2791
2792bool FunctionDecl::isTemplateInstantiation() const {
2793 switch (getTemplateSpecializationKind()) {
2794 case TSK_Undeclared:
2795 case TSK_ExplicitSpecialization:
2796 return false;
2797 case TSK_ImplicitInstantiation:
2798 case TSK_ExplicitInstantiationDeclaration:
2799 case TSK_ExplicitInstantiationDefinition:
2800 return true;
2801 }
2802 llvm_unreachable("All TSK values handled.");
2803}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002804
2805FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002806 // Handle class scope explicit specialization special case.
2807 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2808 return getClassScopeSpecializationPattern();
2809
Douglas Gregorafca3b42009-10-27 20:53:28 +00002810 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2811 while (Primary->getInstantiatedFromMemberTemplate()) {
2812 // If we have hit a point where the user provided a specialization of
2813 // this template, we're done looking.
2814 if (Primary->isMemberSpecialization())
2815 break;
2816
2817 Primary = Primary->getInstantiatedFromMemberTemplate();
2818 }
2819
2820 return Primary->getTemplatedDecl();
2821 }
2822
2823 return getInstantiatedFromMemberFunction();
2824}
2825
Douglas Gregor70d83e22009-06-29 17:30:29 +00002826FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002827 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002828 = TemplateOrSpecialization
2829 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002830 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002831 }
2832 return 0;
2833}
2834
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002835FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2836 return getASTContext().getClassScopeSpecializationPattern(this);
2837}
2838
Douglas Gregor70d83e22009-06-29 17:30:29 +00002839const TemplateArgumentList *
2840FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002841 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002842 = TemplateOrSpecialization
2843 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002844 return Info->TemplateArguments;
2845 }
2846 return 0;
2847}
2848
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002849const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002850FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2851 if (FunctionTemplateSpecializationInfo *Info
2852 = TemplateOrSpecialization
2853 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2854 return Info->TemplateArgumentsAsWritten;
2855 }
2856 return 0;
2857}
2858
Mike Stump11289f42009-09-09 15:08:12 +00002859void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002860FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2861 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002862 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002863 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002864 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002865 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2866 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002867 assert(TSK != TSK_Undeclared &&
2868 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002869 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002870 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002871 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002872 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2873 TemplateArgs,
2874 TemplateArgsAsWritten,
2875 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002876 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002877 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002878}
2879
John McCallb9c78482010-04-08 09:05:18 +00002880void
2881FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2882 const UnresolvedSetImpl &Templates,
2883 const TemplateArgumentListInfo &TemplateArgs) {
2884 assert(TemplateOrSpecialization.isNull());
2885 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2886 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002887 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002888 void *Buffer = Context.Allocate(Size);
2889 DependentFunctionTemplateSpecializationInfo *Info =
2890 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2891 TemplateArgs);
2892 TemplateOrSpecialization = Info;
2893}
2894
2895DependentFunctionTemplateSpecializationInfo::
2896DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2897 const TemplateArgumentListInfo &TArgs)
2898 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2899
2900 d.NumTemplates = Ts.size();
2901 d.NumArgs = TArgs.size();
2902
2903 FunctionTemplateDecl **TsArray =
2904 const_cast<FunctionTemplateDecl**>(getTemplates());
2905 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2906 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2907
2908 TemplateArgumentLoc *ArgsArray =
2909 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2910 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2911 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2912}
2913
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002914TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002915 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002916 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002917 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002918 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002919 if (FTSInfo)
2920 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002921
Douglas Gregord801b062009-10-07 23:56:10 +00002922 MemberSpecializationInfo *MSInfo
2923 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2924 if (MSInfo)
2925 return MSInfo->getTemplateSpecializationKind();
2926
2927 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002928}
2929
Mike Stump11289f42009-09-09 15:08:12 +00002930void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002931FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2932 SourceLocation PointOfInstantiation) {
2933 if (FunctionTemplateSpecializationInfo *FTSInfo
2934 = TemplateOrSpecialization.dyn_cast<
2935 FunctionTemplateSpecializationInfo*>()) {
2936 FTSInfo->setTemplateSpecializationKind(TSK);
2937 if (TSK != TSK_ExplicitSpecialization &&
2938 PointOfInstantiation.isValid() &&
2939 FTSInfo->getPointOfInstantiation().isInvalid())
2940 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2941 } else if (MemberSpecializationInfo *MSInfo
2942 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2943 MSInfo->setTemplateSpecializationKind(TSK);
2944 if (TSK != TSK_ExplicitSpecialization &&
2945 PointOfInstantiation.isValid() &&
2946 MSInfo->getPointOfInstantiation().isInvalid())
2947 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2948 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002949 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002950}
2951
2952SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002953 if (FunctionTemplateSpecializationInfo *FTSInfo
2954 = TemplateOrSpecialization.dyn_cast<
2955 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002956 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002957 else if (MemberSpecializationInfo *MSInfo
2958 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002959 return MSInfo->getPointOfInstantiation();
2960
2961 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002962}
2963
Douglas Gregor6411b922009-09-11 20:15:17 +00002964bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002965 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002966 return true;
2967
2968 // If this function was instantiated from a member function of a
2969 // class template, check whether that member function was defined out-of-line.
2970 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2971 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002972 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002973 return Definition->isOutOfLine();
2974 }
2975
2976 // If this function was instantiated from a function template,
2977 // check whether that function template was defined out-of-line.
2978 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2979 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002980 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002981 return Definition->isOutOfLine();
2982 }
2983
2984 return false;
2985}
2986
Abramo Bagnaraea947882011-03-08 16:41:52 +00002987SourceRange FunctionDecl::getSourceRange() const {
2988 return SourceRange(getOuterLocStart(), EndRangeLoc);
2989}
2990
Anna Zaks28db7ce2012-01-18 02:45:01 +00002991unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002992 IdentifierInfo *FnInfo = getIdentifier();
2993
2994 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002995 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002996
2997 // Builtin handling.
2998 switch (getBuiltinID()) {
2999 case Builtin::BI__builtin_memset:
3000 case Builtin::BI__builtin___memset_chk:
3001 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003002 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003003
3004 case Builtin::BI__builtin_memcpy:
3005 case Builtin::BI__builtin___memcpy_chk:
3006 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003007 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003008
3009 case Builtin::BI__builtin_memmove:
3010 case Builtin::BI__builtin___memmove_chk:
3011 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003012 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003013
3014 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003015 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003016 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00003017 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003018
3019 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003020 case Builtin::BImemcmp:
3021 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003022
3023 case Builtin::BI__builtin_strncpy:
3024 case Builtin::BI__builtin___strncpy_chk:
3025 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003026 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003027
3028 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003029 case Builtin::BIstrncmp:
3030 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003031
3032 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003033 case Builtin::BIstrncasecmp:
3034 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003035
3036 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003037 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003038 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003039 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003040
3041 case Builtin::BI__builtin_strndup:
3042 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003043 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003044
Anna Zaks314cd092012-02-01 19:08:57 +00003045 case Builtin::BI__builtin_strlen:
3046 case Builtin::BIstrlen:
3047 return Builtin::BIstrlen;
3048
Anna Zaks201d4892012-01-13 21:52:01 +00003049 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003050 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003051 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003052 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003053 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003054 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003055 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003056 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003057 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003058 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003059 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003060 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003061 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003062 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003063 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003064 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003065 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003066 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003067 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003068 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003069 else if (FnInfo->isStr("strlen"))
3070 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003071 }
3072 break;
3073 }
Anna Zaks22122702012-01-17 00:37:07 +00003074 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003075}
3076
Chris Lattner59a25942008-03-31 00:36:02 +00003077//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003078// FieldDecl Implementation
3079//===----------------------------------------------------------------------===//
3080
Jay Foad39c79802011-01-12 09:06:06 +00003081FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003082 SourceLocation StartLoc, SourceLocation IdLoc,
3083 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003084 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003085 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003086 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3087 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003088}
3089
Douglas Gregor72172e92012-01-05 21:55:30 +00003090FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003091 return new (C, ID) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
3092 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003093}
3094
Sebastian Redl833ef452010-01-26 22:01:41 +00003095bool FieldDecl::isAnonymousStructOrUnion() const {
3096 if (!isImplicit() || getDeclName())
3097 return false;
3098
3099 if (const RecordType *Record = getType()->getAs<RecordType>())
3100 return Record->getDecl()->isAnonymousStructOrUnion();
3101
3102 return false;
3103}
3104
Richard Smithcaf33902011-10-10 18:28:20 +00003105unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3106 assert(isBitField() && "not a bitfield");
3107 Expr *BitWidth = InitializerOrBitWidth.getPointer();
3108 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3109}
3110
John McCall4e819612011-01-20 07:57:12 +00003111unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003112 const FieldDecl *Canonical = getCanonicalDecl();
3113 if (Canonical != this)
3114 return Canonical->getFieldIndex();
3115
John McCall4e819612011-01-20 07:57:12 +00003116 if (CachedFieldIndex) return CachedFieldIndex - 1;
3117
Richard Smithd62306a2011-11-10 06:34:14 +00003118 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003119 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003120
3121 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
Eli Friedman2782dac2013-06-26 20:50:34 +00003122 I != E; ++I, ++Index)
Richard Smith0b87e072013-10-07 08:02:11 +00003123 I->getCanonicalDecl()->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00003124
Richard Smithd62306a2011-11-10 06:34:14 +00003125 assert(CachedFieldIndex && "failed to find field in parent");
3126 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003127}
3128
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003129SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00003130 if (const Expr *E = InitializerOrBitWidth.getPointer())
3131 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00003132 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003133}
3134
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00003135void FieldDecl::setBitWidth(Expr *Width) {
3136 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3137 "bit width or initializer already set");
3138 InitializerOrBitWidth.setPointer(Width);
3139}
3140
Richard Smith938f40b2011-06-11 17:19:42 +00003141void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00003142 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00003143 "bit width or initializer already set");
3144 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00003145}
3146
Sebastian Redl833ef452010-01-26 22:01:41 +00003147//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003148// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003149//===----------------------------------------------------------------------===//
3150
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003151SourceLocation TagDecl::getOuterLocStart() const {
3152 return getTemplateOrInnerLocStart(this);
3153}
3154
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003155SourceRange TagDecl::getSourceRange() const {
3156 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003157 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003158}
3159
Rafael Espindola8db352d2013-10-17 15:37:26 +00003160TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003161
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003162void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer50ce8352013-09-17 23:57:10 +00003163 NamedDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00003164 if (TypeForDecl)
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003165 assert(TypeForDecl->isLinkageValid());
3166 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003167}
3168
Douglas Gregordee1be82009-01-17 00:42:38 +00003169void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003170 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003171
David Blaikie095deba2012-11-14 01:52:05 +00003172 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00003173 struct CXXRecordDecl::DefinitionData *Data =
3174 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003175 for (auto I : redecls())
3176 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003177 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003178}
3179
3180void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003181 assert((!isa<CXXRecordDecl>(this) ||
3182 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3183 "definition completed but not started");
3184
John McCallf937c022011-10-07 06:10:15 +00003185 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003186 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003187
3188 if (ASTMutationListener *L = getASTMutationListener())
3189 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003190}
3191
John McCallf937c022011-10-07 06:10:15 +00003192TagDecl *TagDecl::getDefinition() const {
3193 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003194 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003195
3196 // If it's possible for us to have an out-of-date definition, check now.
3197 if (MayHaveOutOfDateDef) {
3198 if (IdentifierInfo *II = getIdentifier()) {
3199 if (II->isOutOfDate()) {
3200 updateOutOfDate(*II);
3201 }
3202 }
3203 }
3204
Andrew Trickba266ee2010-10-19 21:54:32 +00003205 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3206 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003207
Aaron Ballman86c93902014-03-06 23:45:36 +00003208 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003209 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003210 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003211
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003212 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00003213}
3214
Douglas Gregor14454802011-02-25 02:25:35 +00003215void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3216 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003217 // Make sure the extended qualifier info is allocated.
3218 if (!hasExtInfo())
David Majnemer50ce8352013-09-17 23:57:10 +00003219 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003220 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003221 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003222 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003223 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003224 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003225 if (getExtInfo()->NumTemplParamLists == 0) {
3226 getASTContext().Deallocate(getExtInfo());
David Majnemer50ce8352013-09-17 23:57:10 +00003227 NamedDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003228 }
3229 else
3230 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003231 }
3232 }
3233}
3234
Abramo Bagnara60804e12011-03-18 15:16:37 +00003235void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3236 unsigned NumTPLists,
3237 TemplateParameterList **TPLists) {
3238 assert(NumTPLists > 0);
3239 // Make sure the extended decl info is allocated.
3240 if (!hasExtInfo())
3241 // Allocate external info struct.
David Majnemer50ce8352013-09-17 23:57:10 +00003242 NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003243 // Set the template parameter lists info.
3244 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3245}
3246
Ted Kremenek21475702008-09-05 17:16:31 +00003247//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003248// EnumDecl Implementation
3249//===----------------------------------------------------------------------===//
3250
David Blaikie68e081d2011-12-20 02:48:34 +00003251void EnumDecl::anchor() { }
3252
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003253EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3254 SourceLocation StartLoc, SourceLocation IdLoc,
3255 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003256 EnumDecl *PrevDecl, bool IsScoped,
3257 bool IsScopedUsingClassTag, bool IsFixed) {
Richard Smithf7981722013-11-22 09:01:48 +00003258 EnumDecl *Enum = new (C, DC) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
3259 IsScoped, IsScopedUsingClassTag,
3260 IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003261 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003262 C.getTypeDeclType(Enum, PrevDecl);
3263 return Enum;
3264}
3265
Douglas Gregor72172e92012-01-05 21:55:30 +00003266EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003267 EnumDecl *Enum = new (C, ID) EnumDecl(0, SourceLocation(), SourceLocation(),
3268 0, 0, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003269 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3270 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003271}
3272
Alp Tokerb9fa5122014-01-06 11:31:18 +00003273SourceRange EnumDecl::getIntegerTypeRange() const {
3274 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3275 return TI->getTypeLoc().getSourceRange();
3276 return SourceRange();
3277}
3278
Douglas Gregord5058122010-02-11 01:19:42 +00003279void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003280 QualType NewPromotionType,
3281 unsigned NumPositiveBits,
3282 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003283 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003284 if (!IntegerType)
3285 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003286 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003287 setNumPositiveBits(NumPositiveBits);
3288 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003289 TagDecl::completeDefinition();
3290}
3291
Richard Smith7d137e32012-03-23 03:33:32 +00003292TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3293 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3294 return MSI->getTemplateSpecializationKind();
3295
3296 return TSK_Undeclared;
3297}
3298
3299void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3300 SourceLocation PointOfInstantiation) {
3301 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3302 assert(MSI && "Not an instantiated member enumeration?");
3303 MSI->setTemplateSpecializationKind(TSK);
3304 if (TSK != TSK_ExplicitSpecialization &&
3305 PointOfInstantiation.isValid() &&
3306 MSI->getPointOfInstantiation().isInvalid())
3307 MSI->setPointOfInstantiation(PointOfInstantiation);
3308}
3309
Richard Smith4b38ded2012-03-14 23:13:10 +00003310EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3311 if (SpecializationInfo)
3312 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3313
3314 return 0;
3315}
3316
3317void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3318 TemplateSpecializationKind TSK) {
3319 assert(!SpecializationInfo && "Member enum is already a specialization");
3320 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3321}
3322
Sebastian Redl833ef452010-01-26 22:01:41 +00003323//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003324// RecordDecl Implementation
3325//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003326
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003327RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3328 SourceLocation StartLoc, SourceLocation IdLoc,
3329 IdentifierInfo *Id, RecordDecl *PrevDecl)
3330 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003331 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003332 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003333 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003334 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003335 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003336 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003337}
3338
Jay Foad39c79802011-01-12 09:06:06 +00003339RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003340 SourceLocation StartLoc, SourceLocation IdLoc,
3341 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smithf7981722013-11-22 09:01:48 +00003342 RecordDecl* R = new (C, DC) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3343 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003344 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3345
Ted Kremenek21475702008-09-05 17:16:31 +00003346 C.getTypeDeclType(R, PrevDecl);
3347 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003348}
3349
Douglas Gregor72172e92012-01-05 21:55:30 +00003350RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003351 RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3352 SourceLocation(), 0, 0);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003353 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3354 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003355}
3356
Douglas Gregordfcad112009-03-25 15:59:44 +00003357bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003358 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003359 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3360}
3361
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003362RecordDecl::field_iterator RecordDecl::field_begin() const {
3363 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3364 LoadFieldsFromExternalStorage();
3365
3366 return field_iterator(decl_iterator(FirstDecl));
3367}
3368
Douglas Gregorb11aad82011-02-19 18:51:44 +00003369/// completeDefinition - Notes that the definition of this type is now
3370/// complete.
3371void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003372 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003373 TagDecl::completeDefinition();
3374}
3375
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003376/// isMsStruct - Get whether or not this record uses ms_struct layout.
3377/// This which can be turned on with an attribute, pragma, or the
3378/// -mms-bitfields command-line option.
3379bool RecordDecl::isMsStruct(const ASTContext &C) const {
3380 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3381}
3382
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003383static bool isFieldOrIndirectField(Decl::Kind K) {
3384 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3385}
3386
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003387void RecordDecl::LoadFieldsFromExternalStorage() const {
3388 ExternalASTSource *Source = getASTContext().getExternalSource();
3389 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3390
3391 // Notify that we have a RecordDecl doing some initialization.
3392 ExternalASTSource::Deserializing TheFields(Source);
3393
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003394 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003395 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003396 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3397 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003398 case ELR_Success:
3399 break;
3400
3401 case ELR_AlreadyLoaded:
3402 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003403 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003404 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003405
3406#ifndef NDEBUG
3407 // Check that all decls we got were FieldDecls.
3408 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003409 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003410#endif
3411
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003412 if (Decls.empty())
3413 return;
3414
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003415 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003416 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003417}
3418
Steve Naroff415d3d52008-10-08 17:01:13 +00003419//===----------------------------------------------------------------------===//
3420// BlockDecl Implementation
3421//===----------------------------------------------------------------------===//
3422
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003423void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003424 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003425
Steve Naroffc4b30e52009-03-13 16:56:44 +00003426 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003427 if (!NewParamInfo.empty()) {
3428 NumParams = NewParamInfo.size();
3429 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3430 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003431 }
3432}
3433
John McCall351762c2011-02-07 10:33:21 +00003434void BlockDecl::setCaptures(ASTContext &Context,
3435 const Capture *begin,
3436 const Capture *end,
3437 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003438 CapturesCXXThis = capturesCXXThis;
3439
3440 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003441 NumCaptures = 0;
3442 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003443 return;
3444 }
3445
John McCall351762c2011-02-07 10:33:21 +00003446 NumCaptures = end - begin;
3447
3448 // Avoid new Capture[] because we don't want to provide a default
3449 // constructor.
3450 size_t allocationSize = NumCaptures * sizeof(Capture);
3451 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3452 memcpy(buffer, begin, allocationSize);
3453 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003454}
Sebastian Redl833ef452010-01-26 22:01:41 +00003455
John McCallce45f882011-06-15 22:51:16 +00003456bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003457 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003458 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003459 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003460 return true;
3461
3462 return false;
3463}
3464
Douglas Gregor70226da2010-12-21 16:27:07 +00003465SourceRange BlockDecl::getSourceRange() const {
3466 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3467}
Sebastian Redl833ef452010-01-26 22:01:41 +00003468
3469//===----------------------------------------------------------------------===//
3470// Other Decl Allocation/Deallocation Method Implementations
3471//===----------------------------------------------------------------------===//
3472
David Blaikie68e081d2011-12-20 02:48:34 +00003473void TranslationUnitDecl::anchor() { }
3474
Sebastian Redl833ef452010-01-26 22:01:41 +00003475TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Richard Smithf7981722013-11-22 09:01:48 +00003476 return new (C, (DeclContext*)0) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003477}
3478
David Blaikie68e081d2011-12-20 02:48:34 +00003479void LabelDecl::anchor() { }
3480
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003481LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003482 SourceLocation IdentL, IdentifierInfo *II) {
Richard Smithf7981722013-11-22 09:01:48 +00003483 return new (C, DC) LabelDecl(DC, IdentL, II, 0, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003484}
3485
3486LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3487 SourceLocation IdentL, IdentifierInfo *II,
3488 SourceLocation GnuLabelL) {
3489 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Richard Smithf7981722013-11-22 09:01:48 +00003490 return new (C, DC) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003491}
3492
Douglas Gregor72172e92012-01-05 21:55:30 +00003493LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003494 return new (C, ID) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003495}
3496
David Blaikie68e081d2011-12-20 02:48:34 +00003497void ValueDecl::anchor() { }
3498
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003499bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00003500 for (const auto *I : attrs())
3501 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003502 return true;
3503
3504 return isWeakImported();
3505}
3506
David Blaikie68e081d2011-12-20 02:48:34 +00003507void ImplicitParamDecl::anchor() { }
3508
Sebastian Redl833ef452010-01-26 22:01:41 +00003509ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003510 SourceLocation IdLoc,
3511 IdentifierInfo *Id,
3512 QualType Type) {
Richard Smithf7981722013-11-22 09:01:48 +00003513 return new (C, DC) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003514}
3515
Richard Smithf7981722013-11-22 09:01:48 +00003516ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003517 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003518 return new (C, ID) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003519}
3520
Sebastian Redl833ef452010-01-26 22:01:41 +00003521FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003522 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003523 const DeclarationNameInfo &NameInfo,
3524 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003525 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003526 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003527 bool hasWrittenPrototype,
3528 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003529 FunctionDecl *New =
3530 new (C, DC) FunctionDecl(Function, DC, StartLoc, NameInfo, T, TInfo, SC,
3531 isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003532 New->HasWrittenPrototype = hasWrittenPrototype;
3533 return New;
3534}
3535
Douglas Gregor72172e92012-01-05 21:55:30 +00003536FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003537 return new (C, ID) FunctionDecl(Function, 0, SourceLocation(),
3538 DeclarationNameInfo(), QualType(), 0,
3539 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003540}
3541
Sebastian Redl833ef452010-01-26 22:01:41 +00003542BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003543 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003544}
3545
Douglas Gregor72172e92012-01-05 21:55:30 +00003546BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003547 return new (C, ID) BlockDecl(0, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003548}
3549
Ben Langmuir37943a72013-05-03 19:00:33 +00003550CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3551 unsigned NumParams) {
Richard Smithf7981722013-11-22 09:01:48 +00003552 return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3553 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003554}
3555
Ben Langmuirce914fc2013-05-03 19:20:19 +00003556CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00003557 unsigned NumParams) {
3558 return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3559 CapturedDecl(0, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00003560}
3561
Sebastian Redl833ef452010-01-26 22:01:41 +00003562EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3563 SourceLocation L,
3564 IdentifierInfo *Id, QualType T,
3565 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00003566 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00003567}
3568
Douglas Gregor72172e92012-01-05 21:55:30 +00003569EnumConstantDecl *
3570EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003571 return new (C, ID) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3572 llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00003573}
3574
David Blaikie68e081d2011-12-20 02:48:34 +00003575void IndirectFieldDecl::anchor() { }
3576
Benjamin Kramer39593702010-11-21 14:11:41 +00003577IndirectFieldDecl *
3578IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3579 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3580 unsigned CHS) {
Richard Smithf7981722013-11-22 09:01:48 +00003581 return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00003582}
3583
Douglas Gregor72172e92012-01-05 21:55:30 +00003584IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3585 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003586 return new (C, ID) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3587 QualType(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003588}
3589
Douglas Gregorbe996932010-09-01 20:41:53 +00003590SourceRange EnumConstantDecl::getSourceRange() const {
3591 SourceLocation End = getLocation();
3592 if (Init)
3593 End = Init->getLocEnd();
3594 return SourceRange(getLocation(), End);
3595}
3596
David Blaikie68e081d2011-12-20 02:48:34 +00003597void TypeDecl::anchor() { }
3598
Sebastian Redl833ef452010-01-26 22:01:41 +00003599TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003600 SourceLocation StartLoc, SourceLocation IdLoc,
3601 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smithf7981722013-11-22 09:01:48 +00003602 return new (C, DC) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003603}
3604
David Blaikie68e081d2011-12-20 02:48:34 +00003605void TypedefNameDecl::anchor() { }
3606
Douglas Gregor72172e92012-01-05 21:55:30 +00003607TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003608 return new (C, ID) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003609}
3610
Richard Smithdda56e42011-04-15 14:24:37 +00003611TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3612 SourceLocation StartLoc,
3613 SourceLocation IdLoc, IdentifierInfo *Id,
3614 TypeSourceInfo *TInfo) {
Richard Smithf7981722013-11-22 09:01:48 +00003615 return new (C, DC) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00003616}
3617
Douglas Gregor72172e92012-01-05 21:55:30 +00003618TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003619 return new (C, ID) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00003620}
3621
Abramo Bagnaraea947882011-03-08 16:41:52 +00003622SourceRange TypedefDecl::getSourceRange() const {
3623 SourceLocation RangeEnd = getLocation();
3624 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3625 if (typeIsPostfix(TInfo->getType()))
3626 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3627 }
3628 return SourceRange(getLocStart(), RangeEnd);
3629}
3630
Richard Smithdda56e42011-04-15 14:24:37 +00003631SourceRange TypeAliasDecl::getSourceRange() const {
3632 SourceLocation RangeEnd = getLocStart();
3633 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3634 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3635 return SourceRange(getLocStart(), RangeEnd);
3636}
3637
David Blaikie68e081d2011-12-20 02:48:34 +00003638void FileScopeAsmDecl::anchor() { }
3639
Sebastian Redl833ef452010-01-26 22:01:41 +00003640FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003641 StringLiteral *Str,
3642 SourceLocation AsmLoc,
3643 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003644 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003645}
Douglas Gregorba345522011-12-02 23:23:56 +00003646
Richard Smithf7981722013-11-22 09:01:48 +00003647FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003648 unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003649 return new (C, ID) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00003650}
3651
Michael Han84324352013-02-22 17:15:32 +00003652void EmptyDecl::anchor() {}
3653
3654EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003655 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00003656}
3657
3658EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smithf7981722013-11-22 09:01:48 +00003659 return new (C, ID) EmptyDecl(0, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00003660}
3661
Douglas Gregorba345522011-12-02 23:23:56 +00003662//===----------------------------------------------------------------------===//
3663// ImportDecl Implementation
3664//===----------------------------------------------------------------------===//
3665
3666/// \brief Retrieve the number of module identifiers needed to name the given
3667/// module.
3668static unsigned getNumModuleIdentifiers(Module *Mod) {
3669 unsigned Result = 1;
3670 while (Mod->Parent) {
3671 Mod = Mod->Parent;
3672 ++Result;
3673 }
3674 return Result;
3675}
3676
Douglas Gregor22d09742012-01-03 18:04:46 +00003677ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003678 Module *Imported,
3679 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003680 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003681 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003682{
3683 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3684 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3685 memcpy(StoredLocs, IdentifierLocs.data(),
3686 IdentifierLocs.size() * sizeof(SourceLocation));
3687}
3688
Douglas Gregor22d09742012-01-03 18:04:46 +00003689ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003690 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003691 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003692 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003693{
3694 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3695}
3696
Richard Smithf7981722013-11-22 09:01:48 +00003697ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003698 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003699 ArrayRef<SourceLocation> IdentifierLocs) {
Richard Smithf7981722013-11-22 09:01:48 +00003700 return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3701 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003702}
3703
Richard Smithf7981722013-11-22 09:01:48 +00003704ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003705 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00003706 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003707 SourceLocation EndLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00003708 ImportDecl *Import =
3709 new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3710 Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003711 Import->setImplicit();
3712 return Import;
3713}
3714
Douglas Gregor72172e92012-01-05 21:55:30 +00003715ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3716 unsigned NumLocations) {
Richard Smithf7981722013-11-22 09:01:48 +00003717 return new (C, ID, NumLocations * sizeof(SourceLocation))
3718 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00003719}
3720
3721ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3722 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003723 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00003724
3725 const SourceLocation *StoredLocs
3726 = reinterpret_cast<const SourceLocation *>(this + 1);
3727 return ArrayRef<SourceLocation>(StoredLocs,
3728 getNumModuleIdentifiers(getImportedModule()));
3729}
3730
3731SourceRange ImportDecl::getSourceRange() const {
3732 if (!ImportedAndComplete.getInt())
3733 return SourceRange(getLocation(),
3734 *reinterpret_cast<const SourceLocation *>(this + 1));
3735
3736 return SourceRange(getLocation(), getIdentifierLocs().back());
3737}