blob: 9ee70e251089a306565c5a3139baea56149b0eed [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000024#include "clang/AST/Stmt.h"
25#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000026#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000027#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000028#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000029#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000030#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000031#include "llvm/Support/ErrorHandling.h"
John McCall5f46c482013-02-21 23:42:58 +000032#include "llvm/Support/type_traits.h"
David Blaikie9c70e042011-09-21 18:16:56 +000033#include <algorithm>
34
Chris Lattner6d9a6852006-10-25 05:11:20 +000035using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000036
Chris Lattner88f70d62008-03-15 05:43:15 +000037//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000038// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000039//===----------------------------------------------------------------------===//
40
John McCalldf25c432013-02-16 00:17:33 +000041// Visibility rules aren't rigorously externally specified, but here
42// are the basic principles behind what we implement:
43//
44// 1. An explicit visibility attribute is generally a direct expression
45// of the user's intent and should be honored. Only the innermost
46// visibility attribute applies. If no visibility attribute applies,
47// global visibility settings are considered.
48//
49// 2. There is one caveat to the above: on or in a template pattern,
50// an explicit visibility attribute is just a default rule, and
51// visibility can be decreased by the visibility of template
52// arguments. But this, too, has an exception: an attribute on an
53// explicit specialization or instantiation causes all the visibility
54// restrictions of the template arguments to be ignored.
55//
56// 3. A variable that does not otherwise have explicit visibility can
57// be restricted by the visibility of its type.
58//
59// 4. A visibility restriction is explicit if it comes from an
60// attribute (or something like it), not a global visibility setting.
61// When emitting a reference to an external symbol, visibility
62// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000063//
64// 5. When computing the visibility of a non-type, including a
65// non-type member of a class, only non-type visibility restrictions
66// are considered: the 'visibility' attribute, global value-visibility
67// settings, and a few special cases like __private_extern.
68//
69// 6. When computing the visibility of a type, including a type member
70// of a class, only type visibility restrictions are considered:
71// the 'type_visibility' attribute and global type-visibility settings.
72// However, a 'visibility' attribute counts as a 'type_visibility'
73// attribute on any declaration that only has the former.
74//
75// The visibility of a "secondary" entity, like a template argument,
76// is computed using the kind of that entity, not the kind of the
77// primary entity for which we are computing visibility. For example,
78// the visibility of a specialization of either of these templates:
79// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
80// template <class T, bool (&compare)(T, X)> class matcher;
81// is restricted according to the type visibility of the argument 'T',
82// the type visibility of 'bool(&)(T,X)', and the value visibility of
83// the argument function 'compare'. That 'has_match' is a value
84// and 'matcher' is a type only matters when looking for attributes
85// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +000086
John McCall5f46c482013-02-21 23:42:58 +000087const unsigned IgnoreExplicitVisibilityBit = 2;
88
John McCalldf25c432013-02-16 00:17:33 +000089/// Kinds of LV computation. The linkage side of the computation is
90/// always the same, but different things can change how visibility is
91/// computed.
92enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +000093 /// Do an LV computation for, ultimately, a type.
94 /// Visibility may be restricted by type visibility settings and
95 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +000096 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +000097
John McCall5f46c482013-02-21 23:42:58 +000098 /// Do an LV computation for, ultimately, a non-type declaration.
99 /// Visibility may be restricted by value visibility settings and
100 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000101 LVForValue = NamedDecl::VisibilityForValue,
102
John McCall5f46c482013-02-21 23:42:58 +0000103 /// Do an LV computation for, ultimately, a type that already has
104 /// some sort of explicit visibility. Visibility may only be
105 /// restricted by the visibility of template arguments.
106 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000107
John McCall5f46c482013-02-21 23:42:58 +0000108 /// Do an LV computation for, ultimately, a non-type declaration
109 /// that already has some sort of explicit visibility. Visibility
110 /// may only be restricted by the visibility of template arguments.
111 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit)
John McCalldf25c432013-02-16 00:17:33 +0000112};
113
John McCalld041a9b2013-02-20 01:54:26 +0000114/// Does this computation kind permit us to consider additional
115/// visibility settings from attributes and the like?
116static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000117 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000118}
119
120/// Given an LVComputationKind, return one of the same type/value sort
121/// that records that it already has explicit visibility.
122static LVComputationKind
123withExplicitVisibilityAlready(LVComputationKind oldKind) {
124 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000125 static_cast<LVComputationKind>(unsigned(oldKind) |
126 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000127 assert(oldKind != LVForType || newKind == LVForExplicitType);
128 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
129 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
130 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
131 return newKind;
132}
133
David Blaikie05785d12013-02-20 22:23:23 +0000134static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
135 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000136 assert(!hasExplicitVisibilityAlready(kind) &&
137 "asking for explicit visibility when we shouldn't be");
138 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
139}
140
John McCalldf25c432013-02-16 00:17:33 +0000141/// Is the given declaration a "type" or a "value" for the purposes of
142/// visibility computation?
143static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000144 return isa<TypeDecl>(D) ||
145 isa<ClassTemplateDecl>(D) ||
146 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000147}
148
John McCall5f46c482013-02-21 23:42:58 +0000149/// Does the given declaration have member specialization information,
150/// and if so, is it an explicit specialization?
151template <class T> static typename
152llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value,
153 bool>::type
154isExplicitMemberSpecialization(const T *D) {
155 if (const MemberSpecializationInfo *member =
156 D->getMemberSpecializationInfo()) {
157 return member->isExplicitSpecialization();
158 }
159 return false;
160}
161
162/// For templates, this question is easier: a member template can't be
163/// explicitly instantiated, so there's a single bit indicating whether
164/// or not this is an explicit member specialization.
165static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
166 return D->isMemberSpecialization();
167}
168
John McCalld041a9b2013-02-20 01:54:26 +0000169/// Given a visibility attribute, return the explicit visibility
170/// associated with it.
171template <class T>
172static Visibility getVisibilityFromAttr(const T *attr) {
173 switch (attr->getVisibility()) {
174 case T::Default:
175 return DefaultVisibility;
176 case T::Hidden:
177 return HiddenVisibility;
178 case T::Protected:
179 return ProtectedVisibility;
180 }
181 llvm_unreachable("bad visibility kind");
182}
183
John McCalldf25c432013-02-16 00:17:33 +0000184/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000185static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000186 NamedDecl::ExplicitVisibilityKind kind) {
187 // If we're ultimately computing the visibility of a type, look for
188 // a 'type_visibility' attribute before looking for 'visibility'.
189 if (kind == NamedDecl::VisibilityForType) {
190 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
191 return getVisibilityFromAttr(A);
192 }
193 }
194
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000195 // If this declaration has an explicit visibility attribute, use it.
196 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000197 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000198 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000199
200 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
201 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000202 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000203 for (specific_attr_iterator<AvailabilityAttr>
204 A = D->specific_attr_begin<AvailabilityAttr>(),
205 AEnd = D->specific_attr_end<AvailabilityAttr>();
206 A != AEnd; ++A)
207 if ((*A)->getPlatform()->getName().equals("macosx"))
208 return DefaultVisibility;
209 }
210
David Blaikie7a30dc52013-02-21 01:47:18 +0000211 return None;
John McCall457a04e2010-10-22 21:05:15 +0000212}
213
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000214/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000215/// template parameter list. For visibility purposes, template
216/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000217static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000218getLVForTemplateParameterList(const TemplateParameterList *params) {
219 LinkageInfo LV;
220 for (TemplateParameterList::const_iterator P = params->begin(),
221 PEnd = params->end();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000222 P != PEnd; ++P) {
John McCalldf25c432013-02-16 00:17:33 +0000223
224 // Template type parameters are the most common and never
225 // contribute to visibility, pack or not.
226 if (isa<TemplateTypeParmDecl>(*P))
227 continue;
228
229 // Non-type template parameters can be restricted by the value type, e.g.
230 // template <enum X> class A { ... };
231 // We have to be careful here, though, because we can be dealing with
232 // dependent types.
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000233 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
John McCalldf25c432013-02-16 00:17:33 +0000234 // Handle the non-pack case first.
235 if (!NTTP->isExpandedParameterPack()) {
236 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000237 LV.merge(NTTP->getType()->getLinkageAndVisibility());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000238 }
239 continue;
240 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000241
John McCalldf25c432013-02-16 00:17:33 +0000242 // Look at all the types in an expanded pack.
243 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
244 QualType type = NTTP->getExpansionType(i);
245 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000246 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000247 }
John McCalldf25c432013-02-16 00:17:33 +0000248 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000249 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000250
John McCalldf25c432013-02-16 00:17:33 +0000251 // Template template parameters can be restricted by their
252 // template parameters, recursively.
253 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
254
255 // Handle the non-pack case first.
256 if (!TTP->isExpandedParameterPack()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000257 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
John McCalldf25c432013-02-16 00:17:33 +0000258 continue;
259 }
260
261 // Look at all expansions in an expanded pack.
262 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
263 i != n; ++i) {
264 LV.merge(getLVForTemplateParameterList(
265 TTP->getExpansionTemplateParameters(i)));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000266 }
267 }
268
John McCall457a04e2010-10-22 21:05:15 +0000269 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000270}
271
Rafael Espindola19de5612013-01-12 06:42:30 +0000272/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000273static LinkageInfo getLVForDecl(const NamedDecl *D,
274 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000275
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000276/// \brief Get the most restrictive linkage for the types and
277/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000278///
279/// Note that we don't take an LVComputationKind because we always
280/// want to honor the visibility of template arguments in the same way.
281static LinkageInfo
282getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) {
283 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000284
John McCalldf25c432013-02-16 00:17:33 +0000285 for (unsigned i = 0, e = args.size(); i != e; ++i) {
286 const TemplateArgument &arg = args[i];
287 switch (arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000288 case TemplateArgument::Null:
289 case TemplateArgument::Integral:
290 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000291 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000292
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000293 case TemplateArgument::Type:
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000294 LV.merge(arg.getAsType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000295 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000296
297 case TemplateArgument::Declaration:
John McCalldf25c432013-02-16 00:17:33 +0000298 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
299 assert(!usesTypeVisibility(ND));
300 LV.merge(getLVForDecl(ND, LVForValue));
301 }
302 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000303
304 case TemplateArgument::NullPtr:
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000305 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000306 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000307
308 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000309 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000310 if (TemplateDecl *Template
John McCalldf25c432013-02-16 00:17:33 +0000311 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
312 LV.merge(getLVForDecl(Template, LVForValue));
313 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000314
315 case TemplateArgument::Pack:
John McCalldf25c432013-02-16 00:17:33 +0000316 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray()));
317 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000318 }
John McCalldf25c432013-02-16 00:17:33 +0000319 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000320 }
321
John McCall457a04e2010-10-22 21:05:15 +0000322 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000323}
324
Rafael Espindola2f869a32012-01-14 00:30:36 +0000325static LinkageInfo
John McCalldf25c432013-02-16 00:17:33 +0000326getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) {
327 return getLVForTemplateArgumentList(TArgs.asArray());
John McCall8823c652010-08-13 08:35:10 +0000328}
329
John McCall5f46c482013-02-21 23:42:58 +0000330static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
331 const FunctionTemplateSpecializationInfo *specInfo) {
332 // Include visibility from the template parameters and arguments
333 // only if this is not an explicit instantiation or specialization
334 // with direct explicit visibility. (Implicit instantiations won't
335 // have a direct attribute.)
336 if (!specInfo->isExplicitInstantiationOrSpecialization())
337 return true;
338
339 return !fn->hasAttr<VisibilityAttr>();
340}
341
John McCalldf25c432013-02-16 00:17:33 +0000342/// Merge in template-related linkage and visibility for the given
343/// function template specialization.
344///
345/// We don't need a computation kind here because we can assume
346/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000347///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000348/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000349static void
350mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
351 const FunctionTemplateSpecializationInfo *specInfo) {
352 bool considerVisibility =
353 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000354
355 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000356 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000357 LinkageInfo tempLV =
358 getLVForTemplateParameterList(temp->getTemplateParameters());
359 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
360
361 // Merge information from the template arguments.
362 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
363 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
364 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000365}
366
John McCall5f46c482013-02-21 23:42:58 +0000367/// Does the given declaration have a direct visibility attribute
368/// that would match the given rules?
369static bool hasDirectVisibilityAttribute(const NamedDecl *D,
370 LVComputationKind computation) {
371 switch (computation) {
372 case LVForType:
373 case LVForExplicitType:
374 if (D->hasAttr<TypeVisibilityAttr>())
375 return true;
376 // fallthrough
377 case LVForValue:
378 case LVForExplicitValue:
379 if (D->hasAttr<VisibilityAttr>())
380 return true;
381 return false;
382 }
383 llvm_unreachable("bad visibility computation kind");
384}
385
John McCalld041a9b2013-02-20 01:54:26 +0000386/// Should we consider visibility associated with the template
387/// arguments and parameters of the given class template specialization?
388static bool shouldConsiderTemplateVisibility(
389 const ClassTemplateSpecializationDecl *spec,
390 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000391 // Include visibility from the template parameters and arguments
392 // only if this is not an explicit instantiation or specialization
393 // with direct explicit visibility (and note that implicit
394 // instantiations won't have a direct attribute).
395 //
396 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000397 // for an explicit specialization when computing the visibility of a
398 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000399 //
400 // This is a bit complex; let's unpack it.
401 //
402 // An explicit class specialization is an independent, top-level
403 // declaration. As such, if it or any of its members has an
404 // explicit visibility attribute, that must directly express the
405 // user's intent, and we should honor it. The same logic applies to
406 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000407
408 // Fast path: if this is not an explicit instantiation or
409 // specialization, we always want to consider template-related
410 // visibility restrictions.
411 if (!spec->isExplicitInstantiationOrSpecialization())
412 return true;
413
414 // This is the 'member thereof' check.
415 if (spec->isExplicitSpecialization() &&
416 hasExplicitVisibilityAlready(computation))
417 return false;
418
John McCall5f46c482013-02-21 23:42:58 +0000419 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000420}
421
422/// Merge in template-related linkage and visibility for the given
423/// class template specialization.
424static void mergeTemplateLV(LinkageInfo &LV,
425 const ClassTemplateSpecializationDecl *spec,
426 LVComputationKind computation) {
427 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000428
429 // Merge information from the template parameters, but ignore
430 // visibility if we're only considering template arguments.
431
John McCalld041a9b2013-02-20 01:54:26 +0000432 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000433 LinkageInfo tempLV =
434 getLVForTemplateParameterList(temp->getTemplateParameters());
435 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000436 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000437
438 // Merge information from the template arguments. We ignore
439 // template-argument visibility if we've got an explicit
440 // instantiation with a visibility attribute.
441 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
442 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs);
443 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000444}
445
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000446static bool useInlineVisibilityHidden(const NamedDecl *D) {
447 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000448 const LangOptions &Opts = D->getASTContext().getLangOpts();
449 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000450 return false;
451
452 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
453 if (!FD)
454 return false;
455
456 TemplateSpecializationKind TSK = TSK_Undeclared;
457 if (FunctionTemplateSpecializationInfo *spec
458 = FD->getTemplateSpecializationInfo()) {
459 TSK = spec->getTemplateSpecializationKind();
460 } else if (MemberSpecializationInfo *MSI =
461 FD->getMemberSpecializationInfo()) {
462 TSK = MSI->getTemplateSpecializationKind();
463 }
464
465 const FunctionDecl *Def = 0;
466 // InlineVisibilityHidden only applies to definitions, and
467 // isInlined() only gives meaningful answers on definitions
468 // anyway.
469 return TSK != TSK_ExplicitInstantiationDeclaration &&
470 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000471 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000472}
473
Benjamin Kramer3e350262013-02-15 12:30:38 +0000474template <typename T> static bool isInExternCContext(T *D) {
Rafael Espindolaf4187652013-02-14 01:18:37 +0000475 const T *First = D->getFirstDeclaration();
476 return First->getDeclContext()->isExternCContext();
477}
478
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000479static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000480 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000481 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000482 "Not a name having namespace scope");
483 ASTContext &Context = D->getASTContext();
484
485 // C++ [basic.link]p3:
486 // A name having namespace scope (3.3.6) has internal linkage if it
487 // is the name of
488 // - an object, reference, function or function template that is
489 // explicitly declared static; or,
490 // (This bullet corresponds to C99 6.2.2p3.)
491 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
492 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000493 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000494 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000495
Richard Smithdc0ef452012-10-19 06:37:48 +0000496 // - a non-volatile object or reference that is explicitly declared const
497 // or constexpr and neither explicitly declared extern nor previously
498 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000499 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000500 Var->getType().isConstQualified() &&
501 !Var->getType().isVolatileQualified() &&
John McCall8e7d6562010-08-26 03:08:43 +0000502 Var->getStorageClass() != SC_Extern &&
503 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000504 bool FoundExtern = false;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000505 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000506 PrevVar && !FoundExtern;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000507 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000508 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000509 FoundExtern = true;
510
511 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000512 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000513 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000514 if (Var->getStorageClass() == SC_None) {
Douglas Gregorec9fd132012-01-14 16:38:05 +0000515 const VarDecl *PrevVar = Var->getPreviousDecl();
516 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000517 if (PrevVar->getStorageClass() == SC_PrivateExtern)
518 break;
Eli Friedmana7137bc2012-10-26 23:05:34 +0000519 if (PrevVar)
520 return PrevVar->getLinkageAndVisibility();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000521 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000522 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000523 // C++ [temp]p4:
524 // A non-member function template can have internal linkage; any
525 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000526 const FunctionDecl *Function = 0;
527 if (const FunctionTemplateDecl *FunTmpl
528 = dyn_cast<FunctionTemplateDecl>(D))
529 Function = FunTmpl->getTemplatedDecl();
530 else
531 Function = cast<FunctionDecl>(D);
532
533 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000534 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000535 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000536 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
537 // - a data member of an anonymous union.
538 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000539 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000540 }
541
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000542 if (D->isInAnonymousNamespace()) {
543 const VarDecl *Var = dyn_cast<VarDecl>(D);
544 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Rafael Espindolaf4187652013-02-14 01:18:37 +0000545 if ((!Var || !isInExternCContext(Var)) &&
546 (!Func || !isInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000547 return LinkageInfo::uniqueExternal();
548 }
John McCallb7139c42010-10-28 04:18:25 +0000549
John McCall457a04e2010-10-22 21:05:15 +0000550 // Set up the defaults.
551
552 // C99 6.2.2p5:
553 // If the declaration of an identifier for an object has file
554 // scope and no storage-class specifier, its linkage is
555 // external.
John McCallc273f242010-10-30 11:50:40 +0000556 LinkageInfo LV;
557
John McCalld041a9b2013-02-20 01:54:26 +0000558 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000559 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000560 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000561 } else {
562 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000563 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000564 for (const DeclContext *DC = D->getDeclContext();
565 !isa<TranslationUnitDecl>(DC);
566 DC = DC->getParent()) {
567 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
568 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000569 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000570 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000571 break;
572 }
573 }
574 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000575
John McCalldf25c432013-02-16 00:17:33 +0000576 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000577 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000578 // Use global type/value visibility as appropriate.
579 Visibility globalVisibility;
580 if (computation == LVForValue) {
581 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
582 } else {
583 assert(computation == LVForType);
584 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
585 }
586 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000587
588 // If we're paying attention to global visibility, apply
589 // -finline-visibility-hidden if this is an inline method.
590 if (useInlineVisibilityHidden(D))
591 LV.mergeVisibility(HiddenVisibility, true);
592 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000593 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000594
Douglas Gregorf73b2822009-11-25 22:24:25 +0000595 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000596
Douglas Gregorf73b2822009-11-25 22:24:25 +0000597 // A name having namespace scope has external linkage if it is the
598 // name of
599 //
600 // - an object or reference, unless it has internal linkage; or
601 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000602 // GCC applies the following optimization to variables and static
603 // data members, but not to functions:
604 //
John McCall457a04e2010-10-22 21:05:15 +0000605 // Modify the variable's LV by the LV of its type unless this is
606 // C or extern "C". This follows from [basic.link]p9:
607 // A type without linkage shall not be used as the type of a
608 // variable or function with external linkage unless
609 // - the entity has C language linkage, or
610 // - the entity is declared within an unnamed namespace, or
611 // - the entity is not used or is defined in the same
612 // translation unit.
613 // and [basic.link]p10:
614 // ...the types specified by all declarations referring to a
615 // given variable or function shall be identical...
616 // C does not have an equivalent rule.
617 //
John McCall5fe84122010-10-26 04:59:26 +0000618 // Ignore this if we've got an explicit attribute; the user
619 // probably knows what they're doing.
620 //
John McCall457a04e2010-10-22 21:05:15 +0000621 // Note that we don't want to make the variable non-external
622 // because of this, but unique-external linkage suits us.
Rafael Espindolab22b91c2013-03-12 15:22:39 +0000623 if (Context.getLangOpts().CPlusPlus && !isInExternCContext(Var)) {
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000624 LinkageInfo TypeLV = Var->getType()->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000625 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000626 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000627 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000628 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000629 }
630
John McCall23032652010-11-02 18:38:13 +0000631 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000632 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000633
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000634 // Note that Sema::MergeVarDecl already takes care of implementing
635 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
636 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000637
Douglas Gregorf73b2822009-11-25 22:24:25 +0000638 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000639 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000640 // In theory, we can modify the function's LV by the LV of its
641 // type unless it has C linkage (see comment above about variables
642 // for justification). In practice, GCC doesn't do this, so it's
643 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000644
John McCall23032652010-11-02 18:38:13 +0000645 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000646 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000647
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000648 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
649 // merging storage classes and visibility attributes, so we don't have to
650 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000651
John McCallf768aa72011-02-10 06:50:24 +0000652 // In C++, then if the type of the function uses a type with
653 // unique-external linkage, it's not legally usable from outside
654 // this translation unit. However, we should use the C linkage
655 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000656 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000657 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000658 Function->getType()->getLinkage() == UniqueExternalLinkage)
659 return LinkageInfo::uniqueExternal();
660
John McCall5f46c482013-02-21 23:42:58 +0000661 // Consider LV from the template and the template arguments.
662 // We're at file scope, so we do not need to worry about nested
663 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000664 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000665 = Function->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000666 mergeTemplateLV(LV, Function, specInfo);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000667 }
668
Douglas Gregorf73b2822009-11-25 22:24:25 +0000669 // - a named class (Clause 9), or an unnamed class defined in a
670 // typedef declaration in which the class has the typedef name
671 // for linkage purposes (7.1.3); or
672 // - a named enumeration (7.2), or an unnamed enumeration
673 // defined in a typedef declaration in which the enumeration
674 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000675 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
676 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000677 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000678 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000679
John McCall457a04e2010-10-22 21:05:15 +0000680 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000681 // linkage of the template and template arguments. We're at file
682 // scope, so we do not need to worry about nested specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000683 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000684 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000685 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000686 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000687
688 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000689 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000690 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000691 computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000692 if (!isExternalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000693 return LinkageInfo::none();
694 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000695
696 // - a template, unless it is a function template that has
697 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000698 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000699 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000700 LinkageInfo tempLV =
701 getLVForTemplateParameterList(temp->getTemplateParameters());
702 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
703
Douglas Gregorf73b2822009-11-25 22:24:25 +0000704 // - a namespace (7.3), unless it is declared within an unnamed
705 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000706 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
707 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000708
John McCall457a04e2010-10-22 21:05:15 +0000709 // By extension, we assign external linkage to Objective-C
710 // interfaces.
711 } else if (isa<ObjCInterfaceDecl>(D)) {
712 // fallout
713
714 // Everything not covered here has no linkage.
715 } else {
John McCallc273f242010-10-30 11:50:40 +0000716 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000717 }
718
719 // If we ended up with non-external linkage, visibility should
720 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000721 if (LV.getLinkage() != ExternalLinkage)
722 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000723
John McCall457a04e2010-10-22 21:05:15 +0000724 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000725}
726
John McCalldf25c432013-02-16 00:17:33 +0000727static LinkageInfo getLVForClassMember(const NamedDecl *D,
728 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000729 // Only certain class members have linkage. Note that fields don't
730 // really have linkage, but it's convenient to say they do for the
731 // purposes of calculating linkage of pointer-to-data-member
732 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000733 if (!(isa<CXXMethodDecl>(D) ||
734 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000735 isa<FieldDecl>(D) ||
David Blaikie095deba2012-11-14 01:52:05 +0000736 isa<TagDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000737 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000738
John McCall07072662010-11-02 01:45:15 +0000739 LinkageInfo LV;
740
John McCall07072662010-11-02 01:45:15 +0000741 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000742 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000743 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000744 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000745 // If we're paying attention to global visibility, apply
746 // -finline-visibility-hidden if this is an inline method.
747 //
748 // Note that we do this before merging information about
749 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000750 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000751 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000752 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000753
754 // If this class member has an explicit visibility attribute, the only
755 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000756 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000757 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000758 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000759 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000760
John McCall5f46c482013-02-21 23:42:58 +0000761 LinkageInfo classLV =
762 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000763 if (!isExternalLinkage(classLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000764 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000765
766 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000767 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000768 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000769
John McCall5f46c482013-02-21 23:42:58 +0000770 // Otherwise, don't merge in classLV yet, because in certain cases
771 // we need to completely ignore the visibility from it.
772
773 // Specifically, if this decl exists and has an explicit attribute.
774 const NamedDecl *explicitSpecSuppressor = 0;
775
John McCall8823c652010-08-13 08:35:10 +0000776 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000777 // If the type of the function uses a type with unique-external
778 // linkage, it's not legally usable from outside this translation unit.
779 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
780 return LinkageInfo::uniqueExternal();
781
John McCall457a04e2010-10-22 21:05:15 +0000782 // If this is a method template specialization, use the linkage for
783 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000784 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000785 = MD->getTemplateSpecializationInfo()) {
John McCalldf25c432013-02-16 00:17:33 +0000786 mergeTemplateLV(LV, MD, spec);
John McCall5f46c482013-02-21 23:42:58 +0000787 if (spec->isExplicitSpecialization()) {
788 explicitSpecSuppressor = MD;
789 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
790 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
791 }
792 } else if (isExplicitMemberSpecialization(MD)) {
793 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000794 }
John McCall457a04e2010-10-22 21:05:15 +0000795
John McCall37bb6c92010-10-29 22:22:43 +0000796 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000797 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000798 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000799 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000800 if (spec->isExplicitSpecialization()) {
801 explicitSpecSuppressor = spec;
802 } else {
803 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
804 if (isExplicitMemberSpecialization(temp)) {
805 explicitSpecSuppressor = temp->getTemplatedDecl();
806 }
807 }
808 } else if (isExplicitMemberSpecialization(RD)) {
809 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000810 }
811
John McCall37bb6c92010-10-29 22:22:43 +0000812 // Static data members.
813 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000814 // Modify the variable's linkage by its type, but ignore the
815 // type's visibility unless it's a definition.
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000816 LinkageInfo typeLV = VD->getType()->getLinkageAndVisibility();
John McCall5f46c482013-02-21 23:42:58 +0000817 LV.mergeMaybeWithVisibility(typeLV,
Rafael Espindola4a5da442013-02-27 02:56:45 +0000818 !LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit());
John McCall5f46c482013-02-21 23:42:58 +0000819
820 if (isExplicitMemberSpecialization(VD)) {
821 explicitSpecSuppressor = VD;
822 }
John McCalldf25c432013-02-16 00:17:33 +0000823
824 // Template members.
825 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
826 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000827 (!LV.isVisibilityExplicit() &&
828 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000829 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000830 LinkageInfo tempLV =
831 getLVForTemplateParameterList(temp->getTemplateParameters());
832 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000833
834 if (const RedeclarableTemplateDecl *redeclTemp =
835 dyn_cast<RedeclarableTemplateDecl>(temp)) {
836 if (isExplicitMemberSpecialization(redeclTemp)) {
837 explicitSpecSuppressor = temp->getTemplatedDecl();
838 }
839 }
John McCall37bb6c92010-10-29 22:22:43 +0000840 }
841
John McCall5f46c482013-02-21 23:42:58 +0000842 // We should never be looking for an attribute directly on a template.
843 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
844
845 // If this member is an explicit member specialization, and it has
846 // an explicit attribute, ignore visibility from the parent.
847 bool considerClassVisibility = true;
848 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000849 // optimization: hasDVA() is true only with explicit visibility.
850 LV.isVisibilityExplicit() &&
851 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000852 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
853 considerClassVisibility = false;
854 }
855
856 // Finally, merge in information from the class.
857 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000858 return LV;
John McCall8823c652010-08-13 08:35:10 +0000859}
860
John McCalld396b972011-02-08 19:01:05 +0000861static void clearLinkageForClass(const CXXRecordDecl *record) {
862 for (CXXRecordDecl::decl_iterator
863 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
864 Decl *child = *i;
865 if (isa<NamedDecl>(child))
Rafael Espindola19de5612013-01-12 06:42:30 +0000866 cast<NamedDecl>(child)->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000867 }
868}
869
David Blaikie68e081d2011-12-20 02:48:34 +0000870void NamedDecl::anchor() { }
871
Rafael Espindola19de5612013-01-12 06:42:30 +0000872void NamedDecl::ClearLinkageCache() {
John McCalld396b972011-02-08 19:01:05 +0000873 // Note that we can't skip clearing the linkage of children just
874 // because the parent doesn't have cached linkage: we don't cache
875 // when computing linkage for parent contexts.
876
Rafael Espindola19de5612013-01-12 06:42:30 +0000877 HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000878
879 // If we're changing the linkage of a class, we need to reset the
880 // linkage of child declarations, too.
881 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
882 clearLinkageForClass(record);
883
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000884 if (ClassTemplateDecl *temp = dyn_cast<ClassTemplateDecl>(this)) {
John McCalld396b972011-02-08 19:01:05 +0000885 // Clear linkage for the template pattern.
886 CXXRecordDecl *record = temp->getTemplatedDecl();
Rafael Espindola19de5612013-01-12 06:42:30 +0000887 record->HasCachedLinkage = 0;
John McCalld396b972011-02-08 19:01:05 +0000888 clearLinkageForClass(record);
889
John McCall83779672011-02-19 02:53:41 +0000890 // We need to clear linkage for specializations, too.
891 for (ClassTemplateDecl::spec_iterator
892 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000893 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000894 }
John McCall83779672011-02-19 02:53:41 +0000895
896 // Clear cached linkage for function template decls, too.
Dmitri Gribenkofb04e1b2013-02-03 16:10:26 +0000897 if (FunctionTemplateDecl *temp = dyn_cast<FunctionTemplateDecl>(this)) {
Rafael Espindola19de5612013-01-12 06:42:30 +0000898 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000899 for (FunctionTemplateDecl::spec_iterator
900 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
Rafael Espindola19de5612013-01-12 06:42:30 +0000901 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000902 }
John McCall83779672011-02-19 02:53:41 +0000903
John McCalld396b972011-02-08 19:01:05 +0000904}
905
Douglas Gregorbf62d642010-12-06 18:36:25 +0000906Linkage NamedDecl::getLinkage() const {
Richard Smith88581592013-02-12 05:48:23 +0000907 if (HasCachedLinkage)
Rafael Espindola19de5612013-01-12 06:42:30 +0000908 return Linkage(CachedLinkage);
Rafael Espindola19de5612013-01-12 06:42:30 +0000909
John McCalld041a9b2013-02-20 01:54:26 +0000910 // We don't care about visibility here, so ask for the cheapest
911 // possible visibility analysis.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000912 CachedLinkage = getLVForDecl(this, LVForExplicitValue).getLinkage();
Rafael Espindola19de5612013-01-12 06:42:30 +0000913 HasCachedLinkage = 1;
914
915#ifndef NDEBUG
916 verifyLinkage();
917#endif
918
919 return Linkage(CachedLinkage);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000920}
921
John McCallc273f242010-10-30 11:50:40 +0000922LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +0000923 LVComputationKind computation =
924 (usesTypeVisibility(this) ? LVForType : LVForValue);
925 LinkageInfo LI = getLVForDecl(this, computation);
Rafael Espindola19de5612013-01-12 06:42:30 +0000926 if (HasCachedLinkage) {
Rafael Espindola4a5da442013-02-27 02:56:45 +0000927 assert(Linkage(CachedLinkage) == LI.getLinkage());
Rafael Espindola19de5612013-01-12 06:42:30 +0000928 return LI;
Rafael Espindola54606d52012-12-25 07:31:49 +0000929 }
Rafael Espindola19de5612013-01-12 06:42:30 +0000930 HasCachedLinkage = 1;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000931 CachedLinkage = LI.getLinkage();
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000932
933#ifndef NDEBUG
Rafael Espindola19de5612013-01-12 06:42:30 +0000934 verifyLinkage();
935#endif
936
937 return LI;
938}
939
940void NamedDecl::verifyLinkage() const {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000941 // In C (because of gnu inline) and in c++ with microsoft extensions an
942 // static can follow an extern, so we can have two decls with different
943 // linkages.
944 const LangOptions &Opts = getASTContext().getLangOpts();
945 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
Rafael Espindola19de5612013-01-12 06:42:30 +0000946 return;
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000947
948 // We have just computed the linkage for this decl. By induction we know
949 // that all other computed linkages match, check that the one we just computed
950 // also does.
951 NamedDecl *D = NULL;
952 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
953 NamedDecl *T = cast<NamedDecl>(*I);
954 if (T == this)
955 continue;
Rafael Espindola19de5612013-01-12 06:42:30 +0000956 if (T->HasCachedLinkage != 0) {
Rafael Espindola3c98afe2013-01-05 01:28:37 +0000957 D = T;
958 break;
959 }
960 }
961 assert(!D || D->CachedLinkage == CachedLinkage);
John McCall033caa52010-10-29 00:29:13 +0000962}
Ted Kremenek926d8602010-04-20 23:15:35 +0000963
David Blaikie05785d12013-02-20 22:23:23 +0000964Optional<Visibility>
John McCalld041a9b2013-02-20 01:54:26 +0000965NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
Rafael Espindola3a52c442013-02-26 19:33:14 +0000966 // Check the declaration itself first.
967 if (Optional<Visibility> V = getVisibilityOf(this, kind))
968 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000969
Rafael Espindola3a52c442013-02-26 19:33:14 +0000970 // If this is a member class of a specialization of a class template
971 // and the corresponding decl has explicit visibility, use that.
972 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
973 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
974 if (InstantiatedFrom)
975 return getVisibilityOf(InstantiatedFrom, kind);
976 }
977
978 // If there wasn't explicit visibility there, and this is a
979 // specialization of a class template, check for visibility
980 // on the pattern.
981 if (const ClassTemplateSpecializationDecl *spec
982 = dyn_cast<ClassTemplateSpecializationDecl>(this))
983 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
984 kind);
985
986 // Use the most recent declaration.
987 const NamedDecl *MostRecent = cast<NamedDecl>(this->getMostRecentDecl());
988 if (MostRecent != this)
989 return MostRecent->getExplicitVisibility(kind);
990
991 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
Rafael Espindola96e68242012-05-16 02:10:38 +0000992 if (Var->isStaticDataMember()) {
993 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
994 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +0000995 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +0000996 }
997
David Blaikie7a30dc52013-02-21 01:47:18 +0000998 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +0000999 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001000 // Also handle function template specializations.
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001001 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001002 // If the function is a specialization of a template with an
1003 // explicit visibility attribute, use that.
1004 if (FunctionTemplateSpecializationInfo *templateInfo
1005 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001006 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1007 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001008
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001009 // If the function is a member of a specialization of a class template
1010 // and the corresponding decl has explicit visibility, use that.
1011 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1012 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001013 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001014
David Blaikie7a30dc52013-02-21 01:47:18 +00001015 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001016 }
1017
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001018 // The visibility of a template is stored in the templated decl.
1019 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this))
John McCalld041a9b2013-02-20 01:54:26 +00001020 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001021
David Blaikie7a30dc52013-02-21 01:47:18 +00001022 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001023}
1024
John McCalldf25c432013-02-16 00:17:33 +00001025static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1026 LVComputationKind computation) {
1027 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1028 if (Function->isInAnonymousNamespace() &&
1029 !Function->getDeclContext()->isExternCContext())
1030 return LinkageInfo::uniqueExternal();
1031
1032 // This is a "void f();" which got merged with a file static.
1033 if (Function->getStorageClass() == SC_Static)
1034 return LinkageInfo::internal();
1035
1036 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001037 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001038 if (Optional<Visibility> Vis =
1039 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001040 LV.mergeVisibility(*Vis, true);
1041 }
1042
1043 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1044 // merging storage classes and visibility attributes, so we don't have to
1045 // look at previous decls in here.
1046
1047 return LV;
1048 }
1049
1050 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola8f326a52013-03-07 01:42:44 +00001051 if (Var->hasExternalStorageAsWritten()) {
John McCalldf25c432013-02-16 00:17:33 +00001052 if (Var->isInAnonymousNamespace() &&
1053 !Var->getDeclContext()->isExternCContext())
1054 return LinkageInfo::uniqueExternal();
1055
1056 // This is an "extern int foo;" which got merged with a file static.
1057 if (Var->getStorageClass() == SC_Static)
1058 return LinkageInfo::internal();
1059
1060 LinkageInfo LV;
1061 if (Var->getStorageClass() == SC_PrivateExtern)
1062 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001063 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001064 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001065 LV.mergeVisibility(*Vis, true);
1066 }
1067
1068 // Note that Sema::MergeVarDecl already takes care of implementing
1069 // C99 6.2.2p4 and propagating the visibility attribute, so we don't
1070 // have to do it here.
1071 return LV;
1072 }
1073 }
1074
1075 return LinkageInfo::none();
1076}
1077
1078static LinkageInfo getLVForDecl(const NamedDecl *D,
1079 LVComputationKind computation) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001080 // Objective-C: treat all Objective-C declarations as having external
1081 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001082 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001083 default:
1084 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001085 case Decl::ParmVar:
1086 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001087 case Decl::TemplateTemplateParm: // count these as external
1088 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001089 case Decl::ObjCAtDefsField:
1090 case Decl::ObjCCategory:
1091 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001092 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001093 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001094 case Decl::ObjCMethod:
1095 case Decl::ObjCProperty:
1096 case Decl::ObjCPropertyImpl:
1097 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001098 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001099
1100 case Decl::CXXRecord: {
1101 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1102 if (Record->isLambda()) {
1103 if (!Record->getLambdaManglingNumber()) {
1104 // This lambda has no mangling number, so it's internal.
1105 return LinkageInfo::internal();
1106 }
1107
1108 // This lambda has its linkage/visibility determined by its owner.
1109 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
1110 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
1111 if (isa<ParmVarDecl>(ContextDecl))
1112 DC = ContextDecl->getDeclContext()->getRedeclContext();
1113 else
John McCalldf25c432013-02-16 00:17:33 +00001114 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001115 }
1116
1117 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
John McCalldf25c432013-02-16 00:17:33 +00001118 return getLVForDecl(ND, computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001119
1120 return LinkageInfo::external();
1121 }
1122
1123 break;
1124 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001125 }
1126
Douglas Gregorf73b2822009-11-25 22:24:25 +00001127 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001128 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001129 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001130
1131 // C++ [basic.link]p5:
1132 // In addition, a member function, static data member, a named
1133 // class or enumeration of class scope, or an unnamed class or
1134 // enumeration defined in a class-scope typedef declaration such
1135 // that the class or enumeration has the typedef name for linkage
1136 // purposes (7.1.3), has external linkage if the name of the class
1137 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001138 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001139 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001140
1141 // C++ [basic.link]p6:
1142 // The name of a function declared in block scope and the name of
1143 // an object declared by a block scope extern declaration have
1144 // linkage. If there is a visible declaration of an entity with
1145 // linkage having the same name and type, ignoring entities
1146 // declared outside the innermost enclosing namespace scope, the
1147 // block scope declaration declares that same entity and receives
1148 // the linkage of the previous declaration. If there is more than
1149 // one such matching entity, the program is ill-formed. Otherwise,
1150 // if no matching entity is found, the block scope entity receives
1151 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001152 if (D->getDeclContext()->isFunctionOrMethod())
1153 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001154
1155 // C++ [basic.link]p6:
1156 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001157 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001158}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001159
Douglas Gregor2ada0482009-02-04 17:27:36 +00001160std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregor78254c82012-03-27 23:34:16 +00001161 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson2fb08242009-09-08 18:24:21 +00001162}
1163
1164std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001165 std::string QualName;
1166 llvm::raw_string_ostream OS(QualName);
1167 printQualifiedName(OS, P);
1168 return OS.str();
1169}
1170
1171void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1172 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1173}
1174
1175void NamedDecl::printQualifiedName(raw_ostream &OS,
1176 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001177 const DeclContext *Ctx = getDeclContext();
1178
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001179 if (Ctx->isFunctionOrMethod()) {
1180 printName(OS);
1181 return;
1182 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001183
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001184 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001185 ContextsTy Contexts;
1186
1187 // Collect contexts.
1188 while (Ctx && isa<NamedDecl>(Ctx)) {
1189 Contexts.push_back(Ctx);
1190 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001191 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001192
1193 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1194 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001195 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001196 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001197 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001198 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001199 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1200 TemplateArgs.data(),
1201 TemplateArgs.size(),
1202 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001203 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +00001204 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001205 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +00001206 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001207 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001208 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1209 if (!RD->getIdentifier())
1210 OS << "<anonymous " << RD->getKindName() << '>';
1211 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001212 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001213 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +00001214 const FunctionProtoType *FT = 0;
1215 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001216 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001217
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001218 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001219 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001220 unsigned NumParams = FD->getNumParams();
1221 for (unsigned i = 0; i < NumParams; ++i) {
1222 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001223 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001224 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001225 }
1226
1227 if (FT->isVariadic()) {
1228 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001229 OS << ", ";
1230 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001231 }
1232 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001233 OS << ')';
1234 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001235 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001236 }
1237 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001238 }
1239
John McCalla2a3f7d2010-03-16 21:48:18 +00001240 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001241 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001242 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001243 OS << "<anonymous>";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001244}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001245
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001246void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1247 const PrintingPolicy &Policy,
1248 bool Qualified) const {
1249 if (Qualified)
1250 printQualifiedName(OS, Policy);
1251 else
1252 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001253}
1254
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001255bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001256 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1257
Douglas Gregor889ceb72009-02-03 19:21:40 +00001258 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1259 // We want to keep it, unless it nominates same namespace.
1260 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +00001261 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1262 ->getOriginalNamespace() ==
1263 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1264 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +00001265 }
Mike Stump11289f42009-09-09 15:08:12 +00001266
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001267 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1268 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +00001269 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001270
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001271 // For function templates, the underlying function declarations are linked.
1272 if (const FunctionTemplateDecl *FunctionTemplate
1273 = dyn_cast<FunctionTemplateDecl>(this))
1274 if (const FunctionTemplateDecl *OldFunctionTemplate
1275 = dyn_cast<FunctionTemplateDecl>(OldD))
1276 return FunctionTemplate->getTemplatedDecl()
1277 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001278
Steve Naroffc4173fa2009-02-22 19:35:57 +00001279 // For method declarations, we keep track of redeclarations.
1280 if (isa<ObjCMethodDecl>(this))
1281 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001282
John McCall9f3059a2009-10-09 21:13:30 +00001283 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1284 return true;
1285
John McCall3f746822009-11-17 05:59:44 +00001286 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1287 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1288 cast<UsingShadowDecl>(OldD)->getTargetDecl();
1289
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001290 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1291 ASTContext &Context = getASTContext();
1292 return Context.getCanonicalNestedNameSpecifier(
1293 cast<UsingDecl>(this)->getQualifier()) ==
1294 Context.getCanonicalNestedNameSpecifier(
1295 cast<UsingDecl>(OldD)->getQualifier());
1296 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +00001297
Douglas Gregorb59643b2012-01-03 23:26:26 +00001298 // A typedef of an Objective-C class type can replace an Objective-C class
1299 // declaration or definition, and vice versa.
1300 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1301 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1302 return true;
1303
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001304 // For non-function declarations, if the declarations are of the
1305 // same kind then this must be a redeclaration, or semantic analysis
1306 // would not have given us the new declaration.
1307 return this->getKind() == OldD->getKind();
1308}
1309
Douglas Gregoreddf4332009-02-24 20:03:32 +00001310bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +00001311 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001312}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001313
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001314NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001315 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001316 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1317 ND = UD->getTargetDecl();
1318
1319 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1320 return AD->getClassInterface();
1321
1322 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001323}
1324
John McCalla8ae2222010-04-06 21:38:20 +00001325bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001326 if (!isCXXClassMember())
1327 return false;
1328
John McCalla8ae2222010-04-06 21:38:20 +00001329 const NamedDecl *D = this;
1330 if (isa<UsingShadowDecl>(D))
1331 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1332
Francois Pichet783dd6e2010-11-21 06:08:52 +00001333 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001334 return true;
1335 if (isa<CXXMethodDecl>(D))
1336 return cast<CXXMethodDecl>(D)->isInstance();
1337 if (isa<FunctionTemplateDecl>(D))
1338 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1339 ->getTemplatedDecl())->isInstance();
1340 return false;
1341}
1342
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001343//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001344// DeclaratorDecl Implementation
1345//===----------------------------------------------------------------------===//
1346
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001347template <typename DeclT>
1348static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1349 if (decl->getNumTemplateParameterLists() > 0)
1350 return decl->getTemplateParameterList(0)->getTemplateLoc();
1351 else
1352 return decl->getInnerLocStart();
1353}
1354
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001355SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001356 TypeSourceInfo *TSI = getTypeSourceInfo();
1357 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001358 return SourceLocation();
1359}
1360
Douglas Gregor14454802011-02-25 02:25:35 +00001361void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1362 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001363 // Make sure the extended decl info is allocated.
1364 if (!hasExtInfo()) {
1365 // Save (non-extended) type source info pointer.
1366 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1367 // Allocate external info struct.
1368 DeclInfo = new (getASTContext()) ExtInfo;
1369 // Restore savedTInfo into (extended) decl info.
1370 getExtInfo()->TInfo = savedTInfo;
1371 }
1372 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001373 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001374 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001375 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001376 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001377 if (getExtInfo()->NumTemplParamLists == 0) {
1378 // Save type source info pointer.
1379 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1380 // Deallocate the extended decl info.
1381 getASTContext().Deallocate(getExtInfo());
1382 // Restore savedTInfo into (non-extended) decl info.
1383 DeclInfo = savedTInfo;
1384 }
1385 else
1386 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001387 }
1388 }
1389}
1390
Abramo Bagnara60804e12011-03-18 15:16:37 +00001391void
1392DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1393 unsigned NumTPLists,
1394 TemplateParameterList **TPLists) {
1395 assert(NumTPLists > 0);
1396 // Make sure the extended decl info is allocated.
1397 if (!hasExtInfo()) {
1398 // Save (non-extended) type source info pointer.
1399 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1400 // Allocate external info struct.
1401 DeclInfo = new (getASTContext()) ExtInfo;
1402 // Restore savedTInfo into (extended) decl info.
1403 getExtInfo()->TInfo = savedTInfo;
1404 }
1405 // Set the template parameter lists info.
1406 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1407}
1408
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001409SourceLocation DeclaratorDecl::getOuterLocStart() const {
1410 return getTemplateOrInnerLocStart(this);
1411}
1412
Abramo Bagnaraea947882011-03-08 16:41:52 +00001413namespace {
1414
1415// Helper function: returns true if QT is or contains a type
1416// having a postfix component.
1417bool typeIsPostfix(clang::QualType QT) {
1418 while (true) {
1419 const Type* T = QT.getTypePtr();
1420 switch (T->getTypeClass()) {
1421 default:
1422 return false;
1423 case Type::Pointer:
1424 QT = cast<PointerType>(T)->getPointeeType();
1425 break;
1426 case Type::BlockPointer:
1427 QT = cast<BlockPointerType>(T)->getPointeeType();
1428 break;
1429 case Type::MemberPointer:
1430 QT = cast<MemberPointerType>(T)->getPointeeType();
1431 break;
1432 case Type::LValueReference:
1433 case Type::RValueReference:
1434 QT = cast<ReferenceType>(T)->getPointeeType();
1435 break;
1436 case Type::PackExpansion:
1437 QT = cast<PackExpansionType>(T)->getPattern();
1438 break;
1439 case Type::Paren:
1440 case Type::ConstantArray:
1441 case Type::DependentSizedArray:
1442 case Type::IncompleteArray:
1443 case Type::VariableArray:
1444 case Type::FunctionProto:
1445 case Type::FunctionNoProto:
1446 return true;
1447 }
1448 }
1449}
1450
1451} // namespace
1452
1453SourceRange DeclaratorDecl::getSourceRange() const {
1454 SourceLocation RangeEnd = getLocation();
1455 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1456 if (typeIsPostfix(TInfo->getType()))
1457 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1458 }
1459 return SourceRange(getOuterLocStart(), RangeEnd);
1460}
1461
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001462void
Douglas Gregor20527e22010-06-15 17:44:38 +00001463QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1464 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001465 TemplateParameterList **TPLists) {
1466 assert((NumTPLists == 0 || TPLists != 0) &&
1467 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001468
1469 // Free previous template parameters (if any).
1470 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001471 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001472 TemplParamLists = 0;
1473 NumTemplParamLists = 0;
1474 }
1475 // Set info on matched template parameter lists (if any).
1476 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001477 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001478 NumTemplParamLists = NumTPLists;
1479 for (unsigned i = NumTPLists; i-- > 0; )
1480 TemplParamLists[i] = TPLists[i];
1481 }
1482}
1483
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001484//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001485// VarDecl Implementation
1486//===----------------------------------------------------------------------===//
1487
Sebastian Redl833ef452010-01-26 22:01:41 +00001488const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1489 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001490 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001491 case SC_Auto: return "auto";
1492 case SC_Extern: return "extern";
1493 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1494 case SC_PrivateExtern: return "__private_extern__";
1495 case SC_Register: return "register";
1496 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001497 }
1498
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001499 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001500}
1501
Abramo Bagnaradff19302011-03-08 08:55:46 +00001502VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1503 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001504 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001505 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001506 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001507}
1508
Douglas Gregor72172e92012-01-05 21:55:30 +00001509VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1510 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1511 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1512 QualType(), 0, SC_None, SC_None);
1513}
1514
Douglas Gregorbf62d642010-12-06 18:36:25 +00001515void VarDecl::setStorageClass(StorageClass SC) {
1516 assert(isLegalForVariable(SC));
1517 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00001518 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001519
John McCallbeaa11c2011-05-01 02:13:58 +00001520 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001521}
1522
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001523SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001524 if (const Expr *Init = getInit()) {
1525 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001526 // If Init is implicit, ignore its source range and fallback on
1527 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1528 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001529 return SourceRange(getOuterLocStart(), InitEnd);
1530 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001531 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001532}
1533
Rafael Espindola88510672013-01-04 21:18:45 +00001534template<typename T>
Rafael Espindolaf4187652013-02-14 01:18:37 +00001535static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001536 // C++ [dcl.link]p1: All function types, function names with external linkage,
1537 // and variable names with external linkage have a language linkage.
1538 if (!isExternalLinkage(D.getLinkage()))
1539 return NoLanguageLinkage;
1540
1541 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001542 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001543 ASTContext &Context = D.getASTContext();
1544 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001545 return CLanguageLinkage;
1546
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001547 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1548 // language linkage of the names of class members and the function type of
1549 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001550 const DeclContext *DC = D.getDeclContext();
1551 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001552 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001553
1554 // If the first decl is in an extern "C" context, any other redeclaration
1555 // will have C language linkage. If the first one is not in an extern "C"
1556 // context, we would have reported an error for any other decl being in one.
Rafael Espindola88510672013-01-04 21:18:45 +00001557 const T *First = D.getFirstDeclaration();
Rafael Espindolaf4187652013-02-14 01:18:37 +00001558 if (First->getDeclContext()->isExternCContext())
1559 return CLanguageLinkage;
1560 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001561}
1562
Rafael Espindolaf4187652013-02-14 01:18:37 +00001563LanguageLinkage VarDecl::getLanguageLinkage() const {
1564 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001565}
1566
Sebastian Redl833ef452010-01-26 22:01:41 +00001567VarDecl *VarDecl::getCanonicalDecl() {
1568 return getFirstDeclaration();
1569}
1570
Daniel Dunbar9d355812012-03-09 01:51:51 +00001571VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1572 ASTContext &C) const
1573{
Sebastian Redl35351a92010-01-31 22:27:38 +00001574 // C++ [basic.def]p2:
1575 // A declaration is a definition unless [...] it contains the 'extern'
1576 // specifier or a linkage-specification and neither an initializer [...],
1577 // it declares a static data member in a class declaration [...].
1578 // C++ [temp.expl.spec]p15:
1579 // An explicit specialization of a static data member of a template is a
1580 // definition if the declaration includes an initializer; otherwise, it is
1581 // a declaration.
1582 if (isStaticDataMember()) {
1583 if (isOutOfLine() && (hasInit() ||
1584 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1585 return Definition;
1586 else
1587 return DeclarationOnly;
1588 }
1589 // C99 6.7p5:
1590 // A definition of an identifier is a declaration for that identifier that
1591 // [...] causes storage to be reserved for that object.
1592 // Note: that applies for all non-file-scope objects.
1593 // C99 6.9.2p1:
1594 // If the declaration of an identifier for an object has file scope and an
1595 // initializer, the declaration is an external definition for the identifier
1596 if (hasInit())
1597 return Definition;
1598 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1599 if (hasExternalStorage())
1600 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001601
1602 if (hasExternalStorageAsWritten()) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001603 for (const VarDecl *PrevVar = getPreviousDecl();
1604 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Rafael Espindola7581f322012-12-17 22:23:47 +00001605 if (PrevVar->getLinkage() == InternalLinkage)
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001606 return DeclarationOnly;
1607 }
1608 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001609 // C99 6.9.2p2:
1610 // A declaration of an object that has file scope without an initializer,
1611 // and without a storage class specifier or the scs 'static', constitutes
1612 // a tentative definition.
1613 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001614 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001615 return TentativeDefinition;
1616
1617 // What's left is (in C, block-scope) declarations without initializers or
1618 // external storage. These are definitions.
1619 return Definition;
1620}
1621
Sebastian Redl35351a92010-01-31 22:27:38 +00001622VarDecl *VarDecl::getActingDefinition() {
1623 DefinitionKind Kind = isThisDeclarationADefinition();
1624 if (Kind != TentativeDefinition)
1625 return 0;
1626
Chris Lattner48eb14d2010-06-14 18:31:46 +00001627 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001628 VarDecl *First = getFirstDeclaration();
1629 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1630 I != E; ++I) {
1631 Kind = (*I)->isThisDeclarationADefinition();
1632 if (Kind == Definition)
1633 return 0;
1634 else if (Kind == TentativeDefinition)
1635 LastTentative = *I;
1636 }
1637 return LastTentative;
1638}
1639
1640bool VarDecl::isTentativeDefinitionNow() const {
1641 DefinitionKind Kind = isThisDeclarationADefinition();
1642 if (Kind != TentativeDefinition)
1643 return false;
1644
1645 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1646 if ((*I)->isThisDeclarationADefinition() == Definition)
1647 return false;
1648 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001649 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001650}
1651
Daniel Dunbar9d355812012-03-09 01:51:51 +00001652VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001653 VarDecl *First = getFirstDeclaration();
1654 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1655 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001656 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl5ca79842010-02-01 20:16:42 +00001657 return *I;
1658 }
1659 return 0;
1660}
1661
Daniel Dunbar9d355812012-03-09 01:51:51 +00001662VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001663 DefinitionKind Kind = DeclarationOnly;
1664
1665 const VarDecl *First = getFirstDeclaration();
1666 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001667 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001668 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001669 if (Kind == Definition)
1670 break;
1671 }
John McCall37bb6c92010-10-29 22:22:43 +00001672
1673 return Kind;
1674}
1675
Sebastian Redl5ca79842010-02-01 20:16:42 +00001676const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001677 redecl_iterator I = redecls_begin(), E = redecls_end();
1678 while (I != E && !I->getInit())
1679 ++I;
1680
1681 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001682 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001683 return I->getInit();
1684 }
1685 return 0;
1686}
1687
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001688bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001689 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001690 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001691
1692 if (!isStaticDataMember())
1693 return false;
1694
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001695 // If this static data member was instantiated from a static data member of
1696 // a class template, check whether that static data member was defined
1697 // out-of-line.
1698 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1699 return VD->isOutOfLine();
1700
1701 return false;
1702}
1703
Douglas Gregor1d957a32009-10-27 18:42:08 +00001704VarDecl *VarDecl::getOutOfLineDefinition() {
1705 if (!isStaticDataMember())
1706 return 0;
1707
1708 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1709 RD != RDEnd; ++RD) {
1710 if (RD->getLexicalDeclContext()->isFileContext())
1711 return *RD;
1712 }
1713
1714 return 0;
1715}
1716
Douglas Gregord5058122010-02-11 01:19:42 +00001717void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001718 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1719 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001720 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001721 }
1722
1723 Init = I;
1724}
1725
Daniel Dunbar9d355812012-03-09 01:51:51 +00001726bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001727 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001728
Richard Smith35ecb362012-03-02 04:14:40 +00001729 if (!Lang.CPlusPlus)
1730 return false;
1731
1732 // In C++11, any variable of reference type can be used in a constant
1733 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001734 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00001735 return true;
1736
1737 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001738 // not require the variable to be non-volatile, but we consider this to be a
1739 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001740 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001741 return false;
1742
1743 // In C++, const, non-volatile variables of integral or enumeration types
1744 // can be used in constant expressions.
1745 if (getType()->isIntegralOrEnumerationType())
1746 return true;
1747
Richard Smith35ecb362012-03-02 04:14:40 +00001748 // Additionally, in C++11, non-volatile constexpr variables can be used in
1749 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001750 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001751}
1752
Richard Smithd0b4dd62011-12-19 06:19:21 +00001753/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1754/// form, which contains extra information on the evaluated value of the
1755/// initializer.
1756EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1757 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1758 if (!Eval) {
1759 Stmt *S = Init.get<Stmt *>();
1760 Eval = new (getASTContext()) EvaluatedStmt;
1761 Eval->Value = S;
1762 Init = Eval;
1763 }
1764 return Eval;
1765}
1766
Richard Smithdafff942012-01-14 04:30:29 +00001767APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001768 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00001769 return evaluateValue(Notes);
1770}
1771
1772APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001773 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001774 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1775
1776 // We only produce notes indicating why an initializer is non-constant the
1777 // first time it is evaluated. FIXME: The notes won't always be emitted the
1778 // first time we try evaluation, so might not be produced at all.
1779 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001780 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001781
1782 const Expr *Init = cast<Expr>(Eval->Value);
1783 assert(!Init->isValueDependent());
1784
1785 if (Eval->IsEvaluating) {
1786 // FIXME: Produce a diagnostic for self-initialization.
1787 Eval->CheckedICE = true;
1788 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001789 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001790 }
1791
1792 Eval->IsEvaluating = true;
1793
1794 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1795 this, Notes);
1796
1797 // Ensure the result is an uninitialized APValue if evaluation fails.
1798 if (!Result)
1799 Eval->Evaluated = APValue();
1800
1801 Eval->IsEvaluating = false;
1802 Eval->WasEvaluated = true;
1803
1804 // In C++11, we have determined whether the initializer was a constant
1805 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001806 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001807 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001808 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001809 }
1810
Richard Smithdafff942012-01-14 04:30:29 +00001811 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001812}
1813
1814bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001815 // Initializers of weak variables are never ICEs.
1816 if (isWeak())
1817 return false;
1818
Richard Smithd0b4dd62011-12-19 06:19:21 +00001819 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1820 if (Eval->CheckedICE)
1821 // We have already checked whether this subexpression is an
1822 // integral constant expression.
1823 return Eval->IsICE;
1824
1825 const Expr *Init = cast<Expr>(Eval->Value);
1826 assert(!Init->isValueDependent());
1827
1828 // In C++11, evaluate the initializer to check whether it's a constant
1829 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001830 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001831 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001832 evaluateValue(Notes);
1833 return Eval->IsICE;
1834 }
1835
1836 // It's an ICE whether or not the definition we found is
1837 // out-of-line. See DR 721 and the discussion in Clang PR
1838 // 6206 for details.
1839
1840 if (Eval->CheckingICE)
1841 return false;
1842 Eval->CheckingICE = true;
1843
1844 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1845 Eval->CheckingICE = false;
1846 Eval->CheckedICE = true;
1847 return Eval->IsICE;
1848}
1849
Douglas Gregorfe314812011-06-21 17:03:29 +00001850bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001851 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001852
1853 const Expr *E = getInit();
1854 if (!E)
1855 return false;
1856
1857 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1858 E = Cleanups->getSubExpr();
1859
1860 return isa<MaterializeTemporaryExpr>(E);
1861}
1862
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001863VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001864 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001865 return cast<VarDecl>(MSI->getInstantiatedFrom());
1866
1867 return 0;
1868}
1869
Douglas Gregor3c74d412009-10-14 20:14:33 +00001870TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001871 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001872 return MSI->getTemplateSpecializationKind();
1873
1874 return TSK_Undeclared;
1875}
1876
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001877MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001878 return getASTContext().getInstantiatedFromStaticDataMember(this);
1879}
1880
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001881void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1882 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001883 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001884 assert(MSI && "Not an instantiated static data member?");
1885 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001886 if (TSK != TSK_ExplicitSpecialization &&
1887 PointOfInstantiation.isValid() &&
1888 MSI->getPointOfInstantiation().isInvalid())
1889 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001890}
1891
Sebastian Redl833ef452010-01-26 22:01:41 +00001892//===----------------------------------------------------------------------===//
1893// ParmVarDecl Implementation
1894//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001895
Sebastian Redl833ef452010-01-26 22:01:41 +00001896ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001897 SourceLocation StartLoc,
1898 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001899 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001900 StorageClass S, StorageClass SCAsWritten,
1901 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001902 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001903 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001904}
1905
Douglas Gregor72172e92012-01-05 21:55:30 +00001906ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1907 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1908 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1909 0, QualType(), 0, SC_None, SC_None, 0);
1910}
1911
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001912SourceRange ParmVarDecl::getSourceRange() const {
1913 if (!hasInheritedDefaultArg()) {
1914 SourceRange ArgRange = getDefaultArgRange();
1915 if (ArgRange.isValid())
1916 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1917 }
1918
1919 return DeclaratorDecl::getSourceRange();
1920}
1921
Sebastian Redl833ef452010-01-26 22:01:41 +00001922Expr *ParmVarDecl::getDefaultArg() {
1923 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1924 assert(!hasUninstantiatedDefaultArg() &&
1925 "Default argument is not yet instantiated!");
1926
1927 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001928 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001929 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001930
Sebastian Redl833ef452010-01-26 22:01:41 +00001931 return Arg;
1932}
1933
Sebastian Redl833ef452010-01-26 22:01:41 +00001934SourceRange ParmVarDecl::getDefaultArgRange() const {
1935 if (const Expr *E = getInit())
1936 return E->getSourceRange();
1937
1938 if (hasUninstantiatedDefaultArg())
1939 return getUninstantiatedDefaultArg()->getSourceRange();
1940
1941 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001942}
1943
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001944bool ParmVarDecl::isParameterPack() const {
1945 return isa<PackExpansionType>(getType());
1946}
1947
Ted Kremenek540017e2011-10-06 05:00:56 +00001948void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1949 getASTContext().setParameterIndex(this, parameterIndex);
1950 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1951}
1952
1953unsigned ParmVarDecl::getParameterIndexLarge() const {
1954 return getASTContext().getParameterIndex(this);
1955}
1956
Nuno Lopes394ec982008-12-17 23:39:55 +00001957//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001958// FunctionDecl Implementation
1959//===----------------------------------------------------------------------===//
1960
Benjamin Kramer9170e912013-02-22 15:46:01 +00001961void FunctionDecl::getNameForDiagnostic(
1962 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
1963 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00001964 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1965 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00001966 TemplateSpecializationType::PrintTemplateArgumentList(
1967 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00001968}
1969
Ted Kremenek186a0742010-04-29 16:49:01 +00001970bool FunctionDecl::isVariadic() const {
1971 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1972 return FT->isVariadic();
1973 return false;
1974}
1975
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001976bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1977 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001978 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001979 Definition = *I;
1980 return true;
1981 }
1982 }
1983
1984 return false;
1985}
1986
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001987bool FunctionDecl::hasTrivialBody() const
1988{
1989 Stmt *S = getBody();
1990 if (!S) {
1991 // Since we don't have a body for this function, we don't know if it's
1992 // trivial or not.
1993 return false;
1994 }
1995
1996 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1997 return true;
1998 return false;
1999}
2000
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002001bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2002 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00002003 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002004 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
2005 return true;
2006 }
2007 }
2008
2009 return false;
2010}
2011
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002012Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00002013 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
2014 if (I->Body) {
2015 Definition = *I;
2016 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00002017 } else if (I->IsLateTemplateParsed) {
2018 Definition = *I;
2019 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00002020 }
2021 }
2022
2023 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002024}
2025
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002026void FunctionDecl::setBody(Stmt *B) {
2027 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002028 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002029 EndRangeLoc = B->getLocEnd();
2030}
2031
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002032void FunctionDecl::setPure(bool P) {
2033 IsPure = P;
2034 if (P)
2035 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2036 Parent->markedVirtualFunctionPure();
2037}
2038
Douglas Gregor16618f22009-09-12 00:17:51 +00002039bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002040 const TranslationUnitDecl *tunit =
2041 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2042 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002043 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00002044 getIdentifier() &&
2045 getIdentifier()->isStr("main");
2046}
2047
2048bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2049 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2050 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2051 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2052 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2053 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2054
2055 if (isa<CXXRecordDecl>(getDeclContext())) return false;
2056 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
2057
2058 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2059 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
2060
2061 ASTContext &Context =
2062 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2063 ->getASTContext();
2064
2065 // The result type and first argument type are constant across all
2066 // these operators. The second argument must be exactly void*.
2067 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002068}
2069
Rafael Espindolaf4187652013-02-14 01:18:37 +00002070LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Rafael Espindola6239e052013-01-12 15:27:44 +00002071 // Users expect to be able to write
2072 // extern "C" void *__builtin_alloca (size_t);
2073 // so consider builtins as having C language linkage.
Rafael Espindolac48f7342013-01-12 15:27:43 +00002074 if (getBuiltinID())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002075 return CLanguageLinkage;
Rafael Espindolac48f7342013-01-12 15:27:43 +00002076
Rafael Espindolaf4187652013-02-14 01:18:37 +00002077 return getLanguageLinkageTemplate(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002078}
2079
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002080bool FunctionDecl::isGlobal() const {
2081 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2082 return Method->isStatic();
2083
John McCall8e7d6562010-08-26 03:08:43 +00002084 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002085 return false;
2086
Mike Stump11289f42009-09-09 15:08:12 +00002087 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002088 DC->isNamespace();
2089 DC = DC->getParent()) {
2090 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2091 if (!Namespace->getDeclName())
2092 return false;
2093 break;
2094 }
2095 }
2096
2097 return true;
2098}
2099
Richard Smith10876ef2013-01-17 01:30:42 +00002100bool FunctionDecl::isNoReturn() const {
2101 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002102 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002103 getType()->getAs<FunctionType>()->getNoReturnAttr();
2104}
2105
Sebastian Redl833ef452010-01-26 22:01:41 +00002106void
2107FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2108 redeclarable_base::setPreviousDeclaration(PrevDecl);
2109
2110 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2111 FunctionTemplateDecl *PrevFunTmpl
2112 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2113 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2114 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
2115 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002116
Axel Naumannfbc7b982011-11-08 18:21:06 +00002117 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002118 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002119}
2120
2121const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2122 return getFirstDeclaration();
2123}
2124
2125FunctionDecl *FunctionDecl::getCanonicalDecl() {
2126 return getFirstDeclaration();
2127}
2128
Douglas Gregorbf62d642010-12-06 18:36:25 +00002129void FunctionDecl::setStorageClass(StorageClass SC) {
2130 assert(isLegalForFunction(SC));
2131 if (getStorageClass() != SC)
Rafael Espindola19de5612013-01-12 06:42:30 +00002132 ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002133
2134 SClass = SC;
2135}
2136
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002137/// \brief Returns a value indicating whether this function
2138/// corresponds to a builtin function.
2139///
2140/// The function corresponds to a built-in function if it is
2141/// declared at translation scope or within an extern "C" block and
2142/// its name matches with the name of a builtin. The returned value
2143/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002144/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002145/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002146unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002147 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002148 return 0;
2149
2150 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002151 if (!BuiltinID)
2152 return 0;
2153
2154 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00002155 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2156 return BuiltinID;
2157
2158 // This function has the name of a known C library
2159 // function. Determine whether it actually refers to the C library
2160 // function or whether it just has the same name.
2161
Douglas Gregora908e7f2009-02-17 03:23:10 +00002162 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002163 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002164 return 0;
2165
Douglas Gregore711f702009-02-14 18:57:46 +00002166 // If this function is at translation-unit scope and we're not in
2167 // C++, it refers to the C library function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002168 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00002169 getDeclContext()->isTranslationUnit())
2170 return BuiltinID;
2171
2172 // If the function is in an extern "C" linkage specification and is
2173 // not marked "overloadable", it's the real function.
2174 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002175 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00002176 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002177 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00002178 return BuiltinID;
2179
2180 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002181 return 0;
2182}
2183
2184
Chris Lattner47c0d002009-04-25 06:03:53 +00002185/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002186/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002187/// after it has been created.
2188unsigned FunctionDecl::getNumParams() const {
Eli Friedman5c27c4c2012-08-30 22:22:09 +00002189 const FunctionType *FT = getType()->castAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002190 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00002191 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002192 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00002193
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002194}
2195
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002196void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002197 ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002198 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002199 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002201 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002202 if (!NewParamInfo.empty()) {
2203 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2204 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002205 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002206}
Chris Lattner41943152007-01-25 04:52:46 +00002207
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002208void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002209 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2210
2211 if (!NewDecls.empty()) {
2212 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2213 std::copy(NewDecls.begin(), NewDecls.end(), A);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002214 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
James Molloy6f8780b2012-02-29 10:24:19 +00002215 }
2216}
2217
Chris Lattner58258242008-04-10 02:22:51 +00002218/// getMinRequiredArguments - Returns the minimum number of arguments
2219/// needed to call this function. This may be fewer than the number of
2220/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00002221/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00002222unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002223 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002224 return getNumParams();
2225
Douglas Gregor7825bf32011-01-06 22:09:01 +00002226 unsigned NumRequiredArgs = getNumParams();
2227
2228 // If the last parameter is a parameter pack, we don't need an argument for
2229 // it.
2230 if (NumRequiredArgs > 0 &&
2231 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2232 --NumRequiredArgs;
2233
2234 // If this parameter has a default argument, we don't need an argument for
2235 // it.
2236 while (NumRequiredArgs > 0 &&
2237 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00002238 --NumRequiredArgs;
2239
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002240 // We might have parameter packs before the end. These can't be deduced,
2241 // but they can still handle multiple arguments.
2242 unsigned ArgIdx = NumRequiredArgs;
2243 while (ArgIdx > 0) {
2244 if (getParamDecl(ArgIdx - 1)->isParameterPack())
2245 NumRequiredArgs = ArgIdx;
2246
2247 --ArgIdx;
2248 }
2249
Chris Lattner58258242008-04-10 02:22:51 +00002250 return NumRequiredArgs;
2251}
2252
Eli Friedman1b125c32012-02-07 03:50:18 +00002253static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2254 // Only consider file-scope declarations in this test.
2255 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2256 return false;
2257
2258 // Only consider explicit declarations; the presence of a builtin for a
2259 // libcall shouldn't affect whether a definition is externally visible.
2260 if (Redecl->isImplicit())
2261 return false;
2262
2263 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2264 return true; // Not an inline definition
2265
2266 return false;
2267}
2268
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002269/// \brief For a function declaration in C or C++, determine whether this
2270/// declaration causes the definition to be externally visible.
2271///
Eli Friedman1b125c32012-02-07 03:50:18 +00002272/// Specifically, this determines if adding the current declaration to the set
2273/// of redeclarations of the given functions causes
2274/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002275bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2276 assert(!doesThisDeclarationHaveABody() &&
2277 "Must have a declaration without a body.");
2278
2279 ASTContext &Context = getASTContext();
2280
David Blaikiebbafb8a2012-03-11 07:00:24 +00002281 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002282 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2283 // an externally visible definition.
2284 //
2285 // FIXME: What happens if gnu_inline gets added on after the first
2286 // declaration?
2287 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
2288 return false;
2289
2290 const FunctionDecl *Prev = this;
2291 bool FoundBody = false;
2292 while ((Prev = Prev->getPreviousDecl())) {
2293 FoundBody |= Prev->Body;
2294
2295 if (Prev->Body) {
2296 // If it's not the case that both 'inline' and 'extern' are
2297 // specified on the definition, then it is always externally visible.
2298 if (!Prev->isInlineSpecified() ||
2299 Prev->getStorageClassAsWritten() != SC_Extern)
2300 return false;
2301 } else if (Prev->isInlineSpecified() &&
2302 Prev->getStorageClassAsWritten() != SC_Extern) {
2303 return false;
2304 }
2305 }
2306 return FoundBody;
2307 }
2308
David Blaikiebbafb8a2012-03-11 07:00:24 +00002309 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002310 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002311
2312 // C99 6.7.4p6:
2313 // [...] If all of the file scope declarations for a function in a
2314 // translation unit include the inline function specifier without extern,
2315 // then the definition in that translation unit is an inline definition.
2316 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002317 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002318 const FunctionDecl *Prev = this;
2319 bool FoundBody = false;
2320 while ((Prev = Prev->getPreviousDecl())) {
2321 FoundBody |= Prev->Body;
2322 if (RedeclForcesDefC99(Prev))
2323 return false;
2324 }
2325 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002326}
2327
Richard Smithf3814ad2013-01-25 00:08:28 +00002328/// \brief For an inline function definition in C, or for a gnu_inline function
2329/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002330///
2331/// Inline function definitions are always available for inlining optimizations.
2332/// However, depending on the language dialect, declaration specifiers, and
2333/// attributes, the definition of an inline function may or may not be
2334/// "externally" visible to other translation units in the program.
2335///
2336/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002337/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002338/// inline definition becomes externally visible (C99 6.7.4p6).
2339///
2340/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2341/// definition, we use the GNU semantics for inline, which are nearly the
2342/// opposite of C99 semantics. In particular, "inline" by itself will create
2343/// an externally visible symbol, but "extern inline" will not create an
2344/// externally visible symbol.
2345bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002346 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002347 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002348 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002349
David Blaikiebbafb8a2012-03-11 07:00:24 +00002350 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002351 // Note: If you change the logic here, please change
2352 // doesDeclarationForceExternallyVisibleDefinition as well.
2353 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002354 // If it's not the case that both 'inline' and 'extern' are
2355 // specified on the definition, then this inline definition is
2356 // externally visible.
2357 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2358 return true;
2359
2360 // If any declaration is 'inline' but not 'extern', then this definition
2361 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002362 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2363 Redecl != RedeclEnd;
2364 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002365 if (Redecl->isInlineSpecified() &&
2366 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002367 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002368 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002369
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002370 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002371 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002372
Richard Smithf3814ad2013-01-25 00:08:28 +00002373 // The rest of this function is C-only.
2374 assert(!Context.getLangOpts().CPlusPlus &&
2375 "should not use C inline rules in C++");
2376
Douglas Gregor299d76e2009-09-13 07:46:26 +00002377 // C99 6.7.4p6:
2378 // [...] If all of the file scope declarations for a function in a
2379 // translation unit include the inline function specifier without extern,
2380 // then the definition in that translation unit is an inline definition.
2381 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2382 Redecl != RedeclEnd;
2383 ++Redecl) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002384 if (RedeclForcesDefC99(*Redecl))
2385 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002386 }
2387
2388 // C99 6.7.4p6:
2389 // An inline definition does not provide an external definition for the
2390 // function, and does not forbid an external definition in another
2391 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002392 return false;
2393}
2394
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002395/// getOverloadedOperator - Which C++ overloaded operator this
2396/// function represents, if any.
2397OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002398 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2399 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002400 else
2401 return OO_None;
2402}
2403
Alexis Huntc88db062010-01-13 09:01:02 +00002404/// getLiteralIdentifier - The literal suffix identifier this function
2405/// represents, if any.
2406const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2407 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2408 return getDeclName().getCXXLiteralIdentifier();
2409 else
2410 return 0;
2411}
2412
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002413FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2414 if (TemplateOrSpecialization.isNull())
2415 return TK_NonTemplate;
2416 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2417 return TK_FunctionTemplate;
2418 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2419 return TK_MemberSpecialization;
2420 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2421 return TK_FunctionTemplateSpecialization;
2422 if (TemplateOrSpecialization.is
2423 <DependentFunctionTemplateSpecializationInfo*>())
2424 return TK_DependentFunctionTemplateSpecialization;
2425
David Blaikie83d382b2011-09-23 05:06:16 +00002426 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002427}
2428
Douglas Gregord801b062009-10-07 23:56:10 +00002429FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002430 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002431 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2432
2433 return 0;
2434}
2435
2436void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002437FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2438 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002439 TemplateSpecializationKind TSK) {
2440 assert(TemplateOrSpecialization.isNull() &&
2441 "Member function is already a specialization");
2442 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002443 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002444 TemplateOrSpecialization = Info;
2445}
2446
Douglas Gregorafca3b42009-10-27 20:53:28 +00002447bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002448 // If the function is invalid, it can't be implicitly instantiated.
2449 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002450 return false;
2451
2452 switch (getTemplateSpecializationKind()) {
2453 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002454 case TSK_ExplicitInstantiationDefinition:
2455 return false;
2456
2457 case TSK_ImplicitInstantiation:
2458 return true;
2459
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002460 // It is possible to instantiate TSK_ExplicitSpecialization kind
2461 // if the FunctionDecl has a class scope specialization pattern.
2462 case TSK_ExplicitSpecialization:
2463 return getClassScopeSpecializationPattern() != 0;
2464
Douglas Gregorafca3b42009-10-27 20:53:28 +00002465 case TSK_ExplicitInstantiationDeclaration:
2466 // Handled below.
2467 break;
2468 }
2469
2470 // Find the actual template from which we will instantiate.
2471 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002472 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002473 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002474 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002475
2476 // C++0x [temp.explicit]p9:
2477 // Except for inline functions, other explicit instantiation declarations
2478 // have the effect of suppressing the implicit instantiation of the entity
2479 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002480 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002481 return true;
2482
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002483 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002484}
2485
2486bool FunctionDecl::isTemplateInstantiation() const {
2487 switch (getTemplateSpecializationKind()) {
2488 case TSK_Undeclared:
2489 case TSK_ExplicitSpecialization:
2490 return false;
2491 case TSK_ImplicitInstantiation:
2492 case TSK_ExplicitInstantiationDeclaration:
2493 case TSK_ExplicitInstantiationDefinition:
2494 return true;
2495 }
2496 llvm_unreachable("All TSK values handled.");
2497}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002498
2499FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002500 // Handle class scope explicit specialization special case.
2501 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2502 return getClassScopeSpecializationPattern();
2503
Douglas Gregorafca3b42009-10-27 20:53:28 +00002504 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2505 while (Primary->getInstantiatedFromMemberTemplate()) {
2506 // If we have hit a point where the user provided a specialization of
2507 // this template, we're done looking.
2508 if (Primary->isMemberSpecialization())
2509 break;
2510
2511 Primary = Primary->getInstantiatedFromMemberTemplate();
2512 }
2513
2514 return Primary->getTemplatedDecl();
2515 }
2516
2517 return getInstantiatedFromMemberFunction();
2518}
2519
Douglas Gregor70d83e22009-06-29 17:30:29 +00002520FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002521 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002522 = TemplateOrSpecialization
2523 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002524 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002525 }
2526 return 0;
2527}
2528
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002529FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2530 return getASTContext().getClassScopeSpecializationPattern(this);
2531}
2532
Douglas Gregor70d83e22009-06-29 17:30:29 +00002533const TemplateArgumentList *
2534FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002535 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002536 = TemplateOrSpecialization
2537 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002538 return Info->TemplateArguments;
2539 }
2540 return 0;
2541}
2542
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002543const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002544FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2545 if (FunctionTemplateSpecializationInfo *Info
2546 = TemplateOrSpecialization
2547 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2548 return Info->TemplateArgumentsAsWritten;
2549 }
2550 return 0;
2551}
2552
Mike Stump11289f42009-09-09 15:08:12 +00002553void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002554FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2555 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002556 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002557 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002558 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002559 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2560 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002561 assert(TSK != TSK_Undeclared &&
2562 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002563 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002564 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002565 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002566 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2567 TemplateArgs,
2568 TemplateArgsAsWritten,
2569 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002570 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002571 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002572}
2573
John McCallb9c78482010-04-08 09:05:18 +00002574void
2575FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2576 const UnresolvedSetImpl &Templates,
2577 const TemplateArgumentListInfo &TemplateArgs) {
2578 assert(TemplateOrSpecialization.isNull());
2579 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2580 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002581 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002582 void *Buffer = Context.Allocate(Size);
2583 DependentFunctionTemplateSpecializationInfo *Info =
2584 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2585 TemplateArgs);
2586 TemplateOrSpecialization = Info;
2587}
2588
2589DependentFunctionTemplateSpecializationInfo::
2590DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2591 const TemplateArgumentListInfo &TArgs)
2592 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2593
2594 d.NumTemplates = Ts.size();
2595 d.NumArgs = TArgs.size();
2596
2597 FunctionTemplateDecl **TsArray =
2598 const_cast<FunctionTemplateDecl**>(getTemplates());
2599 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2600 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2601
2602 TemplateArgumentLoc *ArgsArray =
2603 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2604 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2605 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2606}
2607
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002608TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002609 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002610 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002611 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002612 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002613 if (FTSInfo)
2614 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002615
Douglas Gregord801b062009-10-07 23:56:10 +00002616 MemberSpecializationInfo *MSInfo
2617 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2618 if (MSInfo)
2619 return MSInfo->getTemplateSpecializationKind();
2620
2621 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002622}
2623
Mike Stump11289f42009-09-09 15:08:12 +00002624void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002625FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2626 SourceLocation PointOfInstantiation) {
2627 if (FunctionTemplateSpecializationInfo *FTSInfo
2628 = TemplateOrSpecialization.dyn_cast<
2629 FunctionTemplateSpecializationInfo*>()) {
2630 FTSInfo->setTemplateSpecializationKind(TSK);
2631 if (TSK != TSK_ExplicitSpecialization &&
2632 PointOfInstantiation.isValid() &&
2633 FTSInfo->getPointOfInstantiation().isInvalid())
2634 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2635 } else if (MemberSpecializationInfo *MSInfo
2636 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2637 MSInfo->setTemplateSpecializationKind(TSK);
2638 if (TSK != TSK_ExplicitSpecialization &&
2639 PointOfInstantiation.isValid() &&
2640 MSInfo->getPointOfInstantiation().isInvalid())
2641 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2642 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002643 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002644}
2645
2646SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002647 if (FunctionTemplateSpecializationInfo *FTSInfo
2648 = TemplateOrSpecialization.dyn_cast<
2649 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002650 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002651 else if (MemberSpecializationInfo *MSInfo
2652 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002653 return MSInfo->getPointOfInstantiation();
2654
2655 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002656}
2657
Douglas Gregor6411b922009-09-11 20:15:17 +00002658bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002659 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002660 return true;
2661
2662 // If this function was instantiated from a member function of a
2663 // class template, check whether that member function was defined out-of-line.
2664 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2665 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002666 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002667 return Definition->isOutOfLine();
2668 }
2669
2670 // If this function was instantiated from a function template,
2671 // check whether that function template was defined out-of-line.
2672 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2673 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002674 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002675 return Definition->isOutOfLine();
2676 }
2677
2678 return false;
2679}
2680
Abramo Bagnaraea947882011-03-08 16:41:52 +00002681SourceRange FunctionDecl::getSourceRange() const {
2682 return SourceRange(getOuterLocStart(), EndRangeLoc);
2683}
2684
Anna Zaks28db7ce2012-01-18 02:45:01 +00002685unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002686 IdentifierInfo *FnInfo = getIdentifier();
2687
2688 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002689 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002690
2691 // Builtin handling.
2692 switch (getBuiltinID()) {
2693 case Builtin::BI__builtin_memset:
2694 case Builtin::BI__builtin___memset_chk:
2695 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002696 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002697
2698 case Builtin::BI__builtin_memcpy:
2699 case Builtin::BI__builtin___memcpy_chk:
2700 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002701 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002702
2703 case Builtin::BI__builtin_memmove:
2704 case Builtin::BI__builtin___memmove_chk:
2705 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002706 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002707
2708 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002709 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002710 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002711 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002712
2713 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002714 case Builtin::BImemcmp:
2715 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002716
2717 case Builtin::BI__builtin_strncpy:
2718 case Builtin::BI__builtin___strncpy_chk:
2719 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002720 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002721
2722 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002723 case Builtin::BIstrncmp:
2724 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002725
2726 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002727 case Builtin::BIstrncasecmp:
2728 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002729
2730 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002731 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002732 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002733 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002734
2735 case Builtin::BI__builtin_strndup:
2736 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002737 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002738
Anna Zaks314cd092012-02-01 19:08:57 +00002739 case Builtin::BI__builtin_strlen:
2740 case Builtin::BIstrlen:
2741 return Builtin::BIstrlen;
2742
Anna Zaks201d4892012-01-13 21:52:01 +00002743 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002744 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002745 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002746 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002747 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002748 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002749 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002750 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002751 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002752 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002753 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002754 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002755 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002756 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002757 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002758 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002759 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002760 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002761 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002762 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002763 else if (FnInfo->isStr("strlen"))
2764 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002765 }
2766 break;
2767 }
Anna Zaks22122702012-01-17 00:37:07 +00002768 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002769}
2770
Chris Lattner59a25942008-03-31 00:36:02 +00002771//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002772// FieldDecl Implementation
2773//===----------------------------------------------------------------------===//
2774
Jay Foad39c79802011-01-12 09:06:06 +00002775FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002776 SourceLocation StartLoc, SourceLocation IdLoc,
2777 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002778 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00002779 InClassInitStyle InitStyle) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002780 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith2b013182012-06-10 03:12:00 +00002781 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00002782}
2783
Douglas Gregor72172e92012-01-05 21:55:30 +00002784FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2785 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2786 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
Richard Smith2b013182012-06-10 03:12:00 +00002787 0, QualType(), 0, 0, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00002788}
2789
Sebastian Redl833ef452010-01-26 22:01:41 +00002790bool FieldDecl::isAnonymousStructOrUnion() const {
2791 if (!isImplicit() || getDeclName())
2792 return false;
2793
2794 if (const RecordType *Record = getType()->getAs<RecordType>())
2795 return Record->getDecl()->isAnonymousStructOrUnion();
2796
2797 return false;
2798}
2799
Richard Smithcaf33902011-10-10 18:28:20 +00002800unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2801 assert(isBitField() && "not a bitfield");
2802 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2803 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2804}
2805
John McCall4e819612011-01-20 07:57:12 +00002806unsigned FieldDecl::getFieldIndex() const {
2807 if (CachedFieldIndex) return CachedFieldIndex - 1;
2808
Richard Smithd62306a2011-11-10 06:34:14 +00002809 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002810 const RecordDecl *RD = getParent();
2811 const FieldDecl *LastFD = 0;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002812 bool IsMsStruct = RD->isMsStruct(getASTContext());
Richard Smithd62306a2011-11-10 06:34:14 +00002813
2814 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2815 I != E; ++I, ++Index) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00002816 I->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002817
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002818 if (IsMsStruct) {
2819 // Zero-length bitfields following non-bitfield members are ignored.
David Blaikie40ed2972012-06-06 20:45:41 +00002820 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) {
Richard Smithd62306a2011-11-10 06:34:14 +00002821 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002822 continue;
2823 }
David Blaikie40ed2972012-06-06 20:45:41 +00002824 LastFD = *I;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002825 }
John McCall4e819612011-01-20 07:57:12 +00002826 }
2827
Richard Smithd62306a2011-11-10 06:34:14 +00002828 assert(CachedFieldIndex && "failed to find field in parent");
2829 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002830}
2831
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002832SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002833 if (const Expr *E = InitializerOrBitWidth.getPointer())
2834 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002835 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002836}
2837
Abramo Bagnarab1cdde72012-07-02 20:35:48 +00002838void FieldDecl::setBitWidth(Expr *Width) {
2839 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
2840 "bit width or initializer already set");
2841 InitializerOrBitWidth.setPointer(Width);
2842}
2843
Richard Smith938f40b2011-06-11 17:19:42 +00002844void FieldDecl::setInClassInitializer(Expr *Init) {
Richard Smith2b013182012-06-10 03:12:00 +00002845 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
Richard Smith938f40b2011-06-11 17:19:42 +00002846 "bit width or initializer already set");
2847 InitializerOrBitWidth.setPointer(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002848}
2849
Sebastian Redl833ef452010-01-26 22:01:41 +00002850//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002851// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002852//===----------------------------------------------------------------------===//
2853
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002854SourceLocation TagDecl::getOuterLocStart() const {
2855 return getTemplateOrInnerLocStart(this);
2856}
2857
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002858SourceRange TagDecl::getSourceRange() const {
2859 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002860 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002861}
2862
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002863TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002864 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002865}
2866
Richard Smithdda56e42011-04-15 14:24:37 +00002867void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2868 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002869 if (TypeForDecl)
Rafael Espindola19de5612013-01-12 06:42:30 +00002870 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2871 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002872}
2873
Douglas Gregordee1be82009-01-17 00:42:38 +00002874void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002875 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002876
David Blaikie095deba2012-11-14 01:52:05 +00002877 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
John McCall67da35c2010-02-04 22:26:26 +00002878 struct CXXRecordDecl::DefinitionData *Data =
2879 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002880 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2881 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002882 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002883}
2884
2885void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002886 assert((!isa<CXXRecordDecl>(this) ||
2887 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2888 "definition completed but not started");
2889
John McCallf937c022011-10-07 06:10:15 +00002890 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002891 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002892
2893 if (ASTMutationListener *L = getASTMutationListener())
2894 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002895}
2896
John McCallf937c022011-10-07 06:10:15 +00002897TagDecl *TagDecl::getDefinition() const {
2898 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002899 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002900
2901 // If it's possible for us to have an out-of-date definition, check now.
2902 if (MayHaveOutOfDateDef) {
2903 if (IdentifierInfo *II = getIdentifier()) {
2904 if (II->isOutOfDate()) {
2905 updateOutOfDate(*II);
2906 }
2907 }
2908 }
2909
Andrew Trickba266ee2010-10-19 21:54:32 +00002910 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2911 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002912
2913 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002914 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002915 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002916 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002917
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002918 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002919}
2920
Douglas Gregor14454802011-02-25 02:25:35 +00002921void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2922 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002923 // Make sure the extended qualifier info is allocated.
2924 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002925 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002926 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002927 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002928 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002929 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002930 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002931 if (getExtInfo()->NumTemplParamLists == 0) {
2932 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002933 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002934 }
2935 else
2936 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002937 }
2938 }
2939}
2940
Abramo Bagnara60804e12011-03-18 15:16:37 +00002941void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2942 unsigned NumTPLists,
2943 TemplateParameterList **TPLists) {
2944 assert(NumTPLists > 0);
2945 // Make sure the extended decl info is allocated.
2946 if (!hasExtInfo())
2947 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002948 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002949 // Set the template parameter lists info.
2950 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2951}
2952
Ted Kremenek21475702008-09-05 17:16:31 +00002953//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002954// EnumDecl Implementation
2955//===----------------------------------------------------------------------===//
2956
David Blaikie68e081d2011-12-20 02:48:34 +00002957void EnumDecl::anchor() { }
2958
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002959EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2960 SourceLocation StartLoc, SourceLocation IdLoc,
2961 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002962 EnumDecl *PrevDecl, bool IsScoped,
2963 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002964 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002965 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002966 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00002967 C.getTypeDeclType(Enum, PrevDecl);
2968 return Enum;
2969}
2970
Douglas Gregor72172e92012-01-05 21:55:30 +00002971EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2972 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00002973 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(),
2974 0, 0, false, false, false);
2975 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
2976 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002977}
2978
Douglas Gregord5058122010-02-11 01:19:42 +00002979void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002980 QualType NewPromotionType,
2981 unsigned NumPositiveBits,
2982 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002983 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002984 if (!IntegerType)
2985 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002986 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002987 setNumPositiveBits(NumPositiveBits);
2988 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002989 TagDecl::completeDefinition();
2990}
2991
Richard Smith7d137e32012-03-23 03:33:32 +00002992TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2993 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2994 return MSI->getTemplateSpecializationKind();
2995
2996 return TSK_Undeclared;
2997}
2998
2999void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3000 SourceLocation PointOfInstantiation) {
3001 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3002 assert(MSI && "Not an instantiated member enumeration?");
3003 MSI->setTemplateSpecializationKind(TSK);
3004 if (TSK != TSK_ExplicitSpecialization &&
3005 PointOfInstantiation.isValid() &&
3006 MSI->getPointOfInstantiation().isInvalid())
3007 MSI->setPointOfInstantiation(PointOfInstantiation);
3008}
3009
Richard Smith4b38ded2012-03-14 23:13:10 +00003010EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3011 if (SpecializationInfo)
3012 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3013
3014 return 0;
3015}
3016
3017void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3018 TemplateSpecializationKind TSK) {
3019 assert(!SpecializationInfo && "Member enum is already a specialization");
3020 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3021}
3022
Sebastian Redl833ef452010-01-26 22:01:41 +00003023//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003024// RecordDecl Implementation
3025//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003026
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003027RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3028 SourceLocation StartLoc, SourceLocation IdLoc,
3029 IdentifierInfo *Id, RecordDecl *PrevDecl)
3030 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003031 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003032 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003033 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003034 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003035 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003036 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003037}
3038
Jay Foad39c79802011-01-12 09:06:06 +00003039RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003040 SourceLocation StartLoc, SourceLocation IdLoc,
3041 IdentifierInfo *Id, RecordDecl* PrevDecl) {
3042 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3043 PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003044 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3045
Ted Kremenek21475702008-09-05 17:16:31 +00003046 C.getTypeDeclType(R, PrevDecl);
3047 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003048}
3049
Douglas Gregor72172e92012-01-05 21:55:30 +00003050RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3051 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003052 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3053 SourceLocation(), 0, 0);
3054 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3055 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003056}
3057
Douglas Gregordfcad112009-03-25 15:59:44 +00003058bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003059 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003060 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3061}
3062
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003063RecordDecl::field_iterator RecordDecl::field_begin() const {
3064 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3065 LoadFieldsFromExternalStorage();
3066
3067 return field_iterator(decl_iterator(FirstDecl));
3068}
3069
Douglas Gregorb11aad82011-02-19 18:51:44 +00003070/// completeDefinition - Notes that the definition of this type is now
3071/// complete.
3072void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003073 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003074 TagDecl::completeDefinition();
3075}
3076
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003077/// isMsStruct - Get whether or not this record uses ms_struct layout.
3078/// This which can be turned on with an attribute, pragma, or the
3079/// -mms-bitfields command-line option.
3080bool RecordDecl::isMsStruct(const ASTContext &C) const {
3081 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3082}
3083
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003084static bool isFieldOrIndirectField(Decl::Kind K) {
3085 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3086}
3087
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003088void RecordDecl::LoadFieldsFromExternalStorage() const {
3089 ExternalASTSource *Source = getASTContext().getExternalSource();
3090 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3091
3092 // Notify that we have a RecordDecl doing some initialization.
3093 ExternalASTSource::Deserializing TheFields(Source);
3094
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003095 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003096 LoadedFieldsFromExternalStorage = true;
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003097 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3098 Decls)) {
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003099 case ELR_Success:
3100 break;
3101
3102 case ELR_AlreadyLoaded:
3103 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003104 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00003105 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003106
3107#ifndef NDEBUG
3108 // Check that all decls we got were FieldDecls.
3109 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003110 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003111#endif
3112
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003113 if (Decls.empty())
3114 return;
3115
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003116 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3117 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003118}
3119
Steve Naroff415d3d52008-10-08 17:01:13 +00003120//===----------------------------------------------------------------------===//
3121// BlockDecl Implementation
3122//===----------------------------------------------------------------------===//
3123
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003124void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00003125 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003126
Steve Naroffc4b30e52009-03-13 16:56:44 +00003127 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003128 if (!NewParamInfo.empty()) {
3129 NumParams = NewParamInfo.size();
3130 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3131 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003132 }
3133}
3134
John McCall351762c2011-02-07 10:33:21 +00003135void BlockDecl::setCaptures(ASTContext &Context,
3136 const Capture *begin,
3137 const Capture *end,
3138 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00003139 CapturesCXXThis = capturesCXXThis;
3140
3141 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00003142 NumCaptures = 0;
3143 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00003144 return;
3145 }
3146
John McCall351762c2011-02-07 10:33:21 +00003147 NumCaptures = end - begin;
3148
3149 // Avoid new Capture[] because we don't want to provide a default
3150 // constructor.
3151 size_t allocationSize = NumCaptures * sizeof(Capture);
3152 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3153 memcpy(buffer, begin, allocationSize);
3154 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003155}
Sebastian Redl833ef452010-01-26 22:01:41 +00003156
John McCallce45f882011-06-15 22:51:16 +00003157bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3158 for (capture_const_iterator
3159 i = capture_begin(), e = capture_end(); i != e; ++i)
3160 // Only auto vars can be captured, so no redeclaration worries.
3161 if (i->getVariable() == variable)
3162 return true;
3163
3164 return false;
3165}
3166
Douglas Gregor70226da2010-12-21 16:27:07 +00003167SourceRange BlockDecl::getSourceRange() const {
3168 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3169}
Sebastian Redl833ef452010-01-26 22:01:41 +00003170
3171//===----------------------------------------------------------------------===//
3172// Other Decl Allocation/Deallocation Method Implementations
3173//===----------------------------------------------------------------------===//
3174
David Blaikie68e081d2011-12-20 02:48:34 +00003175void TranslationUnitDecl::anchor() { }
3176
Sebastian Redl833ef452010-01-26 22:01:41 +00003177TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3178 return new (C) TranslationUnitDecl(C);
3179}
3180
David Blaikie68e081d2011-12-20 02:48:34 +00003181void LabelDecl::anchor() { }
3182
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003183LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003184 SourceLocation IdentL, IdentifierInfo *II) {
3185 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
3186}
3187
3188LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3189 SourceLocation IdentL, IdentifierInfo *II,
3190 SourceLocation GnuLabelL) {
3191 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3192 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003193}
3194
Douglas Gregor72172e92012-01-05 21:55:30 +00003195LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3196 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
3197 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003198}
3199
David Blaikie68e081d2011-12-20 02:48:34 +00003200void ValueDecl::anchor() { }
3201
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003202bool ValueDecl::isWeak() const {
3203 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3204 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3205 return true;
3206
3207 return isWeakImported();
3208}
3209
David Blaikie68e081d2011-12-20 02:48:34 +00003210void ImplicitParamDecl::anchor() { }
3211
Sebastian Redl833ef452010-01-26 22:01:41 +00003212ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003213 SourceLocation IdLoc,
3214 IdentifierInfo *Id,
3215 QualType Type) {
3216 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003217}
3218
Douglas Gregor72172e92012-01-05 21:55:30 +00003219ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3220 unsigned ID) {
3221 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
3222 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3223}
3224
Sebastian Redl833ef452010-01-26 22:01:41 +00003225FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003226 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003227 const DeclarationNameInfo &NameInfo,
3228 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003229 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00003230 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003231 bool hasWrittenPrototype,
3232 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003233 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
3234 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00003235 isInlineSpecified,
3236 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003237 New->HasWrittenPrototype = hasWrittenPrototype;
3238 return New;
3239}
3240
Douglas Gregor72172e92012-01-05 21:55:30 +00003241FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3242 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
3243 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
3244 DeclarationNameInfo(), QualType(), 0,
3245 SC_None, SC_None, false, false);
3246}
3247
Sebastian Redl833ef452010-01-26 22:01:41 +00003248BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3249 return new (C) BlockDecl(DC, L);
3250}
3251
Douglas Gregor72172e92012-01-05 21:55:30 +00003252BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3253 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
3254 return new (Mem) BlockDecl(0, SourceLocation());
3255}
3256
Sebastian Redl833ef452010-01-26 22:01:41 +00003257EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3258 SourceLocation L,
3259 IdentifierInfo *Id, QualType T,
3260 Expr *E, const llvm::APSInt &V) {
3261 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
3262}
3263
Douglas Gregor72172e92012-01-05 21:55:30 +00003264EnumConstantDecl *
3265EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3266 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
3267 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3268 llvm::APSInt());
3269}
3270
David Blaikie68e081d2011-12-20 02:48:34 +00003271void IndirectFieldDecl::anchor() { }
3272
Benjamin Kramer39593702010-11-21 14:11:41 +00003273IndirectFieldDecl *
3274IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3275 IdentifierInfo *Id, QualType T, NamedDecl **CH,
3276 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00003277 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3278}
3279
Douglas Gregor72172e92012-01-05 21:55:30 +00003280IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3281 unsigned ID) {
3282 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
3283 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3284 QualType(), 0, 0);
3285}
3286
Douglas Gregorbe996932010-09-01 20:41:53 +00003287SourceRange EnumConstantDecl::getSourceRange() const {
3288 SourceLocation End = getLocation();
3289 if (Init)
3290 End = Init->getLocEnd();
3291 return SourceRange(getLocation(), End);
3292}
3293
David Blaikie68e081d2011-12-20 02:48:34 +00003294void TypeDecl::anchor() { }
3295
Sebastian Redl833ef452010-01-26 22:01:41 +00003296TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003297 SourceLocation StartLoc, SourceLocation IdLoc,
3298 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3299 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00003300}
3301
David Blaikie68e081d2011-12-20 02:48:34 +00003302void TypedefNameDecl::anchor() { }
3303
Douglas Gregor72172e92012-01-05 21:55:30 +00003304TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3305 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
3306 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3307}
3308
Richard Smithdda56e42011-04-15 14:24:37 +00003309TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3310 SourceLocation StartLoc,
3311 SourceLocation IdLoc, IdentifierInfo *Id,
3312 TypeSourceInfo *TInfo) {
3313 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3314}
3315
Douglas Gregor72172e92012-01-05 21:55:30 +00003316TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3317 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
3318 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3319}
3320
Abramo Bagnaraea947882011-03-08 16:41:52 +00003321SourceRange TypedefDecl::getSourceRange() const {
3322 SourceLocation RangeEnd = getLocation();
3323 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3324 if (typeIsPostfix(TInfo->getType()))
3325 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3326 }
3327 return SourceRange(getLocStart(), RangeEnd);
3328}
3329
Richard Smithdda56e42011-04-15 14:24:37 +00003330SourceRange TypeAliasDecl::getSourceRange() const {
3331 SourceLocation RangeEnd = getLocStart();
3332 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3333 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3334 return SourceRange(getLocStart(), RangeEnd);
3335}
3336
David Blaikie68e081d2011-12-20 02:48:34 +00003337void FileScopeAsmDecl::anchor() { }
3338
Sebastian Redl833ef452010-01-26 22:01:41 +00003339FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00003340 StringLiteral *Str,
3341 SourceLocation AsmLoc,
3342 SourceLocation RParenLoc) {
3343 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00003344}
Douglas Gregorba345522011-12-02 23:23:56 +00003345
Douglas Gregor72172e92012-01-05 21:55:30 +00003346FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3347 unsigned ID) {
3348 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
3349 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3350}
3351
Michael Han84324352013-02-22 17:15:32 +00003352void EmptyDecl::anchor() {}
3353
3354EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3355 return new (C) EmptyDecl(DC, L);
3356}
3357
3358EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3359 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EmptyDecl));
3360 return new (Mem) EmptyDecl(0, SourceLocation());
3361}
3362
Douglas Gregorba345522011-12-02 23:23:56 +00003363//===----------------------------------------------------------------------===//
3364// ImportDecl Implementation
3365//===----------------------------------------------------------------------===//
3366
3367/// \brief Retrieve the number of module identifiers needed to name the given
3368/// module.
3369static unsigned getNumModuleIdentifiers(Module *Mod) {
3370 unsigned Result = 1;
3371 while (Mod->Parent) {
3372 Mod = Mod->Parent;
3373 ++Result;
3374 }
3375 return Result;
3376}
3377
Douglas Gregor22d09742012-01-03 18:04:46 +00003378ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003379 Module *Imported,
3380 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00003381 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003382 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003383{
3384 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3385 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3386 memcpy(StoredLocs, IdentifierLocs.data(),
3387 IdentifierLocs.size() * sizeof(SourceLocation));
3388}
3389
Douglas Gregor22d09742012-01-03 18:04:46 +00003390ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003391 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003392 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003393 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003394{
3395 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3396}
3397
3398ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003399 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003400 ArrayRef<SourceLocation> IdentifierLocs) {
3401 void *Mem = C.Allocate(sizeof(ImportDecl) +
3402 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003403 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003404}
3405
3406ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003407 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003408 Module *Imported,
3409 SourceLocation EndLoc) {
3410 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003411 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003412 Import->setImplicit();
3413 return Import;
3414}
3415
Douglas Gregor72172e92012-01-05 21:55:30 +00003416ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3417 unsigned NumLocations) {
3418 void *Mem = AllocateDeserializedDecl(C, ID,
3419 (sizeof(ImportDecl) +
3420 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00003421 return new (Mem) ImportDecl(EmptyShell());
3422}
3423
3424ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3425 if (!ImportedAndComplete.getInt())
3426 return ArrayRef<SourceLocation>();
3427
3428 const SourceLocation *StoredLocs
3429 = reinterpret_cast<const SourceLocation *>(this + 1);
3430 return ArrayRef<SourceLocation>(StoredLocs,
3431 getNumModuleIdentifiers(getImportedModule()));
3432}
3433
3434SourceRange ImportDecl::getSourceRange() const {
3435 if (!ImportedAndComplete.getInt())
3436 return SourceRange(getLocation(),
3437 *reinterpret_cast<const SourceLocation *>(this + 1));
3438
3439 return SourceRange(getLocation(), getIdentifierLocs().back());
3440}