blob: 427ca5efcd6930503e59df16e537950b62907e7b [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Faisal Valib90b2112014-04-03 16:32:21 +000016#include "clang/AST/ASTLambda.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000022#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000024#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "clang/AST/Stmt.h"
26#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000027#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000028#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000029#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000030#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000031#include "clang/Basic/TargetInfo.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000032#include "clang/Frontend/FrontendDiagnostic.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000033#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000034#include <algorithm>
35
Chris Lattner6d9a6852006-10-25 05:11:20 +000036using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000037
Richard Smith0b87e072013-10-07 08:02:11 +000038Decl *clang::getPrimaryMergedDecl(Decl *D) {
39 return D->getASTContext().getPrimaryMergedDecl(D);
40}
41
Richard Smith73b21d82014-09-03 02:33:22 +000042// Defined here so that it can be inlined into its direct callers.
43bool Decl::isOutOfLine() const {
44 return !getLexicalDeclContext()->Equals(getDeclContext());
45}
46
Richard Smith42413142015-05-15 20:05:43 +000047TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
48 : Decl(TranslationUnit, nullptr, SourceLocation()),
49 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
50 Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
51}
52
Chris Lattner88f70d62008-03-15 05:43:15 +000053//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000054// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000055//===----------------------------------------------------------------------===//
56
John McCalldf25c432013-02-16 00:17:33 +000057// Visibility rules aren't rigorously externally specified, but here
58// are the basic principles behind what we implement:
59//
60// 1. An explicit visibility attribute is generally a direct expression
61// of the user's intent and should be honored. Only the innermost
62// visibility attribute applies. If no visibility attribute applies,
63// global visibility settings are considered.
64//
65// 2. There is one caveat to the above: on or in a template pattern,
66// an explicit visibility attribute is just a default rule, and
67// visibility can be decreased by the visibility of template
68// arguments. But this, too, has an exception: an attribute on an
69// explicit specialization or instantiation causes all the visibility
70// restrictions of the template arguments to be ignored.
71//
72// 3. A variable that does not otherwise have explicit visibility can
73// be restricted by the visibility of its type.
74//
75// 4. A visibility restriction is explicit if it comes from an
76// attribute (or something like it), not a global visibility setting.
77// When emitting a reference to an external symbol, visibility
78// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +000079//
80// 5. When computing the visibility of a non-type, including a
81// non-type member of a class, only non-type visibility restrictions
82// are considered: the 'visibility' attribute, global value-visibility
83// settings, and a few special cases like __private_extern.
84//
85// 6. When computing the visibility of a type, including a type member
86// of a class, only type visibility restrictions are considered:
87// the 'type_visibility' attribute and global type-visibility settings.
88// However, a 'visibility' attribute counts as a 'type_visibility'
89// attribute on any declaration that only has the former.
90//
91// The visibility of a "secondary" entity, like a template argument,
92// is computed using the kind of that entity, not the kind of the
93// primary entity for which we are computing visibility. For example,
94// the visibility of a specialization of either of these templates:
95// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
96// template <class T, bool (&compare)(T, X)> class matcher;
97// is restricted according to the type visibility of the argument 'T',
98// the type visibility of 'bool(&)(T,X)', and the value visibility of
99// the argument function 'compare'. That 'has_match' is a value
100// and 'matcher' is a type only matters when looking for attributes
101// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000102
John McCall5f46c482013-02-21 23:42:58 +0000103const unsigned IgnoreExplicitVisibilityBit = 2;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000104const unsigned IgnoreAllVisibilityBit = 4;
John McCall5f46c482013-02-21 23:42:58 +0000105
John McCalldf25c432013-02-16 00:17:33 +0000106/// Kinds of LV computation. The linkage side of the computation is
107/// always the same, but different things can change how visibility is
108/// computed.
109enum LVComputationKind {
John McCall5f46c482013-02-21 23:42:58 +0000110 /// Do an LV computation for, ultimately, a type.
111 /// Visibility may be restricted by type visibility settings and
112 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000113 LVForType = NamedDecl::VisibilityForType,
John McCalldf25c432013-02-16 00:17:33 +0000114
John McCall5f46c482013-02-21 23:42:58 +0000115 /// Do an LV computation for, ultimately, a non-type declaration.
116 /// Visibility may be restricted by value visibility settings and
117 /// the visibility of template arguments.
John McCalld041a9b2013-02-20 01:54:26 +0000118 LVForValue = NamedDecl::VisibilityForValue,
119
John McCall5f46c482013-02-21 23:42:58 +0000120 /// Do an LV computation for, ultimately, a type that already has
121 /// some sort of explicit visibility. Visibility may only be
122 /// restricted by the visibility of template arguments.
123 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
John McCalld041a9b2013-02-20 01:54:26 +0000124
John McCall5f46c482013-02-21 23:42:58 +0000125 /// Do an LV computation for, ultimately, a non-type declaration
126 /// that already has some sort of explicit visibility. Visibility
127 /// may only be restricted by the visibility of template arguments.
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000128 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
129
130 /// Do an LV computation when we only care about the linkage.
131 LVForLinkageOnly =
132 LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
John McCalldf25c432013-02-16 00:17:33 +0000133};
134
John McCalld041a9b2013-02-20 01:54:26 +0000135/// Does this computation kind permit us to consider additional
136/// visibility settings from attributes and the like?
137static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000138 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
John McCalld041a9b2013-02-20 01:54:26 +0000139}
140
141/// Given an LVComputationKind, return one of the same type/value sort
142/// that records that it already has explicit visibility.
143static LVComputationKind
144withExplicitVisibilityAlready(LVComputationKind oldKind) {
145 LVComputationKind newKind =
John McCall5f46c482013-02-21 23:42:58 +0000146 static_cast<LVComputationKind>(unsigned(oldKind) |
147 IgnoreExplicitVisibilityBit);
John McCalld041a9b2013-02-20 01:54:26 +0000148 assert(oldKind != LVForType || newKind == LVForExplicitType);
149 assert(oldKind != LVForValue || newKind == LVForExplicitValue);
150 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType);
151 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
152 return newKind;
153}
154
David Blaikie05785d12013-02-20 22:23:23 +0000155static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
156 LVComputationKind kind) {
John McCalld041a9b2013-02-20 01:54:26 +0000157 assert(!hasExplicitVisibilityAlready(kind) &&
158 "asking for explicit visibility when we shouldn't be");
159 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
160}
161
John McCalldf25c432013-02-16 00:17:33 +0000162/// Is the given declaration a "type" or a "value" for the purposes of
163/// visibility computation?
164static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000165 return isa<TypeDecl>(D) ||
166 isa<ClassTemplateDecl>(D) ||
167 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000168}
169
John McCall5f46c482013-02-21 23:42:58 +0000170/// Does the given declaration have member specialization information,
171/// and if so, is it an explicit specialization?
172template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000173std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000174isExplicitMemberSpecialization(const T *D) {
175 if (const MemberSpecializationInfo *member =
176 D->getMemberSpecializationInfo()) {
177 return member->isExplicitSpecialization();
178 }
179 return false;
180}
181
182/// For templates, this question is easier: a member template can't be
183/// explicitly instantiated, so there's a single bit indicating whether
184/// or not this is an explicit member specialization.
185static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
186 return D->isMemberSpecialization();
187}
188
John McCalld041a9b2013-02-20 01:54:26 +0000189/// Given a visibility attribute, return the explicit visibility
190/// associated with it.
191template <class T>
192static Visibility getVisibilityFromAttr(const T *attr) {
193 switch (attr->getVisibility()) {
194 case T::Default:
195 return DefaultVisibility;
196 case T::Hidden:
197 return HiddenVisibility;
198 case T::Protected:
199 return ProtectedVisibility;
200 }
201 llvm_unreachable("bad visibility kind");
202}
203
John McCalldf25c432013-02-16 00:17:33 +0000204/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000205static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000206 NamedDecl::ExplicitVisibilityKind kind) {
207 // If we're ultimately computing the visibility of a type, look for
208 // a 'type_visibility' attribute before looking for 'visibility'.
209 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000210 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000211 return getVisibilityFromAttr(A);
212 }
213 }
214
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000215 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000216 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000217 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000218 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000219
220 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
221 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +0000222 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000223 for (const auto *A : D->specific_attrs<AvailabilityAttr>())
224 if (A->getPlatform()->getName().equals("macosx"))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000225 return DefaultVisibility;
226 }
227
David Blaikie7a30dc52013-02-21 01:47:18 +0000228 return None;
John McCall457a04e2010-10-22 21:05:15 +0000229}
230
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000231static LinkageInfo
232getLVForType(const Type &T, LVComputationKind computation) {
233 if (computation == LVForLinkageOnly)
234 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
235 return T.getLinkageAndVisibility();
236}
237
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000238/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000239/// template parameter list. For visibility purposes, template
240/// parameters are part of the signature of a template.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000241static LinkageInfo
David Majnemerc7b85c42014-04-23 05:16:48 +0000242getLVForTemplateParameterList(const TemplateParameterList *Params,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000243 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000244 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000245 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000246 // Template type parameters are the most common and never
247 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000248 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000249 continue;
250
251 // Non-type template parameters can be restricted by the value type, e.g.
252 // template <enum X> class A { ... };
253 // We have to be careful here, though, because we can be dealing with
254 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000255 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000256 // Handle the non-pack case first.
257 if (!NTTP->isExpandedParameterPack()) {
258 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000259 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000260 }
261 continue;
262 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000263
John McCalldf25c432013-02-16 00:17:33 +0000264 // Look at all the types in an expanded pack.
265 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
266 QualType type = NTTP->getExpansionType(i);
267 if (!type->isDependentType())
Rafael Espindola6fbfafe2013-02-27 02:27:19 +0000268 LV.merge(type->getLinkageAndVisibility());
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000269 }
John McCalldf25c432013-02-16 00:17:33 +0000270 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000271 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000272
John McCalldf25c432013-02-16 00:17:33 +0000273 // Template template parameters can be restricted by their
274 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000275 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000276
277 // Handle the non-pack case first.
278 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000279 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
280 computation));
John McCalldf25c432013-02-16 00:17:33 +0000281 continue;
282 }
283
284 // Look at all expansions in an expanded pack.
285 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
286 i != n; ++i) {
287 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000288 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000289 }
290 }
291
John McCall457a04e2010-10-22 21:05:15 +0000292 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000293}
294
Rafael Espindola19de5612013-01-12 06:42:30 +0000295/// getLVForDecl - Get the linkage and visibility for the given declaration.
John McCalldf25c432013-02-16 00:17:33 +0000296static LinkageInfo getLVForDecl(const NamedDecl *D,
297 LVComputationKind computation);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000298
Eli Friedman7e346a82013-07-01 20:22:57 +0000299static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000300 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000301 const DeclContext *DC = D->getDeclContext();
302 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000303 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
304 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000305 DC = DC->getParent();
306 }
307 return Ret;
308}
309
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000310/// \brief Get the most restrictive linkage for the types and
311/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000312///
313/// Note that we don't take an LVComputationKind because we always
314/// want to honor the visibility of template arguments in the same way.
David Majnemerc7b85c42014-04-23 05:16:48 +0000315static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
316 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000317 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000318
David Majnemerc7b85c42014-04-23 05:16:48 +0000319 for (const TemplateArgument &Arg : Args) {
320 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321 case TemplateArgument::Null:
322 case TemplateArgument::Integral:
323 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000324 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000325
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000326 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000327 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000328 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000329
330 case TemplateArgument::Declaration:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000331 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000332 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000333 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000334 }
335 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000336
337 case TemplateArgument::NullPtr:
David Majnemerc7b85c42014-04-23 05:16:48 +0000338 LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
John McCalldf25c432013-02-16 00:17:33 +0000339 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000340
341 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000342 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000343 if (TemplateDecl *Template =
344 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000345 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000346 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000347
348 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000349 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000350 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351 }
John McCalldf25c432013-02-16 00:17:33 +0000352 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000353 }
354
John McCall457a04e2010-10-22 21:05:15 +0000355 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000356}
357
Rafael Espindola2f869a32012-01-14 00:30:36 +0000358static LinkageInfo
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000359getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
360 LVComputationKind computation) {
361 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000362}
363
John McCall5f46c482013-02-21 23:42:58 +0000364static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
365 const FunctionTemplateSpecializationInfo *specInfo) {
366 // Include visibility from the template parameters and arguments
367 // only if this is not an explicit instantiation or specialization
368 // with direct explicit visibility. (Implicit instantiations won't
369 // have a direct attribute.)
370 if (!specInfo->isExplicitInstantiationOrSpecialization())
371 return true;
372
373 return !fn->hasAttr<VisibilityAttr>();
374}
375
John McCalldf25c432013-02-16 00:17:33 +0000376/// Merge in template-related linkage and visibility for the given
377/// function template specialization.
378///
379/// We don't need a computation kind here because we can assume
380/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000381///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000382/// \param[out] LV the computation to use for the parent
John McCall5f46c482013-02-21 23:42:58 +0000383static void
384mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000385 const FunctionTemplateSpecializationInfo *specInfo,
386 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000387 bool considerVisibility =
388 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000389
390 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000391 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000392 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000393 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000394 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
395
396 // Merge information from the template arguments.
397 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000398 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000399 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000400}
401
John McCall5f46c482013-02-21 23:42:58 +0000402/// Does the given declaration have a direct visibility attribute
403/// that would match the given rules?
404static bool hasDirectVisibilityAttribute(const NamedDecl *D,
405 LVComputationKind computation) {
406 switch (computation) {
407 case LVForType:
408 case LVForExplicitType:
409 if (D->hasAttr<TypeVisibilityAttr>())
410 return true;
411 // fallthrough
412 case LVForValue:
413 case LVForExplicitValue:
414 if (D->hasAttr<VisibilityAttr>())
415 return true;
416 return false;
Rafael Espindola9551d3b2013-05-28 19:43:11 +0000417 case LVForLinkageOnly:
418 return false;
John McCall5f46c482013-02-21 23:42:58 +0000419 }
420 llvm_unreachable("bad visibility computation kind");
421}
422
John McCalld041a9b2013-02-20 01:54:26 +0000423/// Should we consider visibility associated with the template
424/// arguments and parameters of the given class template specialization?
425static bool shouldConsiderTemplateVisibility(
426 const ClassTemplateSpecializationDecl *spec,
427 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000428 // Include visibility from the template parameters and arguments
429 // only if this is not an explicit instantiation or specialization
430 // with direct explicit visibility (and note that implicit
431 // instantiations won't have a direct attribute).
432 //
433 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000434 // for an explicit specialization when computing the visibility of a
435 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000436 //
437 // This is a bit complex; let's unpack it.
438 //
439 // An explicit class specialization is an independent, top-level
440 // declaration. As such, if it or any of its members has an
441 // explicit visibility attribute, that must directly express the
442 // user's intent, and we should honor it. The same logic applies to
443 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000444
445 // Fast path: if this is not an explicit instantiation or
446 // specialization, we always want to consider template-related
447 // visibility restrictions.
448 if (!spec->isExplicitInstantiationOrSpecialization())
449 return true;
450
451 // This is the 'member thereof' check.
452 if (spec->isExplicitSpecialization() &&
453 hasExplicitVisibilityAlready(computation))
454 return false;
455
John McCall5f46c482013-02-21 23:42:58 +0000456 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000457}
458
459/// Merge in template-related linkage and visibility for the given
460/// class template specialization.
461static void mergeTemplateLV(LinkageInfo &LV,
462 const ClassTemplateSpecializationDecl *spec,
463 LVComputationKind computation) {
464 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000465
466 // Merge information from the template parameters, but ignore
467 // visibility if we're only considering template arguments.
468
John McCalld041a9b2013-02-20 01:54:26 +0000469 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000470 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000471 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000472 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000473 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000474
475 // Merge information from the template arguments. We ignore
476 // template-argument visibility if we've got an explicit
477 // instantiation with a visibility attribute.
478 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000479 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000480 if (considerVisibility)
481 LV.mergeVisibility(argsLV);
482 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000483}
484
Larisse Voufo5899e192014-07-02 23:08:34 +0000485/// Should we consider visibility associated with the template
486/// arguments and parameters of the given variable template
487/// specialization? As usual, follow class template specialization
488/// logic up to initialization.
489static bool shouldConsiderTemplateVisibility(
490 const VarTemplateSpecializationDecl *spec,
491 LVComputationKind computation) {
492 // Include visibility from the template parameters and arguments
493 // only if this is not an explicit instantiation or specialization
494 // with direct explicit visibility (and note that implicit
495 // instantiations won't have a direct attribute).
496 if (!spec->isExplicitInstantiationOrSpecialization())
497 return true;
498
499 // An explicit variable specialization is an independent, top-level
500 // declaration. As such, if it has an explicit visibility attribute,
501 // that must directly express the user's intent, and we should honor
502 // it.
503 if (spec->isExplicitSpecialization() &&
504 hasExplicitVisibilityAlready(computation))
505 return false;
506
507 return !hasDirectVisibilityAttribute(spec, computation);
508}
509
510/// Merge in template-related linkage and visibility for the given
511/// variable template specialization. As usual, follow class template
512/// specialization logic up to initialization.
513static void mergeTemplateLV(LinkageInfo &LV,
514 const VarTemplateSpecializationDecl *spec,
515 LVComputationKind computation) {
516 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
517
518 // Merge information from the template parameters, but ignore
519 // visibility if we're only considering template arguments.
520
521 VarTemplateDecl *temp = spec->getSpecializedTemplate();
522 LinkageInfo tempLV =
523 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
524 LV.mergeMaybeWithVisibility(tempLV,
525 considerVisibility && !hasExplicitVisibilityAlready(computation));
526
527 // Merge information from the template arguments. We ignore
528 // template-argument visibility if we've got an explicit
529 // instantiation with a visibility attribute.
530 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
531 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
532 if (considerVisibility)
533 LV.mergeVisibility(argsLV);
534 LV.mergeExternalVisibility(argsLV);
535}
536
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000537static bool useInlineVisibilityHidden(const NamedDecl *D) {
538 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000539 const LangOptions &Opts = D->getASTContext().getLangOpts();
540 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000541 return false;
542
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000543 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000544 if (!FD)
545 return false;
546
547 TemplateSpecializationKind TSK = TSK_Undeclared;
548 if (FunctionTemplateSpecializationInfo *spec
549 = FD->getTemplateSpecializationInfo()) {
550 TSK = spec->getTemplateSpecializationKind();
551 } else if (MemberSpecializationInfo *MSI =
552 FD->getMemberSpecializationInfo()) {
553 TSK = MSI->getTemplateSpecializationKind();
554 }
555
Craig Topper36250ad2014-05-12 05:36:57 +0000556 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000557 // InlineVisibilityHidden only applies to definitions, and
558 // isInlined() only gives meaningful answers on definitions
559 // anyway.
560 return TSK != TSK_ExplicitInstantiationDeclaration &&
561 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000562 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000563}
564
Rafael Espindola593537a2013-05-05 20:15:21 +0000565template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000566 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000567 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000568}
569
Richard Smith03c05032014-02-17 23:34:47 +0000570static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000571 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000572 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000573 return true;
574 return false;
575}
576
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000577static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
John McCalldf25c432013-02-16 00:17:33 +0000578 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000579 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000580 "Not a name having namespace scope");
581 ASTContext &Context = D->getASTContext();
582
583 // C++ [basic.link]p3:
584 // A name having namespace scope (3.3.6) has internal linkage if it
585 // is the name of
586 // - an object, reference, function or function template that is
587 // explicitly declared static; or,
588 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000589 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000590 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000591 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000592 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000593
Richard Smithdc0ef452012-10-19 06:37:48 +0000594 // - a non-volatile object or reference that is explicitly declared const
595 // or constexpr and neither explicitly declared extern nor previously
596 // declared to have external linkage; or (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000597 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000598 Var->getType().isConstQualified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000599 !Var->getType().isVolatileQualified()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000600 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000601 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000602 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000603
604 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000605 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000606 !isSingleLineLanguageLinkage(*Var))
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000607 return LinkageInfo::internal();
608 }
609
610 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
611 PrevVar = PrevVar->getPreviousDecl()) {
612 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
613 Var->getStorageClass() == SC_None)
614 return PrevVar->getLinkageAndVisibility();
615 // Explicitly declared static.
616 if (PrevVar->getStorageClass() == SC_Static)
617 return LinkageInfo::internal();
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000618 }
Alp Tokera2794f92014-01-22 07:29:52 +0000619 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000620 // C++ [temp]p4:
621 // A non-member function template can have internal linkage; any
622 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000623
624 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000625 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000626 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
David Majnemer18fac3b2014-12-10 22:58:14 +0000627 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
628 // - a data member of an anonymous union.
629 const VarDecl *VD = IFD->getVarDecl();
630 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
631 return getLVForNamespaceScopeDecl(VD, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000632 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000633 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000634
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000635 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000636 const auto *Var = dyn_cast<VarDecl>(D);
637 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smith97135cc2015-11-12 22:19:45 +0000638 // FIXME: In C++11 onwards, anonymous namespaces should give decls
639 // within them internal linkage, not unique external linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000640 if ((!Var || !isFirstInExternCContext(Var)) &&
641 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000642 return LinkageInfo::uniqueExternal();
643 }
John McCallb7139c42010-10-28 04:18:25 +0000644
John McCall457a04e2010-10-22 21:05:15 +0000645 // Set up the defaults.
646
647 // C99 6.2.2p5:
648 // If the declaration of an identifier for an object has file
649 // scope and no storage-class specifier, its linkage is
650 // external.
John McCallc273f242010-10-30 11:50:40 +0000651 LinkageInfo LV;
652
John McCalld041a9b2013-02-20 01:54:26 +0000653 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000654 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000655 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000656 } else {
657 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000658 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000659 for (const DeclContext *DC = D->getDeclContext();
660 !isa<TranslationUnitDecl>(DC);
661 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000662 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000663 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000664 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000665 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000666 break;
667 }
668 }
669 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000670
John McCalldf25c432013-02-16 00:17:33 +0000671 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000672 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000673 // Use global type/value visibility as appropriate.
674 Visibility globalVisibility;
675 if (computation == LVForValue) {
Larisse Voufo404e1422015-02-04 02:34:32 +0000676 globalVisibility = Context.getLangOpts().getValueVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000677 } else {
678 assert(computation == LVForType);
679 globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
680 }
681 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000682
683 // If we're paying attention to global visibility, apply
684 // -finline-visibility-hidden if this is an inline method.
685 if (useInlineVisibilityHidden(D))
686 LV.mergeVisibility(HiddenVisibility, true);
687 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000688 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000689
Douglas Gregorf73b2822009-11-25 22:24:25 +0000690 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000691
Douglas Gregorf73b2822009-11-25 22:24:25 +0000692 // A name having namespace scope has external linkage if it is the
693 // name of
694 //
695 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000696 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000697 // GCC applies the following optimization to variables and static
698 // data members, but not to functions:
699 //
John McCall457a04e2010-10-22 21:05:15 +0000700 // Modify the variable's LV by the LV of its type unless this is
701 // C or extern "C". This follows from [basic.link]p9:
702 // A type without linkage shall not be used as the type of a
703 // variable or function with external linkage unless
704 // - the entity has C language linkage, or
705 // - the entity is declared within an unnamed namespace, or
706 // - the entity is not used or is defined in the same
707 // translation unit.
708 // and [basic.link]p10:
709 // ...the types specified by all declarations referring to a
710 // given variable or function shall be identical...
711 // C does not have an equivalent rule.
712 //
John McCall5fe84122010-10-26 04:59:26 +0000713 // Ignore this if we've got an explicit attribute; the user
714 // probably knows what they're doing.
715 //
John McCall457a04e2010-10-22 21:05:15 +0000716 // Note that we don't want to make the variable non-external
717 // because of this, but unique-external linkage suits us.
Rafael Espindola593537a2013-05-05 20:15:21 +0000718 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000719 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Rafael Espindola4a5da442013-02-27 02:56:45 +0000720 if (TypeLV.getLinkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000721 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000722 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000723 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000724 }
725
John McCall23032652010-11-02 18:38:13 +0000726 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000727 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000728
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000729 // Note that Sema::MergeVarDecl already takes care of implementing
730 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
731 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000732
Larisse Voufo5899e192014-07-02 23:08:34 +0000733 // As per function and class template specializations (below),
734 // consider LV for the template and template arguments. We're at file
735 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000736 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000737 mergeTemplateLV(LV, spec, computation);
738 }
739
Douglas Gregorf73b2822009-11-25 22:24:25 +0000740 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000741 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000742 // In theory, we can modify the function's LV by the LV of its
743 // type unless it has C linkage (see comment above about variables
744 // for justification). In practice, GCC doesn't do this, so it's
745 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000746
John McCall23032652010-11-02 18:38:13 +0000747 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000748 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000749
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000750 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
751 // merging storage classes and visibility attributes, so we don't have to
752 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000753
John McCallf768aa72011-02-10 06:50:24 +0000754 // In C++, then if the type of the function uses a type with
755 // unique-external linkage, it's not legally usable from outside
756 // this translation unit. However, we should use the C linkage
757 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000758 if (Context.getLangOpts().CPlusPlus &&
Richard Smith50f4afc2013-05-12 23:17:59 +0000759 !Function->isInExternCContext()) {
760 // Only look at the type-as-written. If this function has an auto-deduced
761 // return type, we can't compute the linkage of that type because it could
762 // require looking at the linkage of this function, and we don't need this
763 // for correctness because the type is not part of the function's
764 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000765 // FIXME: This is a hack. We should be able to solve this circularity and
766 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000767 QualType TypeAsWritten = Function->getType();
768 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
769 TypeAsWritten = TSI->getType();
770 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
771 return LinkageInfo::uniqueExternal();
772 }
John McCallf768aa72011-02-10 06:50:24 +0000773
John McCall5f46c482013-02-21 23:42:58 +0000774 // Consider LV from the template and the template arguments.
775 // We're at file scope, so we do not need to worry about nested
776 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000777 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000778 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000779 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000780 }
781
Douglas Gregorf73b2822009-11-25 22:24:25 +0000782 // - a named class (Clause 9), or an unnamed class defined in a
783 // typedef declaration in which the class has the typedef name
784 // for linkage purposes (7.1.3); or
785 // - a named enumeration (7.2), or an unnamed enumeration
786 // defined in a typedef declaration in which the enumeration
787 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000788 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000789 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000790 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000791 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000792
John McCall457a04e2010-10-22 21:05:15 +0000793 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000794 // linkage of the template and template arguments. We're at file
795 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000796 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000797 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000798 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000799
800 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000801 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000802 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000803 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000804 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000805 return LinkageInfo::none();
806 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000807
808 // - a template, unless it is a function template that has
809 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000810 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000811 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000812 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000813 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000814 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
815
Douglas Gregorf73b2822009-11-25 22:24:25 +0000816 // - a namespace (7.3), unless it is declared within an unnamed
817 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000818 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
819 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000820
John McCall457a04e2010-10-22 21:05:15 +0000821 // By extension, we assign external linkage to Objective-C
822 // interfaces.
823 } else if (isa<ObjCInterfaceDecl>(D)) {
824 // fallout
825
Richard Smith97135cc2015-11-12 22:19:45 +0000826 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
827 // A typedef declaration has linkage if it gives a type a name for
828 // linkage purposes.
829 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
830 return LinkageInfo::none();
831
John McCall457a04e2010-10-22 21:05:15 +0000832 // Everything not covered here has no linkage.
833 } else {
John McCallc273f242010-10-30 11:50:40 +0000834 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000835 }
836
837 // If we ended up with non-external linkage, visibility should
838 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000839 if (LV.getLinkage() != ExternalLinkage)
840 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000841
John McCall457a04e2010-10-22 21:05:15 +0000842 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000843}
844
John McCalldf25c432013-02-16 00:17:33 +0000845static LinkageInfo getLVForClassMember(const NamedDecl *D,
846 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000847 // Only certain class members have linkage. Note that fields don't
848 // really have linkage, but it's convenient to say they do for the
849 // purposes of calculating linkage of pointer-to-data-member
850 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000851 //
852 // Templates also don't officially have linkage, but since we ignore
853 // the C++ standard and look at template arguments when determining
854 // linkage and visibility of a template specialization, we might hit
855 // a template template argument that way. If we do, we need to
856 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000857 if (!(isa<CXXMethodDecl>(D) ||
858 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000859 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000860 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000861 isa<TagDecl>(D) ||
862 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000863 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000864
John McCall07072662010-11-02 01:45:15 +0000865 LinkageInfo LV;
866
John McCall07072662010-11-02 01:45:15 +0000867 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000868 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000869 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000870 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000871 // If we're paying attention to global visibility, apply
872 // -finline-visibility-hidden if this is an inline method.
873 //
874 // Note that we do this before merging information about
875 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000876 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000877 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000878 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000879
880 // If this class member has an explicit visibility attribute, the only
881 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000882 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000883 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000884 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000885 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000886
John McCall5f46c482013-02-21 23:42:58 +0000887 LinkageInfo classLV =
888 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000889 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000890 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000891 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000892
Rafael Espindolae6190db2013-05-28 02:22:10 +0000893 if (!isExternallyVisible(classLV.getLinkage()))
894 return LinkageInfo::none();
895
896
John McCall5f46c482013-02-21 23:42:58 +0000897 // Otherwise, don't merge in classLV yet, because in certain cases
898 // we need to completely ignore the visibility from it.
899
900 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000901 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000902
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000903 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000904 // If the type of the function uses a type with unique-external
905 // linkage, it's not legally usable from outside this translation unit.
Nico Weber38267342015-04-22 03:44:51 +0000906 // But only look at the type-as-written. If this function has an
907 // auto-deduced return type, we can't compute the linkage of that type
908 // because it could require looking at the linkage of this function, and we
909 // don't need this for correctness because the type is not part of the
910 // function's signature.
911 // FIXME: This is a hack. We should be able to solve this circularity and
912 // the one in getLVForNamespaceScopeDecl for Functions some other way.
Faisal Valid2598e92013-10-08 04:15:04 +0000913 {
914 QualType TypeAsWritten = MD->getType();
915 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
916 TypeAsWritten = TSI->getType();
917 if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
918 return LinkageInfo::uniqueExternal();
919 }
John McCall457a04e2010-10-22 21:05:15 +0000920 // If this is a method template specialization, use the linkage for
921 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000922 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000923 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000924 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000925 if (spec->isExplicitSpecialization()) {
926 explicitSpecSuppressor = MD;
927 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
928 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
929 }
930 } else if (isExplicitMemberSpecialization(MD)) {
931 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000932 }
John McCall457a04e2010-10-22 21:05:15 +0000933
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000934 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
935 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000936 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000937 if (spec->isExplicitSpecialization()) {
938 explicitSpecSuppressor = spec;
939 } else {
940 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
941 if (isExplicitMemberSpecialization(temp)) {
942 explicitSpecSuppressor = temp->getTemplatedDecl();
943 }
944 }
945 } else if (isExplicitMemberSpecialization(RD)) {
946 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000947 }
948
John McCall37bb6c92010-10-29 22:22:43 +0000949 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000950 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
951 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000952 mergeTemplateLV(LV, spec, computation);
953
John McCall36cd5cc2010-10-30 09:18:49 +0000954 // Modify the variable's linkage by its type, but ignore the
955 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000956 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000957 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
958 LV.mergeVisibility(typeLV);
959 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000960
961 if (isExplicitMemberSpecialization(VD)) {
962 explicitSpecSuppressor = VD;
963 }
John McCalldf25c432013-02-16 00:17:33 +0000964
965 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000966 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +0000967 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000968 (!LV.isVisibilityExplicit() &&
969 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000970 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000971 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000972 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000973 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000974
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000975 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +0000976 if (isExplicitMemberSpecialization(redeclTemp)) {
977 explicitSpecSuppressor = temp->getTemplatedDecl();
978 }
979 }
John McCall37bb6c92010-10-29 22:22:43 +0000980 }
981
John McCall5f46c482013-02-21 23:42:58 +0000982 // We should never be looking for an attribute directly on a template.
983 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
984
985 // If this member is an explicit member specialization, and it has
986 // an explicit attribute, ignore visibility from the parent.
987 bool considerClassVisibility = true;
988 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000989 // optimization: hasDVA() is true only with explicit visibility.
990 LV.isVisibilityExplicit() &&
991 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000992 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
993 considerClassVisibility = false;
994 }
995
996 // Finally, merge in information from the class.
997 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000998 return LV;
John McCall8823c652010-08-13 08:35:10 +0000999}
1000
David Blaikie68e081d2011-12-20 02:48:34 +00001001void NamedDecl::anchor() { }
1002
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001003static LinkageInfo computeLVForDecl(const NamedDecl *D,
1004 LVComputationKind computation);
1005
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001006bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001007 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001008 return true;
John McCalld396b972011-02-08 19:01:05 +00001009
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001010 return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
Rafael Espindola50df3a02013-05-25 17:16:20 +00001011 getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001012}
1013
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001014ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1015 StringRef name = getName();
1016 if (name.empty()) return SFF_None;
1017
1018 if (name.front() == 'C')
1019 if (name == "CFStringCreateWithFormat" ||
1020 name == "CFStringCreateWithFormatAndArguments" ||
1021 name == "CFStringAppendFormat" ||
1022 name == "CFStringAppendFormatAndArguments")
1023 return SFF_CFString;
1024 return SFF_None;
1025}
1026
Rafael Espindola3ae00052013-05-13 00:12:11 +00001027Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001028 // We don't care about visibility here, so ask for the cheapest
1029 // possible visibility analysis.
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001030 return getLVForDecl(this, LVForLinkageOnly).getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001031}
1032
John McCallc273f242010-10-30 11:50:40 +00001033LinkageInfo NamedDecl::getLinkageAndVisibility() const {
John McCalldf25c432013-02-16 00:17:33 +00001034 LVComputationKind computation =
1035 (usesTypeVisibility(this) ? LVForType : LVForValue);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001036 return getLVForDecl(this, computation);
John McCall033caa52010-10-29 00:29:13 +00001037}
Ted Kremenek926d8602010-04-20 23:15:35 +00001038
Rafael Espindola9ad61122013-11-26 16:09:08 +00001039static Optional<Visibility>
1040getExplicitVisibilityAux(const NamedDecl *ND,
1041 NamedDecl::ExplicitVisibilityKind kind,
1042 bool IsMostRecent) {
1043 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1044
Rafael Espindola3a52c442013-02-26 19:33:14 +00001045 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001046 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001047 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001048
Rafael Espindola3a52c442013-02-26 19:33:14 +00001049 // If this is a member class of a specialization of a class template
1050 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001051 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001052 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1053 if (InstantiatedFrom)
1054 return getVisibilityOf(InstantiatedFrom, kind);
1055 }
1056
1057 // If there wasn't explicit visibility there, and this is a
1058 // specialization of a class template, check for visibility
1059 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001060 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001061 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1062 kind);
1063
1064 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001065 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001066 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1067 if (MostRecent != ND)
1068 return getExplicitVisibilityAux(MostRecent, kind, true);
1069 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001070
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001071 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001072 if (Var->isStaticDataMember()) {
1073 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1074 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001075 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001076 }
1077
David Majnemer35b02bc2014-04-29 07:32:26 +00001078 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1079 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1080 kind);
1081
David Blaikie7a30dc52013-02-21 01:47:18 +00001082 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001083 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001084 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001085 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001086 // If the function is a specialization of a template with an
1087 // explicit visibility attribute, use that.
1088 if (FunctionTemplateSpecializationInfo *templateInfo
1089 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001090 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1091 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001092
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001093 // If the function is a member of a specialization of a class template
1094 // and the corresponding decl has explicit visibility, use that.
1095 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1096 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001097 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001098
David Blaikie7a30dc52013-02-21 01:47:18 +00001099 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001100 }
1101
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001102 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001103 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001104 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001105
David Blaikie7a30dc52013-02-21 01:47:18 +00001106 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001107}
1108
Rafael Espindola9ad61122013-11-26 16:09:08 +00001109Optional<Visibility>
1110NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1111 return getExplicitVisibilityAux(this, kind, false);
1112}
1113
Eli Friedman7e346a82013-07-01 20:22:57 +00001114static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1115 LVComputationKind computation) {
1116 // This lambda has its linkage/visibility determined by its owner.
1117 if (ContextDecl) {
1118 if (isa<ParmVarDecl>(ContextDecl))
1119 DC = ContextDecl->getDeclContext()->getRedeclContext();
1120 else
1121 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1122 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001123
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001124 if (const auto *ND = dyn_cast<NamedDecl>(DC))
Eli Friedman7e346a82013-07-01 20:22:57 +00001125 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001126
Eli Friedman7e346a82013-07-01 20:22:57 +00001127 return LinkageInfo::external();
1128}
1129
John McCalldf25c432013-02-16 00:17:33 +00001130static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1131 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001132 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001133 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001134 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001135 return LinkageInfo::uniqueExternal();
1136
1137 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001138 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
John McCalldf25c432013-02-16 00:17:33 +00001139 return LinkageInfo::internal();
1140
1141 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001142 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001143 if (Optional<Visibility> Vis =
1144 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001145 LV.mergeVisibility(*Vis, true);
1146 }
1147
1148 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1149 // merging storage classes and visibility attributes, so we don't have to
1150 // look at previous decls in here.
1151
1152 return LV;
1153 }
1154
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001155 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001156 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001157 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001158 return LinkageInfo::uniqueExternal();
1159
John McCalldf25c432013-02-16 00:17:33 +00001160 LinkageInfo LV;
1161 if (Var->getStorageClass() == SC_PrivateExtern)
1162 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001163 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001164 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001165 LV.mergeVisibility(*Vis, true);
1166 }
1167
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001168 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1169 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1170 if (PrevLV.getLinkage())
1171 LV.setLinkage(PrevLV.getLinkage());
1172 LV.mergeVisibility(PrevLV);
1173 }
1174
John McCalldf25c432013-02-16 00:17:33 +00001175 return LV;
1176 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001177
1178 if (!Var->isStaticLocal())
1179 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001180 }
1181
Rafael Espindolaa4184182013-06-17 20:04:51 +00001182 ASTContext &Context = D->getASTContext();
1183 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001184 return LinkageInfo::none();
1185
Eli Friedman7e346a82013-07-01 20:22:57 +00001186 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001187 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001188 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001189
Eli Friedman7e346a82013-07-01 20:22:57 +00001190 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001191 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001192 if (!BD->getBlockManglingNumber())
1193 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001194
Eli Friedman7e346a82013-07-01 20:22:57 +00001195 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1196 BD->getBlockManglingContextDecl(), computation);
1197 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001198 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001199 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001200 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001201 return LinkageInfo::none();
1202
1203 LV = getLVForDecl(FD, computation);
1204 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001205 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001206 return LinkageInfo::none();
1207 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1208 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001209}
1210
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001211static inline const CXXRecordDecl*
1212getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1213 const CXXRecordDecl *Ret = Record;
1214 while (Record && Record->isLambda()) {
1215 Ret = Record;
1216 if (!Record->getParent()) break;
1217 // Get the Containing Class of this Lambda Class
1218 Record = dyn_cast_or_null<CXXRecordDecl>(
1219 Record->getParent()->getParent());
1220 }
1221 return Ret;
1222}
1223
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001224static LinkageInfo computeLVForDecl(const NamedDecl *D,
1225 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001226 // Internal_linkage attribute overrides other considerations.
1227 if (D->hasAttr<InternalLinkageAttr>())
1228 return LinkageInfo::internal();
1229
Ted Kremenek926d8602010-04-20 23:15:35 +00001230 // Objective-C: treat all Objective-C declarations as having external
1231 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001232 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001233 default:
1234 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001235
1236 // Per C++ [basic.link]p2, only the names of objects, references,
1237 // functions, types, templates, namespaces, and values ever have linkage.
1238 //
1239 // Note that the name of a typedef, namespace alias, using declaration,
1240 // and so on are not the name of the corresponding type, namespace, or
1241 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001242 case Decl::ImplicitParam:
1243 case Decl::Label:
1244 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001245 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001246 case Decl::Using:
1247 case Decl::UsingShadow:
1248 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001249 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001250
Richard Smith26210db2015-11-13 03:52:13 +00001251 case Decl::EnumConstant:
1252 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1253 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1254
Richard Smith97135cc2015-11-12 22:19:45 +00001255 case Decl::Typedef:
1256 case Decl::TypeAlias:
1257 // A typedef declaration has linkage if it gives a type a name for
1258 // linkage purposes.
Ben Langmuir90717ad2015-11-14 03:26:14 +00001259 if (!D->getASTContext().getLangOpts().CPlusPlus ||
1260 !cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001261 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1262 return LinkageInfo::none();
1263 break;
1264
John McCall457a04e2010-10-22 21:05:15 +00001265 case Decl::TemplateTemplateParm: // count these as external
1266 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001267 case Decl::ObjCAtDefsField:
1268 case Decl::ObjCCategory:
1269 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001270 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001271 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001272 case Decl::ObjCMethod:
1273 case Decl::ObjCProperty:
1274 case Decl::ObjCPropertyImpl:
1275 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +00001276 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001277
1278 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001279 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001280 if (Record->isLambda()) {
1281 if (!Record->getLambdaManglingNumber()) {
1282 // This lambda has no mangling number, so it's internal.
1283 return LinkageInfo::internal();
1284 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001285
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001286 // This lambda has its linkage/visibility determined:
1287 // - either by the outermost lambda if that lambda has no mangling
1288 // number.
1289 // - or by the parent of the outer most lambda
1290 // This prevents infinite recursion in settings such as nested lambdas
1291 // used in NSDMI's, for e.g.
1292 // struct L {
1293 // int t{};
1294 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1295 // };
1296 const CXXRecordDecl *OuterMostLambda =
1297 getOutermostEnclosingLambda(Record);
1298 if (!OuterMostLambda->getLambdaManglingNumber())
1299 return LinkageInfo::internal();
1300
1301 return getLVForClosure(
1302 OuterMostLambda->getDeclContext()->getRedeclContext(),
1303 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001304 }
1305
1306 break;
1307 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001308 }
1309
Douglas Gregorf73b2822009-11-25 22:24:25 +00001310 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001311 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001312 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001313
1314 // C++ [basic.link]p5:
1315 // In addition, a member function, static data member, a named
1316 // class or enumeration of class scope, or an unnamed class or
1317 // enumeration defined in a class-scope typedef declaration such
1318 // that the class or enumeration has the typedef name for linkage
1319 // purposes (7.1.3), has external linkage if the name of the class
1320 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001321 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001322 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001323
1324 // C++ [basic.link]p6:
1325 // The name of a function declared in block scope and the name of
1326 // an object declared by a block scope extern declaration have
1327 // linkage. If there is a visible declaration of an entity with
1328 // linkage having the same name and type, ignoring entities
1329 // declared outside the innermost enclosing namespace scope, the
1330 // block scope declaration declares that same entity and receives
1331 // the linkage of the previous declaration. If there is more than
1332 // one such matching entity, the program is ill-formed. Otherwise,
1333 // if no matching entity is found, the block scope entity receives
1334 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001335 if (D->getDeclContext()->isFunctionOrMethod())
1336 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001337
1338 // C++ [basic.link]p6:
1339 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001340 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001341}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001342
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001343namespace clang {
1344class LinkageComputer {
1345public:
1346 static LinkageInfo getLVForDecl(const NamedDecl *D,
1347 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001348 // Internal_linkage attribute overrides other considerations.
1349 if (D->hasAttr<InternalLinkageAttr>())
1350 return LinkageInfo::internal();
1351
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001352 if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1353 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1354
1355 LinkageInfo LV = computeLVForDecl(D, computation);
1356 if (D->hasCachedLinkage())
1357 assert(D->getCachedLinkage() == LV.getLinkage());
1358
1359 D->setCachedLinkage(LV.getLinkage());
1360
1361#ifndef NDEBUG
1362 // In C (because of gnu inline) and in c++ with microsoft extensions an
1363 // static can follow an extern, so we can have two decls with different
1364 // linkages.
1365 const LangOptions &Opts = D->getASTContext().getLangOpts();
1366 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1367 return LV;
1368
1369 // We have just computed the linkage for this decl. By induction we know
1370 // that all other computed linkages match, check that the one we just
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001371 // computed also does.
Craig Topper36250ad2014-05-12 05:36:57 +00001372 NamedDecl *Old = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +00001373 for (auto I : D->redecls()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001374 auto *T = cast<NamedDecl>(I);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001375 if (T == D)
1376 continue;
Ismail Pazarbasibe19ae02014-03-06 21:48:45 +00001377 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001378 Old = T;
1379 break;
1380 }
1381 }
1382 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1383#endif
1384
1385 return LV;
1386 }
1387};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001388}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001389
1390static LinkageInfo getLVForDecl(const NamedDecl *D,
1391 LVComputationKind computation) {
1392 return clang::LinkageComputer::getLVForDecl(D, computation);
1393}
1394
Douglas Gregor2ada0482009-02-04 17:27:36 +00001395std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001396 std::string QualName;
1397 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001398 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001399 return OS.str();
1400}
1401
1402void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1403 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1404}
1405
1406void NamedDecl::printQualifiedName(raw_ostream &OS,
1407 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001408 const DeclContext *Ctx = getDeclContext();
1409
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001410 if (Ctx->isFunctionOrMethod()) {
1411 printName(OS);
1412 return;
1413 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001414
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001415 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001416 ContextsTy Contexts;
1417
1418 // Collect contexts.
1419 while (Ctx && isa<NamedDecl>(Ctx)) {
1420 Contexts.push_back(Ctx);
1421 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001422 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001423
1424 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1425 I != E; ++I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001426 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001427 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001428 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00001429 TemplateSpecializationType::PrintTemplateArgumentList(OS,
1430 TemplateArgs.data(),
1431 TemplateArgs.size(),
1432 P);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001433 } else if (const auto *ND = dyn_cast<NamespaceDecl>(*I)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001434 if (P.SuppressUnwrittenScope &&
1435 (ND->isAnonymousNamespace() || ND->isInline()))
1436 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001437 if (ND->isAnonymousNamespace()) {
1438 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1439 : "(anonymous namespace)");
1440 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001441 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001442 OS << *ND;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001443 } else if (const auto *RD = dyn_cast<RecordDecl>(*I)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001444 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001445 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001446 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001447 OS << *RD;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001448 } else if (const auto *FD = dyn_cast<FunctionDecl>(*I)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001449 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001450 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001451 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001452
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001453 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001454 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001455 unsigned NumParams = FD->getNumParams();
1456 for (unsigned i = 0; i < NumParams; ++i) {
1457 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001458 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001459 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001460 }
1461
1462 if (FT->isVariadic()) {
1463 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001464 OS << ", ";
1465 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001466 }
1467 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001468 OS << ')';
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001469 } else if (const auto *ED = dyn_cast<EnumDecl>(*I)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001470 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1471 // enumerator is declared in the scope that immediately contains
1472 // the enum-specifier. Each scoped enumerator is declared in the
1473 // scope of the enumeration.
1474 if (ED->isScoped() || ED->getIdentifier())
1475 OS << *ED;
1476 else
1477 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001478 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001479 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001480 }
1481 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001482 }
1483
John McCalla2a3f7d2010-03-16 21:48:18 +00001484 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001485 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001486 else
David Blaikieabe1a392014-04-02 05:58:29 +00001487 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001488}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001489
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001490void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1491 const PrintingPolicy &Policy,
1492 bool Qualified) const {
1493 if (Qualified)
1494 printQualifiedName(OS, Policy);
1495 else
1496 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001497}
1498
Richard Smithe8292b12015-02-10 03:28:10 +00001499template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1500 return true;
1501}
1502static bool isRedeclarableImpl(...) { return false; }
1503static bool isRedeclarable(Decl::Kind K) {
1504 switch (K) {
1505#define DECL(Type, Base) \
1506 case Decl::Type: \
1507 return isRedeclarableImpl((Type##Decl *)nullptr);
1508#define ABSTRACT_DECL(DECL)
1509#include "clang/AST/DeclNodes.inc"
1510 }
1511 llvm_unreachable("unknown decl kind");
1512}
1513
1514bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001515 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1516
Richard Smithfe620d22015-03-05 23:24:12 +00001517 // Never replace one imported declaration with another; we need both results
1518 // when re-exporting.
1519 if (OldD->isFromASTFile() && isFromASTFile())
1520 return false;
1521
Richard Smith5cd86f82015-11-03 03:13:11 +00001522 // A kind mismatch implies that the declaration is not replaced.
1523 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001524 return false;
1525
Richard Smith5cd86f82015-11-03 03:13:11 +00001526 // For method declarations, we never replace. (Why?)
1527 if (isa<ObjCMethodDecl>(this))
1528 return false;
1529
1530 // For parameters, pick the newer one. This is either an error or (in
1531 // Objective-C) permitted as an extension.
1532 if (isa<ParmVarDecl>(this))
1533 return true;
1534
Richard Smithe8292b12015-02-10 03:28:10 +00001535 // Inline namespaces can give us two declarations with the same
1536 // name and kind in the same scope but different contexts; we should
1537 // keep both declarations in this case.
1538 if (!this->getDeclContext()->getRedeclContext()->Equals(
1539 OldD->getDeclContext()->getRedeclContext()))
1540 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001541
Richard Smith5cd86f82015-11-03 03:13:11 +00001542 // Using declarations can be replaced if they import the same name from the
1543 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001544 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001545 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001546 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001547 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001548 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001549 }
Richard Smithe8292b12015-02-10 03:28:10 +00001550 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001551 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001552 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001553 Context.getCanonicalNestedNameSpecifier(
1554 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1555 }
1556
Richard Smithe8292b12015-02-10 03:28:10 +00001557 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
Richard Smith5cd86f82015-11-03 03:13:11 +00001558 // They can be replaced if they nominate the same namespace.
1559 // FIXME: Is this true even if they have different module visibility?
Richard Smithe8292b12015-02-10 03:28:10 +00001560 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1561 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1562 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1563 ->getOriginalNamespace();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001564
Richard Smith5cd86f82015-11-03 03:13:11 +00001565 if (isRedeclarable(getKind())) {
1566 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1567 return false;
1568
1569 if (IsKnownNewer)
1570 return true;
1571
Richard Smithe8292b12015-02-10 03:28:10 +00001572 // Check whether this is actually newer than OldD. We want to keep the
1573 // newer declaration. This loop will usually only iterate once, because
1574 // OldD is usually the previous declaration.
1575 for (auto D : redecls()) {
1576 if (D == OldD)
1577 break;
1578
1579 // If we reach the canonical declaration, then OldD is not actually older
1580 // than this one.
1581 //
1582 // FIXME: In this case, we should not add this decl to the lookup table.
1583 if (D->isCanonicalDecl())
1584 return false;
1585 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001586
1587 // It's a newer declaration of the same kind of declaration in the same
1588 // scope: we want this decl instead of the existing one.
1589 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001590 }
1591
Richard Smith5cd86f82015-11-03 03:13:11 +00001592 // In all other cases, we need to keep both declarations in case they have
1593 // different visibility. Any attempt to use the name will result in an
1594 // ambiguity if more than one is visible.
1595 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001596}
1597
Douglas Gregoreddf4332009-02-24 20:03:32 +00001598bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001599 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001600}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001601
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001602NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001603 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001604 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001605 ND = UD->getTargetDecl();
1606
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001607 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001608 return AD->getClassInterface();
1609
Richard Smithf2005d32015-12-29 23:34:32 +00001610 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1611 return AD->getNamespace();
1612
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001613 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001614}
1615
John McCalla8ae2222010-04-06 21:38:20 +00001616bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001617 if (!isCXXClassMember())
1618 return false;
1619
John McCalla8ae2222010-04-06 21:38:20 +00001620 const NamedDecl *D = this;
1621 if (isa<UsingShadowDecl>(D))
1622 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1623
John McCall5e77d762013-04-16 07:28:30 +00001624 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001625 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001626 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001627 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001628 return false;
1629}
1630
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001631//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001632// DeclaratorDecl Implementation
1633//===----------------------------------------------------------------------===//
1634
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001635template <typename DeclT>
1636static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1637 if (decl->getNumTemplateParameterLists() > 0)
1638 return decl->getTemplateParameterList(0)->getTemplateLoc();
1639 else
1640 return decl->getInnerLocStart();
1641}
1642
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001643SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001644 TypeSourceInfo *TSI = getTypeSourceInfo();
1645 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001646 return SourceLocation();
1647}
1648
Douglas Gregor14454802011-02-25 02:25:35 +00001649void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1650 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001651 // Make sure the extended decl info is allocated.
1652 if (!hasExtInfo()) {
1653 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001654 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001655 // Allocate external info struct.
1656 DeclInfo = new (getASTContext()) ExtInfo;
1657 // Restore savedTInfo into (extended) decl info.
1658 getExtInfo()->TInfo = savedTInfo;
1659 }
1660 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001661 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001662 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001663 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001664 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001665 if (getExtInfo()->NumTemplParamLists == 0) {
1666 // Save type source info pointer.
1667 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1668 // Deallocate the extended decl info.
1669 getASTContext().Deallocate(getExtInfo());
1670 // Restore savedTInfo into (non-extended) decl info.
1671 DeclInfo = savedTInfo;
1672 }
1673 else
1674 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001675 }
1676 }
1677}
1678
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001679void DeclaratorDecl::setTemplateParameterListsInfo(
1680 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1681 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001682 // Make sure the extended decl info is allocated.
1683 if (!hasExtInfo()) {
1684 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001685 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001686 // Allocate external info struct.
1687 DeclInfo = new (getASTContext()) ExtInfo;
1688 // Restore savedTInfo into (extended) decl info.
1689 getExtInfo()->TInfo = savedTInfo;
1690 }
1691 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001692 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001693}
1694
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001695SourceLocation DeclaratorDecl::getOuterLocStart() const {
1696 return getTemplateOrInnerLocStart(this);
1697}
1698
Abramo Bagnaraea947882011-03-08 16:41:52 +00001699namespace {
1700
1701// Helper function: returns true if QT is or contains a type
1702// having a postfix component.
1703bool typeIsPostfix(clang::QualType QT) {
1704 while (true) {
1705 const Type* T = QT.getTypePtr();
1706 switch (T->getTypeClass()) {
1707 default:
1708 return false;
1709 case Type::Pointer:
1710 QT = cast<PointerType>(T)->getPointeeType();
1711 break;
1712 case Type::BlockPointer:
1713 QT = cast<BlockPointerType>(T)->getPointeeType();
1714 break;
1715 case Type::MemberPointer:
1716 QT = cast<MemberPointerType>(T)->getPointeeType();
1717 break;
1718 case Type::LValueReference:
1719 case Type::RValueReference:
1720 QT = cast<ReferenceType>(T)->getPointeeType();
1721 break;
1722 case Type::PackExpansion:
1723 QT = cast<PackExpansionType>(T)->getPattern();
1724 break;
1725 case Type::Paren:
1726 case Type::ConstantArray:
1727 case Type::DependentSizedArray:
1728 case Type::IncompleteArray:
1729 case Type::VariableArray:
1730 case Type::FunctionProto:
1731 case Type::FunctionNoProto:
1732 return true;
1733 }
1734 }
1735}
1736
1737} // namespace
1738
1739SourceRange DeclaratorDecl::getSourceRange() const {
1740 SourceLocation RangeEnd = getLocation();
1741 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001742 // If the declaration has no name or the type extends past the name take the
1743 // end location of the type.
1744 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001745 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1746 }
1747 return SourceRange(getOuterLocStart(), RangeEnd);
1748}
1749
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001750void QualifierInfo::setTemplateParameterListsInfo(
1751 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001752 // Free previous template parameters (if any).
1753 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001754 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001755 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001756 NumTemplParamLists = 0;
1757 }
1758 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001759 if (!TPLists.empty()) {
1760 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1761 NumTemplParamLists = TPLists.size();
1762 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001763 }
1764}
1765
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001766//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001767// VarDecl Implementation
1768//===----------------------------------------------------------------------===//
1769
Sebastian Redl833ef452010-01-26 22:01:41 +00001770const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1771 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001772 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001773 case SC_Auto: return "auto";
1774 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001775 case SC_PrivateExtern: return "__private_extern__";
1776 case SC_Register: return "register";
1777 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001778 }
1779
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001780 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001781}
1782
Richard Smith053f6c62014-05-16 23:01:30 +00001783VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1784 SourceLocation StartLoc, SourceLocation IdLoc,
1785 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1786 StorageClass SC)
1787 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1788 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001789 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1790 "VarDeclBitfields too large!");
1791 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1792 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001793 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1794 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001795 AllBits = 0;
1796 VarDeclBits.SClass = SC;
1797 // Everything else is implicitly initialized to false.
1798}
1799
Abramo Bagnaradff19302011-03-08 08:55:46 +00001800VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1801 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001802 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001803 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001804 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001805}
1806
Douglas Gregor72172e92012-01-05 21:55:30 +00001807VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001808 return new (C, ID)
1809 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1810 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001811}
1812
Douglas Gregorbf62d642010-12-06 18:36:25 +00001813void VarDecl::setStorageClass(StorageClass SC) {
1814 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001815 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001816}
1817
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001818VarDecl::TLSKind VarDecl::getTLSKind() const {
1819 switch (VarDeclBits.TSCSpec) {
1820 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001821 if (!hasAttr<ThreadAttr>() &&
1822 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1823 getASTContext().getTargetInfo().isTLSSupported() &&
1824 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001825 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001826 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1827 LangOptions::MSVC2015)) ||
1828 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001829 ? TLS_Dynamic
1830 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001831 case TSCS___thread: // Fall through.
1832 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001833 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001834 case TSCS_thread_local:
1835 return TLS_Dynamic;
1836 }
1837 llvm_unreachable("Unknown thread storage class specifier!");
1838}
1839
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001840SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001841 if (const Expr *Init = getInit()) {
1842 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001843 // If Init is implicit, ignore its source range and fallback on
1844 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1845 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001846 return SourceRange(getOuterLocStart(), InitEnd);
1847 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001848 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001849}
1850
Rafael Espindola88510672013-01-04 21:18:45 +00001851template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001852static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001853 // C++ [dcl.link]p1: All function types, function names with external linkage,
1854 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001855 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001856 return NoLanguageLinkage;
1857
1858 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001859 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001860 ASTContext &Context = D.getASTContext();
1861 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001862 return CLanguageLinkage;
1863
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001864 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1865 // language linkage of the names of class members and the function type of
1866 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001867 const DeclContext *DC = D.getDeclContext();
1868 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001869 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001870
1871 // If the first decl is in an extern "C" context, any other redeclaration
1872 // will have C language linkage. If the first one is not in an extern "C"
1873 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001874 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001875 return CLanguageLinkage;
1876 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001877}
1878
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001879template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001880static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001881 // Since the context is ignored for class members, they can only have C++
1882 // language linkage or no language linkage.
1883 const DeclContext *DC = D.getDeclContext();
1884 if (DC->isRecord()) {
1885 assert(D.getASTContext().getLangOpts().CPlusPlus);
1886 return false;
1887 }
1888
1889 return D.getLanguageLinkage() == CLanguageLinkage;
1890}
1891
Rafael Espindolaf4187652013-02-14 01:18:37 +00001892LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001893 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001894}
1895
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001896bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001897 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001898}
1899
Rafael Espindola593537a2013-05-05 20:15:21 +00001900bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001901 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001902}
1903
1904bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001905 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001906}
1907
Rafael Espindola8db352d2013-10-17 15:37:26 +00001908VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001909
Nico Weber7f5015a2015-04-15 21:53:00 +00001910VarDecl::DefinitionKind
1911VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001912 // C++ [basic.def]p2:
1913 // A declaration is a definition unless [...] it contains the 'extern'
1914 // specifier or a linkage-specification and neither an initializer [...],
1915 // it declares a static data member in a class declaration [...].
Richard Smith8809a0c2013-09-27 20:14:12 +00001916 // C++1y [temp.expl.spec]p15:
1917 // An explicit specialization of a static data member or an explicit
1918 // specialization of a static data member template is a definition if the
1919 // declaration includes an initializer; otherwise, it is a declaration.
1920 //
1921 // FIXME: How do you declare (but not define) a partial specialization of
1922 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00001923 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001924 if (isOutOfLine() &&
1925 (hasInit() ||
1926 // If the first declaration is out-of-line, this may be an
1927 // instantiation of an out-of-line partial specialization of a variable
1928 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001929 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001930 ? getTemplateSpecializationKind() == TSK_Undeclared
1931 : getTemplateSpecializationKind() !=
1932 TSK_ExplicitSpecialization) ||
1933 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001934 return Definition;
1935 else
1936 return DeclarationOnly;
1937 }
1938 // C99 6.7p5:
1939 // A definition of an identifier is a declaration for that identifier that
1940 // [...] causes storage to be reserved for that object.
1941 // Note: that applies for all non-file-scope objects.
1942 // C99 6.9.2p1:
1943 // If the declaration of an identifier for an object has file scope and an
1944 // initializer, the declaration is an external definition for the identifier
1945 if (hasInit())
1946 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001947
David Majnemerdd0bed12015-05-14 05:19:20 +00001948 if (hasAttr<AliasAttr>())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001949 return Definition;
1950
David Majnemerdd0bed12015-05-14 05:19:20 +00001951 if (const auto *SAA = getAttr<SelectAnyAttr>())
1952 if (!SAA->isInherited())
1953 return Definition;
1954
Richard Smith8809a0c2013-09-27 20:14:12 +00001955 // A variable template specialization (other than a static data member
1956 // template or an explicit specialization) is a declaration until we
1957 // instantiate its initializer.
1958 if (isa<VarTemplateSpecializationDecl>(this) &&
1959 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1960 return DeclarationOnly;
1961
Nico Weber608e7682015-04-15 23:04:24 +00001962 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00001963 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001964
Rafael Espindolabff59562013-04-25 12:11:36 +00001965 // [dcl.link] p7:
1966 // A declaration directly contained in a linkage-specification is treated
1967 // as if it contains the extern specifier for the purpose of determining
1968 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00001969 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00001970 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00001971
Sebastian Redl35351a92010-01-31 22:27:38 +00001972 // C99 6.9.2p2:
1973 // A declaration of an object that has file scope without an initializer,
1974 // and without a storage class specifier or the scs 'static', constitutes
1975 // a tentative definition.
1976 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001977 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001978 return TentativeDefinition;
1979
1980 // What's left is (in C, block-scope) declarations without initializers or
1981 // external storage. These are definitions.
1982 return Definition;
1983}
1984
Sebastian Redl35351a92010-01-31 22:27:38 +00001985VarDecl *VarDecl::getActingDefinition() {
1986 DefinitionKind Kind = isThisDeclarationADefinition();
1987 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00001988 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001989
Craig Topper36250ad2014-05-12 05:36:57 +00001990 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00001991 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00001992 for (auto I : First->redecls()) {
1993 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00001994 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00001995 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00001996 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00001997 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00001998 }
1999 return LastTentative;
2000}
2001
Daniel Dunbar9d355812012-03-09 01:51:51 +00002002VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002003 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002004 for (auto I : First->redecls()) {
2005 if (I->isThisDeclarationADefinition(C) == Definition)
2006 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002007 }
Craig Topper36250ad2014-05-12 05:36:57 +00002008 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002009}
2010
Daniel Dunbar9d355812012-03-09 01:51:51 +00002011VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002012 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002013
Rafael Espindola8db352d2013-10-17 15:37:26 +00002014 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002015 for (auto I : First->redecls()) {
2016 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002017 if (Kind == Definition)
2018 break;
2019 }
John McCall37bb6c92010-10-29 22:22:43 +00002020
2021 return Kind;
2022}
2023
Sebastian Redl5ca79842010-02-01 20:16:42 +00002024const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002025 for (auto I : redecls()) {
2026 if (auto Expr = I->getInit()) {
2027 D = I;
2028 return Expr;
2029 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002030 }
Craig Topper36250ad2014-05-12 05:36:57 +00002031 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002032}
2033
Chandler Carruth813faed2015-12-30 02:51:00 +00002034bool VarDecl::hasInit() const {
2035 if (auto *P = dyn_cast<ParmVarDecl>(this))
2036 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2037 return false;
2038
2039 return !Init.isNull();
2040}
2041
2042Expr *VarDecl::getInit() {
2043 if (!hasInit())
2044 return nullptr;
2045
2046 if (auto *S = Init.dyn_cast<Stmt *>())
2047 return cast<Expr>(S);
2048
2049 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2050}
2051
2052Stmt **VarDecl::getInitAddress() {
2053 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2054 return &ES->Value;
2055
2056 return Init.getAddrOfPtr1();
2057}
2058
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002059bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002060 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002061 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002062
2063 if (!isStaticDataMember())
2064 return false;
2065
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002066 // If this static data member was instantiated from a static data member of
2067 // a class template, check whether that static data member was defined
2068 // out-of-line.
2069 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2070 return VD->isOutOfLine();
2071
2072 return false;
2073}
2074
Douglas Gregor1d957a32009-10-27 18:42:08 +00002075VarDecl *VarDecl::getOutOfLineDefinition() {
2076 if (!isStaticDataMember())
Craig Topper36250ad2014-05-12 05:36:57 +00002077 return nullptr;
2078
Aaron Ballman86c93902014-03-06 23:45:36 +00002079 for (auto RD : redecls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002080 if (RD->getLexicalDeclContext()->isFileContext())
Aaron Ballman86c93902014-03-06 23:45:36 +00002081 return RD;
Douglas Gregor1d957a32009-10-27 18:42:08 +00002082 }
Craig Topper36250ad2014-05-12 05:36:57 +00002083
2084 return nullptr;
Douglas Gregor1d957a32009-10-27 18:42:08 +00002085}
2086
Douglas Gregord5058122010-02-11 01:19:42 +00002087void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002088 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002089 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002090 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002091 }
2092
2093 Init = I;
2094}
2095
Daniel Dunbar9d355812012-03-09 01:51:51 +00002096bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002097 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002098
Richard Smith35ecb362012-03-02 04:14:40 +00002099 if (!Lang.CPlusPlus)
2100 return false;
2101
2102 // In C++11, any variable of reference type can be used in a constant
2103 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002104 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002105 return true;
2106
2107 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002108 // not require the variable to be non-volatile, but we consider this to be a
2109 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002110 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002111 return false;
2112
2113 // In C++, const, non-volatile variables of integral or enumeration types
2114 // can be used in constant expressions.
2115 if (getType()->isIntegralOrEnumerationType())
2116 return true;
2117
Richard Smith35ecb362012-03-02 04:14:40 +00002118 // Additionally, in C++11, non-volatile constexpr variables can be used in
2119 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002120 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002121}
2122
Richard Smithd0b4dd62011-12-19 06:19:21 +00002123/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2124/// form, which contains extra information on the evaluated value of the
2125/// initializer.
2126EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002127 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002128 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002129 // Note: EvaluatedStmt contains an APValue, which usually holds
2130 // resources not allocated from the ASTContext. We need to do some
2131 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2132 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002133 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002134 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002135 Init = Eval;
2136 }
2137 return Eval;
2138}
2139
Richard Smithdafff942012-01-14 04:30:29 +00002140APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002141 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002142 return evaluateValue(Notes);
2143}
2144
Manuel Klimeka7328992013-06-03 13:51:33 +00002145namespace {
2146// Destroy an APValue that was allocated in an ASTContext.
2147void DestroyAPValue(void* UntypedValue) {
2148 static_cast<APValue*>(UntypedValue)->~APValue();
2149}
2150} // namespace
2151
Richard Smithdafff942012-01-14 04:30:29 +00002152APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002153 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002154 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2155
2156 // We only produce notes indicating why an initializer is non-constant the
2157 // first time it is evaluated. FIXME: The notes won't always be emitted the
2158 // first time we try evaluation, so might not be produced at all.
2159 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002160 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002161
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002162 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002163 assert(!Init->isValueDependent());
2164
2165 if (Eval->IsEvaluating) {
2166 // FIXME: Produce a diagnostic for self-initialization.
2167 Eval->CheckedICE = true;
2168 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002169 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002170 }
2171
2172 Eval->IsEvaluating = true;
2173
2174 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2175 this, Notes);
2176
Manuel Klimeka7328992013-06-03 13:51:33 +00002177 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2178 // or that it's empty (so that there's nothing to clean up) if evaluation
2179 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002180 if (!Result)
2181 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002182 else if (Eval->Evaluated.needsCleanup())
2183 getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002184
2185 Eval->IsEvaluating = false;
2186 Eval->WasEvaluated = true;
2187
2188 // In C++11, we have determined whether the initializer was a constant
2189 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002190 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002191 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002192 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002193 }
2194
Craig Topper36250ad2014-05-12 05:36:57 +00002195 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002196}
2197
Chandler Carruth813faed2015-12-30 02:51:00 +00002198APValue *VarDecl::getEvaluatedValue() const {
2199 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2200 if (Eval->WasEvaluated)
2201 return &Eval->Evaluated;
2202
2203 return nullptr;
2204}
2205
2206bool VarDecl::isInitKnownICE() const {
2207 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2208 return Eval->CheckedICE;
2209
2210 return false;
2211}
2212
2213bool VarDecl::isInitICE() const {
2214 assert(isInitKnownICE() &&
2215 "Check whether we already know that the initializer is an ICE");
2216 return Init.get<EvaluatedStmt *>()->IsICE;
2217}
2218
Richard Smithd0b4dd62011-12-19 06:19:21 +00002219bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002220 // Initializers of weak variables are never ICEs.
2221 if (isWeak())
2222 return false;
2223
Richard Smithd0b4dd62011-12-19 06:19:21 +00002224 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2225 if (Eval->CheckedICE)
2226 // We have already checked whether this subexpression is an
2227 // integral constant expression.
2228 return Eval->IsICE;
2229
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002230 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002231 assert(!Init->isValueDependent());
2232
2233 // In C++11, evaluate the initializer to check whether it's a constant
2234 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002235 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002236 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002237 evaluateValue(Notes);
2238 return Eval->IsICE;
2239 }
2240
2241 // It's an ICE whether or not the definition we found is
2242 // out-of-line. See DR 721 and the discussion in Clang PR
2243 // 6206 for details.
2244
2245 if (Eval->CheckingICE)
2246 return false;
2247 Eval->CheckingICE = true;
2248
2249 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2250 Eval->CheckingICE = false;
2251 Eval->CheckedICE = true;
2252 return Eval->IsICE;
2253}
2254
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002255VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002256 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002257 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002258
2259 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002260}
2261
Douglas Gregor3c74d412009-10-14 20:14:33 +00002262TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002263 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002264 return Spec->getSpecializationKind();
2265
Sebastian Redl35351a92010-01-31 22:27:38 +00002266 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002267 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002268
Douglas Gregor86d142a2009-10-08 07:24:58 +00002269 return TSK_Undeclared;
2270}
2271
Richard Smith8809a0c2013-09-27 20:14:12 +00002272SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002273 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002274 return Spec->getPointOfInstantiation();
2275
2276 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2277 return MSI->getPointOfInstantiation();
2278
2279 return SourceLocation();
2280}
2281
Larisse Voufo39a1e502013-08-06 01:03:05 +00002282VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2283 return getASTContext().getTemplateOrSpecializationInfo(this)
2284 .dyn_cast<VarTemplateDecl *>();
2285}
2286
2287void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2288 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2289}
2290
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002291MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002292 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002293 // FIXME: Remove ?
2294 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2295 return getASTContext().getTemplateOrSpecializationInfo(this)
2296 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002297 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002298}
2299
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002300void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2301 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002302 assert((isa<VarTemplateSpecializationDecl>(this) ||
2303 getMemberSpecializationInfo()) &&
2304 "not a variable or static data member template specialization");
2305
Larisse Voufo39a1e502013-08-06 01:03:05 +00002306 if (VarTemplateSpecializationDecl *Spec =
2307 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2308 Spec->setSpecializationKind(TSK);
2309 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2310 Spec->getPointOfInstantiation().isInvalid())
2311 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002312 }
2313
2314 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2315 MSI->setTemplateSpecializationKind(TSK);
2316 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2317 MSI->getPointOfInstantiation().isInvalid())
2318 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002319 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002320}
2321
2322void
2323VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2324 TemplateSpecializationKind TSK) {
2325 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2326 "Previous template or instantiation?");
2327 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002328}
2329
Sebastian Redl833ef452010-01-26 22:01:41 +00002330//===----------------------------------------------------------------------===//
2331// ParmVarDecl Implementation
2332//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002333
Sebastian Redl833ef452010-01-26 22:01:41 +00002334ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002335 SourceLocation StartLoc,
2336 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002337 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002338 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002339 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002340 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002341}
2342
Reid Kleckner8a365022013-06-24 17:51:48 +00002343QualType ParmVarDecl::getOriginalType() const {
2344 TypeSourceInfo *TSI = getTypeSourceInfo();
2345 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002346 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002347 return DT->getOriginalType();
2348 return T;
2349}
2350
Douglas Gregor72172e92012-01-05 21:55:30 +00002351ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002352 return new (C, ID)
2353 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2354 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002355}
2356
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002357SourceRange ParmVarDecl::getSourceRange() const {
2358 if (!hasInheritedDefaultArg()) {
2359 SourceRange ArgRange = getDefaultArgRange();
2360 if (ArgRange.isValid())
2361 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2362 }
2363
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002364 // DeclaratorDecl considers the range of postfix types as overlapping with the
2365 // declaration name, but this is not the case with parameters in ObjC methods.
2366 if (isa<ObjCMethodDecl>(getDeclContext()))
2367 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2368
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002369 return DeclaratorDecl::getSourceRange();
2370}
2371
Sebastian Redl833ef452010-01-26 22:01:41 +00002372Expr *ParmVarDecl::getDefaultArg() {
2373 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2374 assert(!hasUninstantiatedDefaultArg() &&
2375 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002376
Sebastian Redl833ef452010-01-26 22:01:41 +00002377 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002378 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002379 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002380
Sebastian Redl833ef452010-01-26 22:01:41 +00002381 return Arg;
2382}
2383
Chandler Carruth813faed2015-12-30 02:51:00 +00002384void ParmVarDecl::setDefaultArg(Expr *defarg) {
2385 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2386 Init = defarg;
2387}
Sebastian Redl833ef452010-01-26 22:01:41 +00002388
Chandler Carruth813faed2015-12-30 02:51:00 +00002389SourceRange ParmVarDecl::getDefaultArgRange() const {
2390 switch (ParmVarDeclBits.DefaultArgKind) {
2391 case DAK_None:
2392 case DAK_Unparsed:
2393 // Nothing we can do here.
2394 return SourceRange();
2395
2396 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002397 return getUninstantiatedDefaultArg()->getSourceRange();
2398
Chandler Carruth813faed2015-12-30 02:51:00 +00002399 case DAK_Normal:
2400 if (const Expr *E = getInit())
2401 return E->getSourceRange();
2402
2403 // Missing an actual expression, may be invalid.
2404 return SourceRange();
2405 }
2406 llvm_unreachable("Invalid default argument kind.");
2407}
2408
2409void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2410 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2411 Init = arg;
2412}
2413
2414Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2415 assert(hasUninstantiatedDefaultArg() &&
2416 "Wrong kind of initialization expression!");
2417 return cast_or_null<Expr>(Init.get<Stmt *>());
2418}
2419
2420bool ParmVarDecl::hasDefaultArg() const {
2421 // FIXME: We should just return false for DAK_None here once callers are
2422 // prepared for the case that we encountered an invalid default argument and
2423 // were unable to even build an invalid expression.
2424 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2425 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002426}
2427
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002428bool ParmVarDecl::isParameterPack() const {
2429 return isa<PackExpansionType>(getType());
2430}
2431
Ted Kremenek540017e2011-10-06 05:00:56 +00002432void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2433 getASTContext().setParameterIndex(this, parameterIndex);
2434 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2435}
2436
2437unsigned ParmVarDecl::getParameterIndexLarge() const {
2438 return getASTContext().getParameterIndex(this);
2439}
2440
Nuno Lopes394ec982008-12-17 23:39:55 +00002441//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002442// FunctionDecl Implementation
2443//===----------------------------------------------------------------------===//
2444
Benjamin Kramer9170e912013-02-22 15:46:01 +00002445void FunctionDecl::getNameForDiagnostic(
2446 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2447 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002448 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2449 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002450 TemplateSpecializationType::PrintTemplateArgumentList(
2451 OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002452}
2453
Ted Kremenek186a0742010-04-29 16:49:01 +00002454bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002455 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002456 return FT->isVariadic();
2457 return false;
2458}
2459
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002460bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002461 for (auto I : redecls()) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002462 if (I->Body || I->IsLateTemplateParsed) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002463 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002464 return true;
2465 }
2466 }
2467
2468 return false;
2469}
2470
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002471bool FunctionDecl::hasTrivialBody() const
2472{
2473 Stmt *S = getBody();
2474 if (!S) {
2475 // Since we don't have a body for this function, we don't know if it's
2476 // trivial or not.
2477 return false;
2478 }
2479
2480 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2481 return true;
2482 return false;
2483}
2484
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002485bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002486 for (auto I : redecls()) {
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002487 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2488 I->hasAttr<AliasAttr>()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002489 Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002490 return true;
2491 }
2492 }
2493
2494 return false;
2495}
2496
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002497Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002498 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002499 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002500
2501 if (Definition->Body)
2502 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002503
Craig Topper36250ad2014-05-12 05:36:57 +00002504 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002505}
2506
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002507void FunctionDecl::setBody(Stmt *B) {
2508 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002509 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002510 EndRangeLoc = B->getLocEnd();
2511}
2512
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002513void FunctionDecl::setPure(bool P) {
2514 IsPure = P;
2515 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002516 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002517 Parent->markedVirtualFunctionPure();
2518}
2519
Richard Smith8d0dc312013-07-21 23:12:18 +00002520template<std::size_t Len>
2521static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2522 IdentifierInfo *II = ND->getIdentifier();
2523 return II && II->isStr(Str);
2524}
2525
Douglas Gregor16618f22009-09-12 00:17:51 +00002526bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002527 const TranslationUnitDecl *tunit =
2528 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2529 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002530 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002531 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002532}
2533
David Majnemerc729b0b2013-09-16 22:44:20 +00002534bool FunctionDecl::isMSVCRTEntryPoint() const {
2535 const TranslationUnitDecl *TUnit =
2536 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2537 if (!TUnit)
2538 return false;
2539
2540 // Even though we aren't really targeting MSVCRT if we are freestanding,
2541 // semantic analysis for these functions remains the same.
2542
2543 // MSVCRT entry points only exist on MSVCRT targets.
2544 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2545 return false;
2546
2547 // Nameless functions like constructors cannot be entry points.
2548 if (!getIdentifier())
2549 return false;
2550
2551 return llvm::StringSwitch<bool>(getName())
2552 .Cases("main", // an ANSI console app
2553 "wmain", // a Unicode console App
2554 "WinMain", // an ANSI GUI app
2555 "wWinMain", // a Unicode GUI app
2556 "DllMain", // a DLL
2557 true)
2558 .Default(false);
2559}
2560
John McCall53ffd372011-05-15 17:49:20 +00002561bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2562 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2563 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2564 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2565 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2566 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2567
Richard Smithf6004412014-01-19 23:25:37 +00002568 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2569 return false;
John McCall53ffd372011-05-15 17:49:20 +00002570
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002571 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002572 if (proto->getNumParams() != 2 || proto->isVariadic())
2573 return false;
John McCall53ffd372011-05-15 17:49:20 +00002574
2575 ASTContext &Context =
2576 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2577 ->getASTContext();
2578
2579 // The result type and first argument type are constant across all
2580 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002581 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002582}
2583
Richard Smith8d0dc312013-07-21 23:12:18 +00002584bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2585 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2586 return false;
2587 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2588 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2589 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2590 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2591 return false;
2592
2593 if (isa<CXXRecordDecl>(getDeclContext()))
2594 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002595
2596 // This can only fail for an invalid 'operator new' declaration.
2597 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2598 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002599
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002600 const auto *FPT = getType()->castAs<FunctionProtoType>();
Nick Lewycky6fb99b92014-06-07 00:43:57 +00002601 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002602 return false;
2603
2604 // If this is a single-parameter function, it must be a replaceable global
2605 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002606 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002607 return true;
2608
2609 // Otherwise, we're looking for a second parameter whose type is
Richard Smith1cdec012013-09-29 04:40:38 +00002610 // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
Alp Toker9cacbab2014-01-20 20:26:09 +00002611 QualType Ty = FPT->getParamType(1);
Richard Smith1cdec012013-09-29 04:40:38 +00002612 ASTContext &Ctx = getASTContext();
Richard Smithb47c36f2013-11-05 09:12:18 +00002613 if (Ctx.getLangOpts().SizedDeallocation &&
2614 Ctx.hasSameType(Ty, Ctx.getSizeType()))
Richard Smith1cdec012013-09-29 04:40:38 +00002615 return true;
Richard Smith8d0dc312013-07-21 23:12:18 +00002616 if (!Ty->isReferenceType())
2617 return false;
2618 Ty = Ty->getPointeeType();
2619 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2620 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002621 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Richard Trieuc771d5d2014-05-28 02:16:01 +00002622 return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
Richard Smith8d0dc312013-07-21 23:12:18 +00002623}
2624
Rafael Espindolaf4187652013-02-14 01:18:37 +00002625LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002626 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002627}
2628
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002629bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002630 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002631}
2632
Rafael Espindola593537a2013-05-05 20:15:21 +00002633bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002634 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002635}
2636
2637bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002638 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002639}
2640
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002641bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002642 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002643 return Method->isStatic();
2644
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002645 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002646 return false;
2647
Mike Stump11289f42009-09-09 15:08:12 +00002648 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002649 DC->isNamespace();
2650 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002651 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002652 if (!Namespace->getDeclName())
2653 return false;
2654 break;
2655 }
2656 }
2657
2658 return true;
2659}
2660
Richard Smith10876ef2013-01-17 01:30:42 +00002661bool FunctionDecl::isNoReturn() const {
2662 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
Richard Smithdebc59d2013-01-30 05:45:05 +00002663 hasAttr<C11NoReturnAttr>() ||
Richard Smith10876ef2013-01-17 01:30:42 +00002664 getType()->getAs<FunctionType>()->getNoReturnAttr();
2665}
2666
Sebastian Redl833ef452010-01-26 22:01:41 +00002667void
2668FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002669 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002670
2671 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2672 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002673 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002674 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002675 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002676 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002677
Axel Naumannfbc7b982011-11-08 18:21:06 +00002678 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002679 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002680}
2681
Rafael Espindola8db352d2013-10-17 15:37:26 +00002682FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002683
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002684/// \brief Returns a value indicating whether this function
2685/// corresponds to a builtin function.
2686///
2687/// The function corresponds to a built-in function if it is
2688/// declared at translation scope or within an extern "C" block and
2689/// its name matches with the name of a builtin. The returned value
2690/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002691/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002692/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002693unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002694 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002695 return 0;
2696
2697 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002698 if (!BuiltinID)
2699 return 0;
2700
2701 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002702 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002703 const auto *LinkageDecl =
2704 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002705 // In C++, the first declaration of a builtin is always inside an implicit
2706 // extern "C".
2707 // FIXME: A recognised library function may not be directly in an extern "C"
2708 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002709 if (!LinkageDecl) {
2710 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2711 Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2712 isInStdNamespace())
2713 return Builtin::BI__GetExceptionInfo;
2714 return 0;
2715 }
2716 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002717 return 0;
2718 }
2719
2720 // If the function is marked "overloadable", it has a different mangled name
2721 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002722 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002723 return 0;
2724
Douglas Gregore711f702009-02-14 18:57:46 +00002725 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2726 return BuiltinID;
2727
2728 // This function has the name of a known C library
2729 // function. Determine whether it actually refers to the C library
2730 // function or whether it just has the same name.
2731
Douglas Gregora908e7f2009-02-17 03:23:10 +00002732 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002733 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002734 return 0;
2735
Warren Hunt445d83e2013-11-01 23:46:51 +00002736 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002737}
2738
2739
Chris Lattner47c0d002009-04-25 06:03:53 +00002740/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002741/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002742/// after it has been created.
2743unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002744 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002745 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002746}
2747
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002748void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002749 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002750 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002751 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002752
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002753 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002754 if (!NewParamInfo.empty()) {
2755 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2756 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002757 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002758}
Chris Lattner41943152007-01-25 04:52:46 +00002759
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002760void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
James Molloy6f8780b2012-02-29 10:24:19 +00002761 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2762
2763 if (!NewDecls.empty()) {
2764 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2765 std::copy(NewDecls.begin(), NewDecls.end(), A);
Craig Topper5fc8fc22014-08-27 06:28:36 +00002766 DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
Serge Pavlova8261472014-06-25 17:09:41 +00002767 // Move declarations introduced in prototype to the function context.
2768 for (auto I : NewDecls) {
2769 DeclContext *DC = I->getDeclContext();
2770 // Forward-declared reference to an enumeration is not added to
2771 // declaration scope, so skip declaration that is absent from its
2772 // declaration contexts.
2773 if (DC->containsDecl(I)) {
2774 DC->removeDecl(I);
2775 I->setDeclContext(this);
2776 addDecl(I);
2777 }
2778 }
James Molloy6f8780b2012-02-29 10:24:19 +00002779 }
2780}
2781
Chris Lattner58258242008-04-10 02:22:51 +00002782/// getMinRequiredArguments - Returns the minimum number of arguments
2783/// needed to call this function. This may be fewer than the number of
2784/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002785/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002786unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002787 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002788 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002789
Richard Smith91151782014-04-01 19:18:16 +00002790 unsigned NumRequiredArgs = 0;
2791 for (auto *Param : params())
2792 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2793 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002794 return NumRequiredArgs;
2795}
2796
David Majnemer54e3ba52014-04-02 23:17:29 +00002797/// \brief The combination of the extern and inline keywords under MSVC forces
2798/// the function to be required.
2799///
2800/// Note: This function assumes that we will only get called when isInlined()
2801/// would return true for this FunctionDecl.
2802bool FunctionDecl::isMSExternInline() const {
2803 assert(isInlined() && "expected to get called on an inlined function!");
2804
2805 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002806 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2807 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002808 return false;
2809
David Majnemer73768702015-03-20 00:02:27 +00002810 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2811 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002812 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002813 return true;
2814
2815 return false;
2816}
2817
2818static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2819 if (Redecl->getStorageClass() != SC_Extern)
2820 return false;
2821
2822 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2823 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002824 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002825 return false;
2826
2827 return true;
2828}
2829
Eli Friedman1b125c32012-02-07 03:50:18 +00002830static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2831 // Only consider file-scope declarations in this test.
2832 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2833 return false;
2834
2835 // Only consider explicit declarations; the presence of a builtin for a
2836 // libcall shouldn't affect whether a definition is externally visible.
2837 if (Redecl->isImplicit())
2838 return false;
2839
2840 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2841 return true; // Not an inline definition
2842
2843 return false;
2844}
2845
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002846/// \brief For a function declaration in C or C++, determine whether this
2847/// declaration causes the definition to be externally visible.
2848///
David Majnemer54e3ba52014-04-02 23:17:29 +00002849/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002850/// of redeclarations of the given functions causes
2851/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002852bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2853 assert(!doesThisDeclarationHaveABody() &&
2854 "Must have a declaration without a body.");
2855
2856 ASTContext &Context = getASTContext();
2857
David Majnemer54e3ba52014-04-02 23:17:29 +00002858 if (Context.getLangOpts().MSVCCompat) {
2859 const FunctionDecl *Definition;
2860 if (hasBody(Definition) && Definition->isInlined() &&
2861 redeclForcesDefMSVC(this))
2862 return true;
2863 }
2864
David Blaikiebbafb8a2012-03-11 07:00:24 +00002865 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002866 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2867 // an externally visible definition.
2868 //
2869 // FIXME: What happens if gnu_inline gets added on after the first
2870 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002871 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002872 return false;
2873
2874 const FunctionDecl *Prev = this;
2875 bool FoundBody = false;
2876 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002877 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002878
2879 if (Prev->Body) {
2880 // If it's not the case that both 'inline' and 'extern' are
2881 // specified on the definition, then it is always externally visible.
2882 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002883 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002884 return false;
2885 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002886 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002887 return false;
2888 }
2889 }
2890 return FoundBody;
2891 }
2892
David Blaikiebbafb8a2012-03-11 07:00:24 +00002893 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002894 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002895
2896 // C99 6.7.4p6:
2897 // [...] If all of the file scope declarations for a function in a
2898 // translation unit include the inline function specifier without extern,
2899 // then the definition in that translation unit is an inline definition.
2900 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002901 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002902 const FunctionDecl *Prev = this;
2903 bool FoundBody = false;
2904 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002905 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002906 if (RedeclForcesDefC99(Prev))
2907 return false;
2908 }
2909 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002910}
2911
Alp Tokerd0787eb2014-07-02 01:47:15 +00002912SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2913 const TypeSourceInfo *TSI = getTypeSourceInfo();
2914 if (!TSI)
2915 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00002916 FunctionTypeLoc FTL =
2917 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2918 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00002919 return SourceRange();
2920
Alp Tokerf5b10792014-07-02 12:55:58 +00002921 // Skip self-referential return types.
2922 const SourceManager &SM = getASTContext().getSourceManager();
2923 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2924 SourceLocation Boundary = getNameInfo().getLocStart();
2925 if (RTRange.isInvalid() || Boundary.isInvalid() ||
2926 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2927 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00002928
Alp Tokerf5b10792014-07-02 12:55:58 +00002929 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00002930}
2931
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002932bool FunctionDecl::hasUnusedResultAttr() const {
2933 QualType RetType = getReturnType();
2934 if (RetType->isRecordType()) {
2935 const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002936 const auto *MD = dyn_cast<CXXMethodDecl>(this);
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00002937 if (Ret && Ret->hasAttr<WarnUnusedResultAttr>() &&
2938 !(MD && MD->getCorrespondingMethodInClass(Ret, true)))
2939 return true;
2940 }
2941 return hasAttr<WarnUnusedResultAttr>();
2942}
2943
Richard Smithf3814ad2013-01-25 00:08:28 +00002944/// \brief For an inline function definition in C, or for a gnu_inline function
2945/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002946///
2947/// Inline function definitions are always available for inlining optimizations.
2948/// However, depending on the language dialect, declaration specifiers, and
2949/// attributes, the definition of an inline function may or may not be
2950/// "externally" visible to other translation units in the program.
2951///
2952/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002953/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002954/// inline definition becomes externally visible (C99 6.7.4p6).
2955///
2956/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2957/// definition, we use the GNU semantics for inline, which are nearly the
2958/// opposite of C99 semantics. In particular, "inline" by itself will create
2959/// an externally visible symbol, but "extern inline" will not create an
2960/// externally visible symbol.
2961bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002962 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002963 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002964 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002965
David Blaikiebbafb8a2012-03-11 07:00:24 +00002966 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002967 // Note: If you change the logic here, please change
2968 // doesDeclarationForceExternallyVisibleDefinition as well.
2969 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002970 // If it's not the case that both 'inline' and 'extern' are
2971 // specified on the definition, then this inline definition is
2972 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002973 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00002974 return true;
2975
2976 // If any declaration is 'inline' but not 'extern', then this definition
2977 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00002978 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002979 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002980 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002981 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002982 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002983
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002984 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002985 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002986
Richard Smithf3814ad2013-01-25 00:08:28 +00002987 // The rest of this function is C-only.
2988 assert(!Context.getLangOpts().CPlusPlus &&
2989 "should not use C inline rules in C++");
2990
Douglas Gregor299d76e2009-09-13 07:46:26 +00002991 // C99 6.7.4p6:
2992 // [...] If all of the file scope declarations for a function in a
2993 // translation unit include the inline function specifier without extern,
2994 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00002995 for (auto Redecl : redecls()) {
2996 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00002997 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002998 }
2999
3000 // C99 6.7.4p6:
3001 // An inline definition does not provide an external definition for the
3002 // function, and does not forbid an external definition in another
3003 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003004 return false;
3005}
3006
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003007/// getOverloadedOperator - Which C++ overloaded operator this
3008/// function represents, if any.
3009OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003010 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3011 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003012 else
3013 return OO_None;
3014}
3015
Alexis Huntc88db062010-01-13 09:01:02 +00003016/// getLiteralIdentifier - The literal suffix identifier this function
3017/// represents, if any.
3018const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3019 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3020 return getDeclName().getCXXLiteralIdentifier();
3021 else
Craig Topper36250ad2014-05-12 05:36:57 +00003022 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003023}
3024
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003025FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3026 if (TemplateOrSpecialization.isNull())
3027 return TK_NonTemplate;
3028 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3029 return TK_FunctionTemplate;
3030 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3031 return TK_MemberSpecialization;
3032 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3033 return TK_FunctionTemplateSpecialization;
3034 if (TemplateOrSpecialization.is
3035 <DependentFunctionTemplateSpecializationInfo*>())
3036 return TK_DependentFunctionTemplateSpecialization;
3037
David Blaikie83d382b2011-09-23 05:06:16 +00003038 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003039}
3040
Douglas Gregord801b062009-10-07 23:56:10 +00003041FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003042 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003043 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003044
3045 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003046}
3047
Chandler Carruth21c90602015-12-30 03:24:14 +00003048MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3049 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3050}
3051
Douglas Gregord801b062009-10-07 23:56:10 +00003052void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003053FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3054 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003055 TemplateSpecializationKind TSK) {
3056 assert(TemplateOrSpecialization.isNull() &&
3057 "Member function is already a specialization");
3058 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003059 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003060 TemplateOrSpecialization = Info;
3061}
3062
Chandler Carruth21c90602015-12-30 03:24:14 +00003063FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3064 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3065}
3066
3067void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3068 TemplateOrSpecialization = Template;
3069}
3070
Douglas Gregorafca3b42009-10-27 20:53:28 +00003071bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003072 // If the function is invalid, it can't be implicitly instantiated.
3073 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003074 return false;
3075
3076 switch (getTemplateSpecializationKind()) {
3077 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003078 case TSK_ExplicitInstantiationDefinition:
3079 return false;
3080
3081 case TSK_ImplicitInstantiation:
3082 return true;
3083
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003084 // It is possible to instantiate TSK_ExplicitSpecialization kind
3085 // if the FunctionDecl has a class scope specialization pattern.
3086 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003087 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003088
Douglas Gregorafca3b42009-10-27 20:53:28 +00003089 case TSK_ExplicitInstantiationDeclaration:
3090 // Handled below.
3091 break;
3092 }
3093
3094 // Find the actual template from which we will instantiate.
3095 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003096 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003097 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003098 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003099
3100 // C++0x [temp.explicit]p9:
3101 // Except for inline functions, other explicit instantiation declarations
3102 // have the effect of suppressing the implicit instantiation of the entity
3103 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003104 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003105 return true;
3106
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003107 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003108}
3109
3110bool FunctionDecl::isTemplateInstantiation() const {
3111 switch (getTemplateSpecializationKind()) {
3112 case TSK_Undeclared:
3113 case TSK_ExplicitSpecialization:
3114 return false;
3115 case TSK_ImplicitInstantiation:
3116 case TSK_ExplicitInstantiationDeclaration:
3117 case TSK_ExplicitInstantiationDefinition:
3118 return true;
3119 }
3120 llvm_unreachable("All TSK values handled.");
3121}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003122
3123FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003124 // Handle class scope explicit specialization special case.
3125 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3126 return getClassScopeSpecializationPattern();
Faisal Valib90b2112014-04-03 16:32:21 +00003127
3128 // If this is a generic lambda call operator specialization, its
3129 // instantiation pattern is always its primary template's pattern
3130 // even if its primary template was instantiated from another
3131 // member template (which happens with nested generic lambdas).
3132 // Since a lambda's call operator's body is transformed eagerly,
3133 // we don't have to go hunting for a prototype definition template
3134 // (i.e. instantiated-from-member-template) to use as an instantiation
3135 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003136
Faisal Valib90b2112014-04-03 16:32:21 +00003137 if (isGenericLambdaCallOperatorSpecialization(
3138 dyn_cast<CXXMethodDecl>(this))) {
3139 assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3140 "generated from a primary call operator "
3141 "template");
3142 assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3143 "A generic lambda call operator template must always have a body - "
3144 "even if instantiated from a prototype (i.e. as written) member "
3145 "template");
3146 return getPrimaryTemplate()->getTemplatedDecl();
3147 }
3148
Douglas Gregorafca3b42009-10-27 20:53:28 +00003149 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3150 while (Primary->getInstantiatedFromMemberTemplate()) {
3151 // If we have hit a point where the user provided a specialization of
3152 // this template, we're done looking.
3153 if (Primary->isMemberSpecialization())
3154 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003155 Primary = Primary->getInstantiatedFromMemberTemplate();
3156 }
3157
3158 return Primary->getTemplatedDecl();
3159 }
3160
3161 return getInstantiatedFromMemberFunction();
3162}
3163
Douglas Gregor70d83e22009-06-29 17:30:29 +00003164FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003165 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003166 = TemplateOrSpecialization
3167 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003168 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003169 }
Craig Topper36250ad2014-05-12 05:36:57 +00003170 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003171}
3172
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003173FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3174 return getASTContext().getClassScopeSpecializationPattern(this);
3175}
3176
Chandler Carruth21c90602015-12-30 03:24:14 +00003177FunctionTemplateSpecializationInfo *
3178FunctionDecl::getTemplateSpecializationInfo() const {
3179 return TemplateOrSpecialization
3180 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3181}
3182
Douglas Gregor70d83e22009-06-29 17:30:29 +00003183const TemplateArgumentList *
3184FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003185 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003186 = TemplateOrSpecialization
3187 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003188 return Info->TemplateArguments;
3189 }
Craig Topper36250ad2014-05-12 05:36:57 +00003190 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003191}
3192
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003193const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003194FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3195 if (FunctionTemplateSpecializationInfo *Info
3196 = TemplateOrSpecialization
3197 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3198 return Info->TemplateArgumentsAsWritten;
3199 }
Craig Topper36250ad2014-05-12 05:36:57 +00003200 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003201}
3202
Mike Stump11289f42009-09-09 15:08:12 +00003203void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003204FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3205 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003206 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003207 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003208 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003209 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3210 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003211 assert(TSK != TSK_Undeclared &&
3212 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003213 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003214 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003215 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003216 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3217 TemplateArgs,
3218 TemplateArgsAsWritten,
3219 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003220 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003221 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003222}
3223
John McCallb9c78482010-04-08 09:05:18 +00003224void
3225FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3226 const UnresolvedSetImpl &Templates,
3227 const TemplateArgumentListInfo &TemplateArgs) {
3228 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003229 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003230 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3231 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003232 TemplateOrSpecialization = Info;
3233}
3234
James Y Knight7a22b242015-08-06 20:26:32 +00003235DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003236FunctionDecl::getDependentSpecializationInfo() const {
3237 return TemplateOrSpecialization
3238 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3239}
3240
3241DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003242DependentFunctionTemplateSpecializationInfo::Create(
3243 ASTContext &Context, const UnresolvedSetImpl &Ts,
3244 const TemplateArgumentListInfo &TArgs) {
3245 void *Buffer = Context.Allocate(
3246 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3247 TArgs.size(), Ts.size()));
3248 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3249}
3250
John McCallb9c78482010-04-08 09:05:18 +00003251DependentFunctionTemplateSpecializationInfo::
3252DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3253 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003254 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
John McCallb9c78482010-04-08 09:05:18 +00003255
James Y Knight53c76162015-07-17 18:21:37 +00003256 NumTemplates = Ts.size();
3257 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003258
James Y Knight7a22b242015-08-06 20:26:32 +00003259 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003260 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3261 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3262
James Y Knight7a22b242015-08-06 20:26:32 +00003263 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003264 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3265 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3266}
3267
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003268TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003269 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003270 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003271 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003272 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003273 if (FTSInfo)
3274 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003275
Douglas Gregord801b062009-10-07 23:56:10 +00003276 MemberSpecializationInfo *MSInfo
3277 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3278 if (MSInfo)
3279 return MSInfo->getTemplateSpecializationKind();
3280
3281 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003282}
3283
Mike Stump11289f42009-09-09 15:08:12 +00003284void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003285FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3286 SourceLocation PointOfInstantiation) {
3287 if (FunctionTemplateSpecializationInfo *FTSInfo
3288 = TemplateOrSpecialization.dyn_cast<
3289 FunctionTemplateSpecializationInfo*>()) {
3290 FTSInfo->setTemplateSpecializationKind(TSK);
3291 if (TSK != TSK_ExplicitSpecialization &&
3292 PointOfInstantiation.isValid() &&
3293 FTSInfo->getPointOfInstantiation().isInvalid())
3294 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3295 } else if (MemberSpecializationInfo *MSInfo
3296 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3297 MSInfo->setTemplateSpecializationKind(TSK);
3298 if (TSK != TSK_ExplicitSpecialization &&
3299 PointOfInstantiation.isValid() &&
3300 MSInfo->getPointOfInstantiation().isInvalid())
3301 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3302 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003303 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003304}
3305
3306SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003307 if (FunctionTemplateSpecializationInfo *FTSInfo
3308 = TemplateOrSpecialization.dyn_cast<
3309 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003310 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003311 else if (MemberSpecializationInfo *MSInfo
3312 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003313 return MSInfo->getPointOfInstantiation();
3314
3315 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003316}
3317
Douglas Gregor6411b922009-09-11 20:15:17 +00003318bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003319 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003320 return true;
3321
3322 // If this function was instantiated from a member function of a
3323 // class template, check whether that member function was defined out-of-line.
3324 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3325 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003326 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003327 return Definition->isOutOfLine();
3328 }
3329
3330 // If this function was instantiated from a function template,
3331 // check whether that function template was defined out-of-line.
3332 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3333 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003334 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003335 return Definition->isOutOfLine();
3336 }
3337
3338 return false;
3339}
3340
Abramo Bagnaraea947882011-03-08 16:41:52 +00003341SourceRange FunctionDecl::getSourceRange() const {
3342 return SourceRange(getOuterLocStart(), EndRangeLoc);
3343}
3344
Anna Zaks28db7ce2012-01-18 02:45:01 +00003345unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003346 IdentifierInfo *FnInfo = getIdentifier();
3347
3348 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003349 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003350
3351 // Builtin handling.
3352 switch (getBuiltinID()) {
3353 case Builtin::BI__builtin_memset:
3354 case Builtin::BI__builtin___memset_chk:
3355 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003356 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003357
3358 case Builtin::BI__builtin_memcpy:
3359 case Builtin::BI__builtin___memcpy_chk:
3360 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003361 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003362
3363 case Builtin::BI__builtin_memmove:
3364 case Builtin::BI__builtin___memmove_chk:
3365 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003366 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003367
3368 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003369 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003370 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003371
Anna Zaks201d4892012-01-13 21:52:01 +00003372 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003373 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003374 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003375
3376 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003377 case Builtin::BImemcmp:
3378 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003379
3380 case Builtin::BI__builtin_strncpy:
3381 case Builtin::BI__builtin___strncpy_chk:
3382 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003383 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003384
3385 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003386 case Builtin::BIstrncmp:
3387 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003388
3389 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003390 case Builtin::BIstrncasecmp:
3391 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003392
3393 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003394 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003395 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003396 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003397
3398 case Builtin::BI__builtin_strndup:
3399 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003400 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003401
Anna Zaks314cd092012-02-01 19:08:57 +00003402 case Builtin::BI__builtin_strlen:
3403 case Builtin::BIstrlen:
3404 return Builtin::BIstrlen;
3405
Anna Zaks201d4892012-01-13 21:52:01 +00003406 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003407 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003408 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003409 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003410 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003411 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003412 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003413 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003414 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003415 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003416 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003417 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003418 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003419 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003420 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003421 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003422 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003423 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003424 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003425 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003426 else if (FnInfo->isStr("strlen"))
3427 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00003428 }
3429 break;
3430 }
Anna Zaks22122702012-01-17 00:37:07 +00003431 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003432}
3433
Chris Lattner59a25942008-03-31 00:36:02 +00003434//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003435// FieldDecl Implementation
3436//===----------------------------------------------------------------------===//
3437
Jay Foad39c79802011-01-12 09:06:06 +00003438FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003439 SourceLocation StartLoc, SourceLocation IdLoc,
3440 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003441 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003442 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003443 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3444 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003445}
3446
Douglas Gregor72172e92012-01-05 21:55:30 +00003447FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003448 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3449 SourceLocation(), nullptr, QualType(), nullptr,
3450 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003451}
3452
Sebastian Redl833ef452010-01-26 22:01:41 +00003453bool FieldDecl::isAnonymousStructOrUnion() const {
3454 if (!isImplicit() || getDeclName())
3455 return false;
3456
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003457 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003458 return Record->getDecl()->isAnonymousStructOrUnion();
3459
3460 return false;
3461}
3462
Richard Smithcaf33902011-10-10 18:28:20 +00003463unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3464 assert(isBitField() && "not a bitfield");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003465 auto *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
Richard Smithcaf33902011-10-10 18:28:20 +00003466 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3467}
3468
John McCall4e819612011-01-20 07:57:12 +00003469unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003470 const FieldDecl *Canonical = getCanonicalDecl();
3471 if (Canonical != this)
3472 return Canonical->getFieldIndex();
3473
John McCall4e819612011-01-20 07:57:12 +00003474 if (CachedFieldIndex) return CachedFieldIndex - 1;
3475
Richard Smithd62306a2011-11-10 06:34:14 +00003476 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003477 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003478
Hans Wennborga302cd92014-08-21 16:06:57 +00003479 for (auto *Field : RD->fields()) {
3480 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3481 ++Index;
3482 }
John McCall4e819612011-01-20 07:57:12 +00003483
Richard Smithd62306a2011-11-10 06:34:14 +00003484 assert(CachedFieldIndex && "failed to find field in parent");
3485 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003486}
3487
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003488SourceRange FieldDecl::getSourceRange() const {
John McCallc90c1492014-10-10 18:44:34 +00003489 switch (InitStorage.getInt()) {
3490 // All three of these cases store an optional Expr*.
3491 case ISK_BitWidthOrNothing:
3492 case ISK_InClassCopyInit:
3493 case ISK_InClassListInit:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003494 if (const auto *E = static_cast<const Expr *>(InitStorage.getPointer()))
John McCallc90c1492014-10-10 18:44:34 +00003495 return SourceRange(getInnerLocStart(), E->getLocEnd());
3496 // FALLTHROUGH
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003497
John McCallc90c1492014-10-10 18:44:34 +00003498 case ISK_CapturedVLAType:
3499 return DeclaratorDecl::getSourceRange();
3500 }
3501 llvm_unreachable("bad init storage kind");
Alexey Bataev39c81e22014-08-28 04:28:19 +00003502}
3503
3504void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003505 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003506 "capturing type in non-lambda or captured record.");
John McCallc90c1492014-10-10 18:44:34 +00003507 assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3508 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003509 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003510 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3511 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003512}
3513
Sebastian Redl833ef452010-01-26 22:01:41 +00003514//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003515// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003516//===----------------------------------------------------------------------===//
3517
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003518SourceLocation TagDecl::getOuterLocStart() const {
3519 return getTemplateOrInnerLocStart(this);
3520}
3521
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003522SourceRange TagDecl::getSourceRange() const {
3523 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003524 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003525}
3526
Rafael Espindola8db352d2013-10-17 15:37:26 +00003527TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003528
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003529void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003530 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003531 if (const Type *T = getTypeForDecl()) {
3532 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003533 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003534 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003535 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003536}
3537
Douglas Gregordee1be82009-01-17 00:42:38 +00003538void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003539 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003540
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003541 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003542 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003543 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003544 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003545 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003546 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003547}
3548
3549void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003550 assert((!isa<CXXRecordDecl>(this) ||
3551 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3552 "definition completed but not started");
3553
John McCallf937c022011-10-07 06:10:15 +00003554 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003555 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003556
3557 if (ASTMutationListener *L = getASTMutationListener())
3558 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003559}
3560
John McCallf937c022011-10-07 06:10:15 +00003561TagDecl *TagDecl::getDefinition() const {
3562 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003563 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003564
3565 // If it's possible for us to have an out-of-date definition, check now.
3566 if (MayHaveOutOfDateDef) {
3567 if (IdentifierInfo *II = getIdentifier()) {
3568 if (II->isOutOfDate()) {
3569 updateOutOfDate(*II);
3570 }
3571 }
3572 }
3573
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003574 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003575 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003576
Aaron Ballman86c93902014-03-06 23:45:36 +00003577 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003578 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003579 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003580
Craig Topper36250ad2014-05-12 05:36:57 +00003581 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003582}
3583
Douglas Gregor14454802011-02-25 02:25:35 +00003584void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3585 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003586 // Make sure the extended qualifier info is allocated.
3587 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003588 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003589 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003590 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003591 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003592 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003593 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003594 if (getExtInfo()->NumTemplParamLists == 0) {
3595 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003596 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003597 }
3598 else
3599 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003600 }
3601 }
3602}
3603
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003604void TagDecl::setTemplateParameterListsInfo(
3605 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3606 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003607 // Make sure the extended decl info is allocated.
3608 if (!hasExtInfo())
3609 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003610 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003611 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003612 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003613}
3614
Ted Kremenek21475702008-09-05 17:16:31 +00003615//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003616// EnumDecl Implementation
3617//===----------------------------------------------------------------------===//
3618
David Blaikie68e081d2011-12-20 02:48:34 +00003619void EnumDecl::anchor() { }
3620
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003621EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3622 SourceLocation StartLoc, SourceLocation IdLoc,
3623 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003624 EnumDecl *PrevDecl, bool IsScoped,
3625 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003626 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3627 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003628 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003629 C.getTypeDeclType(Enum, PrevDecl);
3630 return Enum;
3631}
3632
Douglas Gregor72172e92012-01-05 21:55:30 +00003633EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003634 EnumDecl *Enum =
3635 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3636 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003637 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3638 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003639}
3640
Alp Tokerb9fa5122014-01-06 11:31:18 +00003641SourceRange EnumDecl::getIntegerTypeRange() const {
3642 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3643 return TI->getTypeLoc().getSourceRange();
3644 return SourceRange();
3645}
3646
Douglas Gregord5058122010-02-11 01:19:42 +00003647void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003648 QualType NewPromotionType,
3649 unsigned NumPositiveBits,
3650 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003651 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003652 if (!IntegerType)
3653 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003654 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003655 setNumPositiveBits(NumPositiveBits);
3656 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003657 TagDecl::completeDefinition();
3658}
3659
Richard Smith7d137e32012-03-23 03:33:32 +00003660TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3661 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3662 return MSI->getTemplateSpecializationKind();
3663
3664 return TSK_Undeclared;
3665}
3666
3667void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3668 SourceLocation PointOfInstantiation) {
3669 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3670 assert(MSI && "Not an instantiated member enumeration?");
3671 MSI->setTemplateSpecializationKind(TSK);
3672 if (TSK != TSK_ExplicitSpecialization &&
3673 PointOfInstantiation.isValid() &&
3674 MSI->getPointOfInstantiation().isInvalid())
3675 MSI->setPointOfInstantiation(PointOfInstantiation);
3676}
3677
Richard Smith4b38ded2012-03-14 23:13:10 +00003678EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3679 if (SpecializationInfo)
3680 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3681
Craig Topper36250ad2014-05-12 05:36:57 +00003682 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003683}
3684
3685void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3686 TemplateSpecializationKind TSK) {
3687 assert(!SpecializationInfo && "Member enum is already a specialization");
3688 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3689}
3690
Sebastian Redl833ef452010-01-26 22:01:41 +00003691//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003692// RecordDecl Implementation
3693//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003694
Richard Smith053f6c62014-05-16 23:01:30 +00003695RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3696 DeclContext *DC, SourceLocation StartLoc,
3697 SourceLocation IdLoc, IdentifierInfo *Id,
3698 RecordDecl *PrevDecl)
3699 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003700 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003701 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003702 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003703 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003704 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003705 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003706}
3707
Jay Foad39c79802011-01-12 09:06:06 +00003708RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003709 SourceLocation StartLoc, SourceLocation IdLoc,
3710 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003711 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3712 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003713 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3714
Ted Kremenek21475702008-09-05 17:16:31 +00003715 C.getTypeDeclType(R, PrevDecl);
3716 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003717}
3718
Douglas Gregor72172e92012-01-05 21:55:30 +00003719RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003720 RecordDecl *R =
3721 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3722 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003723 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3724 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003725}
3726
Douglas Gregordfcad112009-03-25 15:59:44 +00003727bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003728 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003729 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3730}
3731
Alexey Bataev39c81e22014-08-28 04:28:19 +00003732bool RecordDecl::isLambda() const {
3733 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3734 return RD->isLambda();
3735 return false;
3736}
3737
Alexey Bataev330de032014-10-29 12:21:55 +00003738bool RecordDecl::isCapturedRecord() const {
3739 return hasAttr<CapturedRecordAttr>();
3740}
3741
3742void RecordDecl::setCapturedRecord() {
3743 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3744}
3745
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003746RecordDecl::field_iterator RecordDecl::field_begin() const {
3747 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3748 LoadFieldsFromExternalStorage();
3749
3750 return field_iterator(decl_iterator(FirstDecl));
3751}
3752
Douglas Gregorb11aad82011-02-19 18:51:44 +00003753/// completeDefinition - Notes that the definition of this type is now
3754/// complete.
3755void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003756 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003757 TagDecl::completeDefinition();
3758}
3759
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003760/// isMsStruct - Get whether or not this record uses ms_struct layout.
3761/// This which can be turned on with an attribute, pragma, or the
3762/// -mms-bitfields command-line option.
3763bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003764 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003765}
3766
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003767void RecordDecl::LoadFieldsFromExternalStorage() const {
3768 ExternalASTSource *Source = getASTContext().getExternalSource();
3769 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3770
3771 // Notify that we have a RecordDecl doing some initialization.
3772 ExternalASTSource::Deserializing TheFields(Source);
3773
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003774 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00003775 LoadedFieldsFromExternalStorage = true;
3776 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3777 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3778 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003779
3780#ifndef NDEBUG
3781 // Check that all decls we got were FieldDecls.
3782 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003783 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003784#endif
3785
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003786 if (Decls.empty())
3787 return;
3788
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003789 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003790 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003791}
3792
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003793bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3794 ASTContext &Context = getASTContext();
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003795 if (!Context.getLangOpts().Sanitize.hasOneOf(
3796 SanitizerKind::Address | SanitizerKind::KernelAddress) ||
Alexey Samsonova0416102014-11-11 01:26:14 +00003797 !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003798 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003799 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003800 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003801 // We may be able to relax some of these requirements.
3802 int ReasonToReject = -1;
3803 if (!CXXRD || CXXRD->isExternCContext())
3804 ReasonToReject = 0; // is not C++.
3805 else if (CXXRD->hasAttr<PackedAttr>())
3806 ReasonToReject = 1; // is packed.
3807 else if (CXXRD->isUnion())
3808 ReasonToReject = 2; // is a union.
3809 else if (CXXRD->isTriviallyCopyable())
3810 ReasonToReject = 3; // is trivially copyable.
3811 else if (CXXRD->hasTrivialDestructor())
3812 ReasonToReject = 4; // has trivial destructor.
3813 else if (CXXRD->isStandardLayout())
3814 ReasonToReject = 5; // is standard layout.
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003815 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003816 ReasonToReject = 6; // is in a blacklisted file.
3817 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3818 "field-padding"))
3819 ReasonToReject = 7; // is blacklisted.
3820
3821 if (EmitRemark) {
3822 if (ReasonToReject >= 0)
3823 Context.getDiagnostics().Report(
3824 getLocation(),
3825 diag::remark_sanitize_address_insert_extra_padding_rejected)
3826 << getQualifiedNameAsString() << ReasonToReject;
3827 else
3828 Context.getDiagnostics().Report(
3829 getLocation(),
3830 diag::remark_sanitize_address_insert_extra_padding_accepted)
3831 << getQualifiedNameAsString();
3832 }
3833 return ReasonToReject < 0;
3834}
3835
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003836const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3837 for (const auto *I : fields()) {
3838 if (I->getIdentifier())
3839 return I;
3840
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003841 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003842 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003843 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003844 return NamedDataMember;
3845 }
3846
3847 // We didn't find a named data member.
3848 return nullptr;
3849}
3850
3851
Steve Naroff415d3d52008-10-08 17:01:13 +00003852//===----------------------------------------------------------------------===//
3853// BlockDecl Implementation
3854//===----------------------------------------------------------------------===//
3855
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003856void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003857 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003858
Steve Naroffc4b30e52009-03-13 16:56:44 +00003859 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003860 if (!NewParamInfo.empty()) {
3861 NumParams = NewParamInfo.size();
3862 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3863 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003864 }
3865}
3866
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003867void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3868 bool CapturesCXXThis) {
3869 this->CapturesCXXThis = CapturesCXXThis;
3870 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00003871
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003872 if (Captures.empty()) {
3873 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00003874 return;
3875 }
3876
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003877 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00003878}
Sebastian Redl833ef452010-01-26 22:01:41 +00003879
John McCallce45f882011-06-15 22:51:16 +00003880bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00003881 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00003882 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00003883 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00003884 return true;
3885
3886 return false;
3887}
3888
Douglas Gregor70226da2010-12-21 16:27:07 +00003889SourceRange BlockDecl::getSourceRange() const {
3890 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3891}
Sebastian Redl833ef452010-01-26 22:01:41 +00003892
3893//===----------------------------------------------------------------------===//
3894// Other Decl Allocation/Deallocation Method Implementations
3895//===----------------------------------------------------------------------===//
3896
David Blaikie68e081d2011-12-20 02:48:34 +00003897void TranslationUnitDecl::anchor() { }
3898
Sebastian Redl833ef452010-01-26 22:01:41 +00003899TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00003900 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00003901}
3902
Richard Smithf19e1272015-03-07 00:04:49 +00003903void ExternCContextDecl::anchor() { }
3904
3905ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
3906 TranslationUnitDecl *DC) {
3907 return new (C, DC) ExternCContextDecl(DC);
3908}
3909
David Blaikie68e081d2011-12-20 02:48:34 +00003910void LabelDecl::anchor() { }
3911
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003912LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003913 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00003914 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00003915}
3916
3917LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3918 SourceLocation IdentL, IdentifierInfo *II,
3919 SourceLocation GnuLabelL) {
3920 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00003921 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00003922}
3923
Douglas Gregor72172e92012-01-05 21:55:30 +00003924LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003925 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3926 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00003927}
3928
Ehsan Akhgari31097582014-09-22 02:21:54 +00003929void LabelDecl::setMSAsmLabel(StringRef Name) {
3930 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
3931 memcpy(Buffer, Name.data(), Name.size());
3932 Buffer[Name.size()] = '\0';
3933 MSAsmName = Buffer;
3934}
3935
David Blaikie68e081d2011-12-20 02:48:34 +00003936void ValueDecl::anchor() { }
3937
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003938bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00003939 for (const auto *I : attrs())
3940 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00003941 return true;
3942
3943 return isWeakImported();
3944}
3945
David Blaikie68e081d2011-12-20 02:48:34 +00003946void ImplicitParamDecl::anchor() { }
3947
Sebastian Redl833ef452010-01-26 22:01:41 +00003948ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003949 SourceLocation IdLoc,
3950 IdentifierInfo *Id,
3951 QualType Type) {
Richard Smith053f6c62014-05-16 23:01:30 +00003952 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00003953}
3954
Richard Smithf7981722013-11-22 09:01:48 +00003955ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00003956 unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003957 return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00003958 QualType());
Douglas Gregor72172e92012-01-05 21:55:30 +00003959}
3960
Sebastian Redl833ef452010-01-26 22:01:41 +00003961FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003962 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00003963 const DeclarationNameInfo &NameInfo,
3964 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003965 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00003966 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00003967 bool hasWrittenPrototype,
3968 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00003969 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00003970 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
3971 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00003972 New->HasWrittenPrototype = hasWrittenPrototype;
3973 return New;
3974}
3975
Douglas Gregor72172e92012-01-05 21:55:30 +00003976FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003977 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00003978 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00003979 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00003980}
3981
Sebastian Redl833ef452010-01-26 22:01:41 +00003982BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00003983 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00003984}
3985
Douglas Gregor72172e92012-01-05 21:55:30 +00003986BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003987 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00003988}
3989
Chandler Carruth21c90602015-12-30 03:24:14 +00003990CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
3991 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
3992 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
3993
Ben Langmuir37943a72013-05-03 19:00:33 +00003994CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3995 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00003996 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00003997 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00003998}
3999
Ben Langmuirce914fc2013-05-03 19:20:19 +00004000CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004001 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004002 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004003 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004004}
4005
Chandler Carruth21c90602015-12-30 03:24:14 +00004006Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4007void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4008
4009bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4010void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4011
Sebastian Redl833ef452010-01-26 22:01:41 +00004012EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4013 SourceLocation L,
4014 IdentifierInfo *Id, QualType T,
4015 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004016 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004017}
4018
Douglas Gregor72172e92012-01-05 21:55:30 +00004019EnumConstantDecl *
4020EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004021 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4022 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004023}
4024
David Blaikie68e081d2011-12-20 02:48:34 +00004025void IndirectFieldDecl::anchor() { }
4026
Richard Smith9f951822016-01-06 22:49:11 +00004027IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4028 SourceLocation L, DeclarationName N,
4029 QualType T, NamedDecl **CH, unsigned CHS)
4030 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {
4031 // In C++, indirect field declarations conflict with tag declarations in the
4032 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4033 if (C.getLangOpts().CPlusPlus)
4034 IdentifierNamespace |= IDNS_Tag;
4035}
4036
Benjamin Kramer39593702010-11-21 14:11:41 +00004037IndirectFieldDecl *
4038IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4039 IdentifierInfo *Id, QualType T, NamedDecl **CH,
4040 unsigned CHS) {
Richard Smith9f951822016-01-06 22:49:11 +00004041 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH, CHS);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004042}
4043
Douglas Gregor72172e92012-01-05 21:55:30 +00004044IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4045 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004046 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004047 DeclarationName(), QualType(), nullptr,
4048 0);
Douglas Gregor72172e92012-01-05 21:55:30 +00004049}
4050
Douglas Gregorbe996932010-09-01 20:41:53 +00004051SourceRange EnumConstantDecl::getSourceRange() const {
4052 SourceLocation End = getLocation();
4053 if (Init)
4054 End = Init->getLocEnd();
4055 return SourceRange(getLocation(), End);
4056}
4057
David Blaikie68e081d2011-12-20 02:48:34 +00004058void TypeDecl::anchor() { }
4059
Sebastian Redl833ef452010-01-26 22:01:41 +00004060TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004061 SourceLocation StartLoc, SourceLocation IdLoc,
4062 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004063 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004064}
4065
David Blaikie68e081d2011-12-20 02:48:34 +00004066void TypedefNameDecl::anchor() { }
4067
Richard Smith42413142015-05-15 20:05:43 +00004068TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4069 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4070 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4071 auto *ThisTypedef = this;
4072 if (AnyRedecl && OwningTypedef) {
4073 OwningTypedef = OwningTypedef->getCanonicalDecl();
4074 ThisTypedef = ThisTypedef->getCanonicalDecl();
4075 }
4076 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004077 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004078 }
Richard Smitha5230222015-03-27 01:37:43 +00004079
4080 return nullptr;
4081}
4082
Douglas Gregor72172e92012-01-05 21:55:30 +00004083TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004084 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004085 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004086}
4087
Richard Smithdda56e42011-04-15 14:24:37 +00004088TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4089 SourceLocation StartLoc,
4090 SourceLocation IdLoc, IdentifierInfo *Id,
4091 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004092 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004093}
4094
Douglas Gregor72172e92012-01-05 21:55:30 +00004095TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004096 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4097 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004098}
4099
Abramo Bagnaraea947882011-03-08 16:41:52 +00004100SourceRange TypedefDecl::getSourceRange() const {
4101 SourceLocation RangeEnd = getLocation();
4102 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4103 if (typeIsPostfix(TInfo->getType()))
4104 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4105 }
4106 return SourceRange(getLocStart(), RangeEnd);
4107}
4108
Richard Smithdda56e42011-04-15 14:24:37 +00004109SourceRange TypeAliasDecl::getSourceRange() const {
4110 SourceLocation RangeEnd = getLocStart();
4111 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4112 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4113 return SourceRange(getLocStart(), RangeEnd);
4114}
4115
David Blaikie68e081d2011-12-20 02:48:34 +00004116void FileScopeAsmDecl::anchor() { }
4117
Sebastian Redl833ef452010-01-26 22:01:41 +00004118FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004119 StringLiteral *Str,
4120 SourceLocation AsmLoc,
4121 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004122 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004123}
Douglas Gregorba345522011-12-02 23:23:56 +00004124
Richard Smithf7981722013-11-22 09:01:48 +00004125FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004126 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004127 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4128 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004129}
4130
Michael Han84324352013-02-22 17:15:32 +00004131void EmptyDecl::anchor() {}
4132
4133EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004134 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004135}
4136
4137EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004138 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004139}
4140
Douglas Gregorba345522011-12-02 23:23:56 +00004141//===----------------------------------------------------------------------===//
4142// ImportDecl Implementation
4143//===----------------------------------------------------------------------===//
4144
4145/// \brief Retrieve the number of module identifiers needed to name the given
4146/// module.
4147static unsigned getNumModuleIdentifiers(Module *Mod) {
4148 unsigned Result = 1;
4149 while (Mod->Parent) {
4150 Mod = Mod->Parent;
4151 ++Result;
4152 }
4153 return Result;
4154}
4155
Douglas Gregor22d09742012-01-03 18:04:46 +00004156ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004157 Module *Imported,
4158 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004159 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004160 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004161{
4162 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004163 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004164 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4165 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004166}
4167
Douglas Gregor22d09742012-01-03 18:04:46 +00004168ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004169 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004170 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004171 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004172{
James Y Knight7a22b242015-08-06 20:26:32 +00004173 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004174}
4175
Richard Smithf7981722013-11-22 09:01:48 +00004176ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004177 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004178 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004179 return new (C, DC,
4180 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004181 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004182}
4183
Richard Smithf7981722013-11-22 09:01:48 +00004184ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004185 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004186 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004187 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004188 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4189 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004190 Import->setImplicit();
4191 return Import;
4192}
4193
Douglas Gregor72172e92012-01-05 21:55:30 +00004194ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4195 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004196 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004197 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004198}
4199
4200ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4201 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004202 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004203
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004204 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004205 return llvm::makeArrayRef(StoredLocs,
4206 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004207}
4208
4209SourceRange ImportDecl::getSourceRange() const {
4210 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004211 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4212
Douglas Gregorba345522011-12-02 23:23:56 +00004213 return SourceRange(getLocation(), getIdentifierLocs().back());
4214}