blob: a6036d1cbf83e9b98dc44710a2ca5cd8ad307059 [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"
George Burgess IV99db3ea2017-08-09 04:02:49 +000015#include "Linkage.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000016#include "clang/AST/ASTContext.h"
Faisal Valib90b2112014-04-03 16:32:21 +000017#include "clang/AST/ASTLambda.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000022#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/AST/DeclTemplate.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000024#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000026#include "clang/AST/PrettyPrinter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "clang/AST/Stmt.h"
28#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000029#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000030#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000031#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000032#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000033#include "clang/Basic/TargetInfo.h"
Kostya Serebryany293dc9b2014-10-16 20:54:52 +000034#include "clang/Frontend/FrontendDiagnostic.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000035#include "llvm/Support/ErrorHandling.h"
David Blaikie9c70e042011-09-21 18:16:56 +000036#include <algorithm>
37
Chris Lattner6d9a6852006-10-25 05:11:20 +000038using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000039
Richard Smith0b87e072013-10-07 08:02:11 +000040Decl *clang::getPrimaryMergedDecl(Decl *D) {
41 return D->getASTContext().getPrimaryMergedDecl(D);
42}
43
Richard Smith73b21d82014-09-03 02:33:22 +000044// Defined here so that it can be inlined into its direct callers.
45bool Decl::isOutOfLine() const {
46 return !getLexicalDeclContext()->Equals(getDeclContext());
47}
48
Richard Smith42413142015-05-15 20:05:43 +000049TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
50 : Decl(TranslationUnit, nullptr, SourceLocation()),
Richard Smith26342f92017-05-17 00:24:14 +000051 DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {}
Richard Smith42413142015-05-15 20:05:43 +000052
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 McCalld041a9b2013-02-20 01:54:26 +0000103/// Does this computation kind permit us to consider additional
104/// visibility settings from attributes and the like?
105static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000106 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000107}
108
109/// Given an LVComputationKind, return one of the same type/value sort
110/// that records that it already has explicit visibility.
111static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000112withExplicitVisibilityAlready(LVComputationKind Kind) {
113 Kind.IgnoreExplicitVisibility = true;
114 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000115}
116
David Blaikie05785d12013-02-20 22:23:23 +0000117static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
118 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000119 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000120 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000121 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000122}
123
John McCalldf25c432013-02-16 00:17:33 +0000124/// Is the given declaration a "type" or a "value" for the purposes of
125/// visibility computation?
126static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000127 return isa<TypeDecl>(D) ||
128 isa<ClassTemplateDecl>(D) ||
129 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000130}
131
John McCall5f46c482013-02-21 23:42:58 +0000132/// Does the given declaration have member specialization information,
133/// and if so, is it an explicit specialization?
134template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000135std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000136isExplicitMemberSpecialization(const T *D) {
137 if (const MemberSpecializationInfo *member =
138 D->getMemberSpecializationInfo()) {
139 return member->isExplicitSpecialization();
140 }
141 return false;
142}
143
144/// For templates, this question is easier: a member template can't be
145/// explicitly instantiated, so there's a single bit indicating whether
146/// or not this is an explicit member specialization.
147static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
148 return D->isMemberSpecialization();
149}
150
John McCalld041a9b2013-02-20 01:54:26 +0000151/// Given a visibility attribute, return the explicit visibility
152/// associated with it.
153template <class T>
154static Visibility getVisibilityFromAttr(const T *attr) {
155 switch (attr->getVisibility()) {
156 case T::Default:
157 return DefaultVisibility;
158 case T::Hidden:
159 return HiddenVisibility;
160 case T::Protected:
161 return ProtectedVisibility;
162 }
163 llvm_unreachable("bad visibility kind");
164}
165
John McCalldf25c432013-02-16 00:17:33 +0000166/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000167static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000168 NamedDecl::ExplicitVisibilityKind kind) {
169 // If we're ultimately computing the visibility of a type, look for
170 // a 'type_visibility' attribute before looking for 'visibility'.
171 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000172 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000173 return getVisibilityFromAttr(A);
174 }
175 }
176
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000177 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000178 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000179 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000180 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000181
David Blaikie7a30dc52013-02-21 01:47:18 +0000182 return None;
John McCall457a04e2010-10-22 21:05:15 +0000183}
184
George Burgess IV99db3ea2017-08-09 04:02:49 +0000185LinkageInfo LinkageComputer::getLVForType(const Type &T,
186 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000187 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000188 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000189 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000190}
191
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000192/// \brief Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000193/// template parameter list. For visibility purposes, template
194/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000195LinkageInfo LinkageComputer::getLVForTemplateParameterList(
196 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000197 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000198 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000199 // Template type parameters are the most common and never
200 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000201 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000202 continue;
203
204 // Non-type template parameters can be restricted by the value type, e.g.
205 // template <enum X> class A { ... };
206 // We have to be careful here, though, because we can be dealing with
207 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000208 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000209 // Handle the non-pack case first.
210 if (!NTTP->isExpandedParameterPack()) {
211 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000212 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000213 }
214 continue;
215 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000216
John McCalldf25c432013-02-16 00:17:33 +0000217 // Look at all the types in an expanded pack.
218 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
219 QualType type = NTTP->getExpansionType(i);
220 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000221 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000222 }
John McCalldf25c432013-02-16 00:17:33 +0000223 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000224 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000225
John McCalldf25c432013-02-16 00:17:33 +0000226 // Template template parameters can be restricted by their
227 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000228 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000229
230 // Handle the non-pack case first.
231 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000232 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
233 computation));
John McCalldf25c432013-02-16 00:17:33 +0000234 continue;
235 }
236
237 // Look at all expansions in an expanded pack.
238 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
239 i != n; ++i) {
240 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000241 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000242 }
243 }
244
John McCall457a04e2010-10-22 21:05:15 +0000245 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000246}
247
Eli Friedman7e346a82013-07-01 20:22:57 +0000248static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000249 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000250 const DeclContext *DC = D->getDeclContext();
251 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000252 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
253 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000254 DC = DC->getParent();
255 }
256 return Ret;
257}
258
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000259/// \brief Get the most restrictive linkage for the types and
260/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000261///
262/// Note that we don't take an LVComputationKind because we always
263/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000264LinkageInfo
265LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
266 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000267 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000268
David Majnemerc7b85c42014-04-23 05:16:48 +0000269 for (const TemplateArgument &Arg : Args) {
270 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000271 case TemplateArgument::Null:
272 case TemplateArgument::Integral:
273 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000274 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000275
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000276 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000277 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000278 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279
280 case TemplateArgument::Declaration:
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000281 if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
John McCalldf25c432013-02-16 00:17:33 +0000282 assert(!usesTypeVisibility(ND));
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000283 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000284 }
285 continue;
Eli Friedmanb826a002012-09-26 02:36:12 +0000286
287 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000288 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000289 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000290
291 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000292 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000293 if (TemplateDecl *Template =
294 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000295 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000296 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000297
298 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000299 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000300 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000301 }
John McCalldf25c432013-02-16 00:17:33 +0000302 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000303 }
304
John McCall457a04e2010-10-22 21:05:15 +0000305 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000306}
307
George Burgess IV99db3ea2017-08-09 04:02:49 +0000308LinkageInfo
309LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
310 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000311 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000312}
313
John McCall5f46c482013-02-21 23:42:58 +0000314static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
315 const FunctionTemplateSpecializationInfo *specInfo) {
316 // Include visibility from the template parameters and arguments
317 // only if this is not an explicit instantiation or specialization
318 // with direct explicit visibility. (Implicit instantiations won't
319 // have a direct attribute.)
320 if (!specInfo->isExplicitInstantiationOrSpecialization())
321 return true;
322
323 return !fn->hasAttr<VisibilityAttr>();
324}
325
John McCalldf25c432013-02-16 00:17:33 +0000326/// Merge in template-related linkage and visibility for the given
327/// function template specialization.
328///
329/// We don't need a computation kind here because we can assume
330/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000331///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000332/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000333void LinkageComputer::mergeTemplateLV(
334 LinkageInfo &LV, const FunctionDecl *fn,
335 const FunctionTemplateSpecializationInfo *specInfo,
336 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000337 bool considerVisibility =
338 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000339
340 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000341 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000342 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000343 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000344 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
345
346 // Merge information from the template arguments.
347 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000348 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000349 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000350}
351
John McCall5f46c482013-02-21 23:42:58 +0000352/// Does the given declaration have a direct visibility attribute
353/// that would match the given rules?
354static bool hasDirectVisibilityAttribute(const NamedDecl *D,
355 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000356 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000357 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000358
359 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
360 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000361}
362
John McCalld041a9b2013-02-20 01:54:26 +0000363/// Should we consider visibility associated with the template
364/// arguments and parameters of the given class template specialization?
365static bool shouldConsiderTemplateVisibility(
366 const ClassTemplateSpecializationDecl *spec,
367 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000368 // Include visibility from the template parameters and arguments
369 // only if this is not an explicit instantiation or specialization
370 // with direct explicit visibility (and note that implicit
371 // instantiations won't have a direct attribute).
372 //
373 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000374 // for an explicit specialization when computing the visibility of a
375 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000376 //
377 // This is a bit complex; let's unpack it.
378 //
379 // An explicit class specialization is an independent, top-level
380 // declaration. As such, if it or any of its members has an
381 // explicit visibility attribute, that must directly express the
382 // user's intent, and we should honor it. The same logic applies to
383 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000384
385 // Fast path: if this is not an explicit instantiation or
386 // specialization, we always want to consider template-related
387 // visibility restrictions.
388 if (!spec->isExplicitInstantiationOrSpecialization())
389 return true;
390
391 // This is the 'member thereof' check.
392 if (spec->isExplicitSpecialization() &&
393 hasExplicitVisibilityAlready(computation))
394 return false;
395
John McCall5f46c482013-02-21 23:42:58 +0000396 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000397}
398
399/// Merge in template-related linkage and visibility for the given
400/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000401void LinkageComputer::mergeTemplateLV(
402 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
403 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000404 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000405
406 // Merge information from the template parameters, but ignore
407 // visibility if we're only considering template arguments.
408
John McCalld041a9b2013-02-20 01:54:26 +0000409 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000410 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000411 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000412 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000413 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000414
415 // Merge information from the template arguments. We ignore
416 // template-argument visibility if we've got an explicit
417 // instantiation with a visibility attribute.
418 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000419 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000420 if (considerVisibility)
421 LV.mergeVisibility(argsLV);
422 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000423}
424
Larisse Voufo5899e192014-07-02 23:08:34 +0000425/// Should we consider visibility associated with the template
426/// arguments and parameters of the given variable template
427/// specialization? As usual, follow class template specialization
428/// logic up to initialization.
429static bool shouldConsiderTemplateVisibility(
430 const VarTemplateSpecializationDecl *spec,
431 LVComputationKind computation) {
432 // Include visibility from the template parameters and arguments
433 // only if this is not an explicit instantiation or specialization
434 // with direct explicit visibility (and note that implicit
435 // instantiations won't have a direct attribute).
436 if (!spec->isExplicitInstantiationOrSpecialization())
437 return true;
438
439 // An explicit variable specialization is an independent, top-level
440 // declaration. As such, if it has an explicit visibility attribute,
441 // that must directly express the user's intent, and we should honor
442 // it.
443 if (spec->isExplicitSpecialization() &&
444 hasExplicitVisibilityAlready(computation))
445 return false;
446
447 return !hasDirectVisibilityAttribute(spec, computation);
448}
449
450/// Merge in template-related linkage and visibility for the given
451/// variable template specialization. As usual, follow class template
452/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000453void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
454 const VarTemplateSpecializationDecl *spec,
455 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000456 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
457
458 // Merge information from the template parameters, but ignore
459 // visibility if we're only considering template arguments.
460
461 VarTemplateDecl *temp = spec->getSpecializedTemplate();
462 LinkageInfo tempLV =
463 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
464 LV.mergeMaybeWithVisibility(tempLV,
465 considerVisibility && !hasExplicitVisibilityAlready(computation));
466
467 // Merge information from the template arguments. We ignore
468 // template-argument visibility if we've got an explicit
469 // instantiation with a visibility attribute.
470 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
471 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
472 if (considerVisibility)
473 LV.mergeVisibility(argsLV);
474 LV.mergeExternalVisibility(argsLV);
475}
476
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000477static bool useInlineVisibilityHidden(const NamedDecl *D) {
478 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000479 const LangOptions &Opts = D->getASTContext().getLangOpts();
480 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000481 return false;
482
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000483 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000484 if (!FD)
485 return false;
486
487 TemplateSpecializationKind TSK = TSK_Undeclared;
488 if (FunctionTemplateSpecializationInfo *spec
489 = FD->getTemplateSpecializationInfo()) {
490 TSK = spec->getTemplateSpecializationKind();
491 } else if (MemberSpecializationInfo *MSI =
492 FD->getMemberSpecializationInfo()) {
493 TSK = MSI->getTemplateSpecializationKind();
494 }
495
Craig Topper36250ad2014-05-12 05:36:57 +0000496 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000497 // InlineVisibilityHidden only applies to definitions, and
498 // isInlined() only gives meaningful answers on definitions
499 // anyway.
500 return TSK != TSK_ExplicitInstantiationDeclaration &&
501 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000502 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000503}
504
Rafael Espindola593537a2013-05-05 20:15:21 +0000505template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000506 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000507 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000508}
509
Richard Smith03c05032014-02-17 23:34:47 +0000510static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000511 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000512 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000513 return true;
514 return false;
515}
516
Richard Smith1283e982017-07-07 20:04:28 +0000517static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) {
518 switch (D->getModuleOwnershipKind()) {
519 case Decl::ModuleOwnershipKind::Unowned:
520 case Decl::ModuleOwnershipKind::ModulePrivate:
521 return false;
522 case Decl::ModuleOwnershipKind::Visible:
523 case Decl::ModuleOwnershipKind::VisibleWhenImported:
524 if (auto *M = D->getOwningModule())
525 return M->Kind == Module::ModuleInterfaceUnit;
526 }
527 llvm_unreachable("unexpected module ownership kind");
528}
529
530static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
531 // Internal linkage declarations within a module interface unit are modeled
532 // as "module-internal linkage", which means that they have internal linkage
533 // formally but can be indirectly accessed from outside the module via inline
534 // functions and templates defined within the module.
535 if (auto *M = D->getOwningModule())
536 if (M->Kind == Module::ModuleInterfaceUnit)
537 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
538
539 return LinkageInfo::internal();
540}
541
542static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
543 // C++ Modules TS [basic.link]/6.8:
544 // - A name declared at namespace scope that does not have internal linkage
545 // by the previous rules and that is introduced by a non-exported
546 // declaration has module linkage.
547 if (auto *M = D->getOwningModule())
548 if (M->Kind == Module::ModuleInterfaceUnit)
549 if (!isExportedFromModuleIntefaceUnit(D))
550 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
551
552 return LinkageInfo::external();
553}
554
George Burgess IV99db3ea2017-08-09 04:02:49 +0000555LinkageInfo
556LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
557 LVComputationKind computation) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000558 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000559 "Not a name having namespace scope");
560 ASTContext &Context = D->getASTContext();
561
562 // C++ [basic.link]p3:
563 // A name having namespace scope (3.3.6) has internal linkage if it
564 // is the name of
565 // - an object, reference, function or function template that is
566 // explicitly declared static; or,
567 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000568 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000569 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000570 if (Var->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000571 return getInternalLinkageFor(Var);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000572
Richard Smith62f19e72016-06-25 00:15:56 +0000573 // - a non-inline, non-volatile object or reference that is explicitly
574 // declared const or constexpr and neither explicitly declared extern
575 // nor previously declared to have external linkage; or (there is no
576 // equivalent in C99)
Richard Smith1283e982017-07-07 20:04:28 +0000577 // The C++ modules TS adds "non-exported" to this list.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000578 if (Context.getLangOpts().CPlusPlus &&
Richard Smithdc0ef452012-10-19 06:37:48 +0000579 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000580 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000581 !Var->isInline() &&
582 !isExportedFromModuleIntefaceUnit(Var)) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000583 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000584 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000585 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000586
587 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000588 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000589 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000590 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000591 }
592
593 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
594 PrevVar = PrevVar->getPreviousDecl()) {
595 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
596 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000597 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000598 // Explicitly declared static.
599 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000600 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000601 }
Alp Tokera2794f92014-01-22 07:29:52 +0000602 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000603 // C++ [temp]p4:
604 // A non-member function template can have internal linkage; any
605 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000606
607 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000608 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000609 return getInternalLinkageFor(Function);
David Majnemer18fac3b2014-12-10 22:58:14 +0000610 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
611 // - a data member of an anonymous union.
612 const VarDecl *VD = IFD->getVarDecl();
613 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
614 return getLVForNamespaceScopeDecl(VD, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000615 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000616 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000617
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000618 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000619 const auto *Var = dyn_cast<VarDecl>(D);
620 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smith97135cc2015-11-12 22:19:45 +0000621 // FIXME: In C++11 onwards, anonymous namespaces should give decls
Richard Smith1283e982017-07-07 20:04:28 +0000622 // within them (including those inside extern "C" contexts) internal
623 // linkage, not unique external linkage:
624 //
625 // C++11 [basic.link]p4:
626 // An unnamed namespace or a namespace declared directly or indirectly
627 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000628 if ((!Var || !isFirstInExternCContext(Var)) &&
629 (!Func || !isFirstInExternCContext(Func)))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000630 return LinkageInfo::uniqueExternal();
631 }
John McCallb7139c42010-10-28 04:18:25 +0000632
John McCall457a04e2010-10-22 21:05:15 +0000633 // Set up the defaults.
634
635 // C99 6.2.2p5:
636 // If the declaration of an identifier for an object has file
637 // scope and no storage-class specifier, its linkage is
638 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000639 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000640
John McCalld041a9b2013-02-20 01:54:26 +0000641 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000642 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000643 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000644 } else {
645 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000646 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000647 for (const DeclContext *DC = D->getDeclContext();
648 !isa<TranslationUnitDecl>(DC);
649 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000650 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000651 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000652 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000653 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000654 break;
655 }
656 }
657 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000658
John McCalldf25c432013-02-16 00:17:33 +0000659 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000660 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000661 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000662 Visibility globalVisibility =
663 computation.isValueVisibility()
664 ? Context.getLangOpts().getValueVisibilityMode()
665 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000666 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000667
668 // If we're paying attention to global visibility, apply
669 // -finline-visibility-hidden if this is an inline method.
670 if (useInlineVisibilityHidden(D))
671 LV.mergeVisibility(HiddenVisibility, true);
672 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000673 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000674
Douglas Gregorf73b2822009-11-25 22:24:25 +0000675 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000676
Douglas Gregorf73b2822009-11-25 22:24:25 +0000677 // A name having namespace scope has external linkage if it is the
678 // name of
679 //
680 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000681 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000682 // GCC applies the following optimization to variables and static
683 // data members, but not to functions:
684 //
John McCall457a04e2010-10-22 21:05:15 +0000685 // Modify the variable's LV by the LV of its type unless this is
686 // C or extern "C". This follows from [basic.link]p9:
687 // A type without linkage shall not be used as the type of a
688 // variable or function with external linkage unless
689 // - the entity has C language linkage, or
690 // - the entity is declared within an unnamed namespace, or
691 // - the entity is not used or is defined in the same
692 // translation unit.
693 // and [basic.link]p10:
694 // ...the types specified by all declarations referring to a
695 // given variable or function shall be identical...
696 // C does not have an equivalent rule.
697 //
John McCall5fe84122010-10-26 04:59:26 +0000698 // Ignore this if we've got an explicit attribute; the user
699 // probably knows what they're doing.
700 //
John McCall457a04e2010-10-22 21:05:15 +0000701 // Note that we don't want to make the variable non-external
702 // because of this, but unique-external linkage suits us.
Vitaly Buka17def212017-09-21 02:51:56 +0000703 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000704 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000705 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000706 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000707 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000708 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000709 }
710
John McCall23032652010-11-02 18:38:13 +0000711 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000712 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000713
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000714 // Note that Sema::MergeVarDecl already takes care of implementing
715 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
716 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000717
Larisse Voufo5899e192014-07-02 23:08:34 +0000718 // As per function and class template specializations (below),
719 // consider LV for the template and template arguments. We're at file
720 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000721 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000722 mergeTemplateLV(LV, spec, computation);
723 }
724
Douglas Gregorf73b2822009-11-25 22:24:25 +0000725 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000726 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000727 // In theory, we can modify the function's LV by the LV of its
728 // type unless it has C linkage (see comment above about variables
729 // for justification). In practice, GCC doesn't do this, so it's
730 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000731
John McCall23032652010-11-02 18:38:13 +0000732 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000733 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000734
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000735 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
736 // merging storage classes and visibility attributes, so we don't have to
737 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000738
John McCallf768aa72011-02-10 06:50:24 +0000739 // In C++, then if the type of the function uses a type with
740 // unique-external linkage, it's not legally usable from outside
741 // this translation unit. However, we should use the C linkage
742 // rules instead for extern "C" declarations.
Vitaly Buka17def212017-09-21 02:51:56 +0000743 if (Context.getLangOpts().CPlusPlus &&
744 !Function->isInExternCContext()) {
Richard Smith50f4afc2013-05-12 23:17:59 +0000745 // Only look at the type-as-written. If this function has an auto-deduced
746 // return type, we can't compute the linkage of that type because it could
747 // require looking at the linkage of this function, and we don't need this
748 // for correctness because the type is not part of the function's
749 // signature.
Faisal Valid2598e92013-10-08 04:15:04 +0000750 // FIXME: This is a hack. We should be able to solve this circularity and
751 // the one in getLVForClassMember for Functions some other way.
Richard Smith50f4afc2013-05-12 23:17:59 +0000752 QualType TypeAsWritten = Function->getType();
753 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
754 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000755 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000756 return LinkageInfo::uniqueExternal();
757 }
John McCallf768aa72011-02-10 06:50:24 +0000758
John McCall5f46c482013-02-21 23:42:58 +0000759 // Consider LV from the template and the template arguments.
760 // We're at file scope, so we do not need to worry about nested
761 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000762 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000763 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000764 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000765 }
766
Douglas Gregorf73b2822009-11-25 22:24:25 +0000767 // - a named class (Clause 9), or an unnamed class defined in a
768 // typedef declaration in which the class has the typedef name
769 // for linkage purposes (7.1.3); or
770 // - a named enumeration (7.2), or an unnamed enumeration
771 // defined in a typedef declaration in which the enumeration
772 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000773 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000774 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000775 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000776 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000777
John McCall457a04e2010-10-22 21:05:15 +0000778 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000779 // linkage of the template and template arguments. We're at file
780 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000781 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000782 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000783 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000784
785 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000786 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000787 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000788 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000789 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000790 return LinkageInfo::none();
791 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000792
793 // - a template, unless it is a function template that has
794 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000795 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000796 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000797 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000798 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000799 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
800
Douglas Gregorf73b2822009-11-25 22:24:25 +0000801 // - a namespace (7.3), unless it is declared within an unnamed
802 // namespace.
Richard Smith1283e982017-07-07 20:04:28 +0000803 //
804 // We handled names in anonymous namespaces above.
805 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000806 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000807
John McCall457a04e2010-10-22 21:05:15 +0000808 // By extension, we assign external linkage to Objective-C
809 // interfaces.
810 } else if (isa<ObjCInterfaceDecl>(D)) {
811 // fallout
812
Richard Smith97135cc2015-11-12 22:19:45 +0000813 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
814 // A typedef declaration has linkage if it gives a type a name for
815 // linkage purposes.
816 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
817 return LinkageInfo::none();
818
John McCall457a04e2010-10-22 21:05:15 +0000819 // Everything not covered here has no linkage.
820 } else {
John McCallc273f242010-10-30 11:50:40 +0000821 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000822 }
823
824 // If we ended up with non-external linkage, visibility should
825 // always be default.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000826 if (LV.getLinkage() != ExternalLinkage)
827 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000828
John McCall457a04e2010-10-22 21:05:15 +0000829 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000830}
831
George Burgess IV99db3ea2017-08-09 04:02:49 +0000832LinkageInfo
833LinkageComputer::getLVForClassMember(const NamedDecl *D,
834 LVComputationKind computation) {
John McCall457a04e2010-10-22 21:05:15 +0000835 // Only certain class members have linkage. Note that fields don't
836 // really have linkage, but it's convenient to say they do for the
837 // purposes of calculating linkage of pointer-to-data-member
838 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000839 //
840 // Templates also don't officially have linkage, but since we ignore
841 // the C++ standard and look at template arguments when determining
842 // linkage and visibility of a template specialization, we might hit
843 // a template template argument that way. If we do, we need to
844 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000845 if (!(isa<CXXMethodDecl>(D) ||
846 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000847 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000848 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000849 isa<TagDecl>(D) ||
850 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000851 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000852
John McCall07072662010-11-02 01:45:15 +0000853 LinkageInfo LV;
854
John McCall07072662010-11-02 01:45:15 +0000855 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000856 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000857 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000858 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000859 // If we're paying attention to global visibility, apply
860 // -finline-visibility-hidden if this is an inline method.
861 //
862 // Note that we do this before merging information about
863 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000864 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000865 LV.mergeVisibility(HiddenVisibility, true);
John McCall07072662010-11-02 01:45:15 +0000866 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000867
868 // If this class member has an explicit visibility attribute, the only
869 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000870 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000871 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000872 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000873 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000874
John McCall5f46c482013-02-21 23:42:58 +0000875 LinkageInfo classLV =
876 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
John McCall8823c652010-08-13 08:35:10 +0000877 // If the class already has unique-external linkage, we can't improve.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000878 if (classLV.getLinkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000879 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000880
Rafael Espindolae6190db2013-05-28 02:22:10 +0000881 if (!isExternallyVisible(classLV.getLinkage()))
882 return LinkageInfo::none();
883
884
John McCall5f46c482013-02-21 23:42:58 +0000885 // Otherwise, don't merge in classLV yet, because in certain cases
886 // we need to completely ignore the visibility from it.
887
888 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000889 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000890
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000891 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smith405e2db2017-09-20 07:22:00 +0000892 // If the type of the function uses a type that has non-externally-visible
John McCallf768aa72011-02-10 06:50:24 +0000893 // linkage, it's not legally usable from outside this translation unit.
Nico Weber38267342015-04-22 03:44:51 +0000894 // But only look at the type-as-written. If this function has an
895 // auto-deduced return type, we can't compute the linkage of that type
896 // because it could require looking at the linkage of this function, and we
897 // don't need this for correctness because the type is not part of the
898 // function's signature.
899 // FIXME: This is a hack. We should be able to solve this circularity and
900 // the one in getLVForNamespaceScopeDecl for Functions some other way.
Faisal Valid2598e92013-10-08 04:15:04 +0000901 {
902 QualType TypeAsWritten = MD->getType();
903 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
904 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000905 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Faisal Valid2598e92013-10-08 04:15:04 +0000906 return LinkageInfo::uniqueExternal();
907 }
John McCall457a04e2010-10-22 21:05:15 +0000908 // If this is a method template specialization, use the linkage for
909 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000910 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000911 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000912 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000913 if (spec->isExplicitSpecialization()) {
914 explicitSpecSuppressor = MD;
915 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
916 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
917 }
918 } else if (isExplicitMemberSpecialization(MD)) {
919 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000920 }
John McCall457a04e2010-10-22 21:05:15 +0000921
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000922 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
923 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000924 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000925 if (spec->isExplicitSpecialization()) {
926 explicitSpecSuppressor = spec;
927 } else {
928 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
929 if (isExplicitMemberSpecialization(temp)) {
930 explicitSpecSuppressor = temp->getTemplatedDecl();
931 }
932 }
933 } else if (isExplicitMemberSpecialization(RD)) {
934 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000935 }
936
John McCall37bb6c92010-10-29 22:22:43 +0000937 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000938 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
939 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000940 mergeTemplateLV(LV, spec, computation);
941
John McCall36cd5cc2010-10-30 09:18:49 +0000942 // Modify the variable's linkage by its type, but ignore the
943 // type's visibility unless it's a definition.
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000944 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000945 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
946 LV.mergeVisibility(typeLV);
947 LV.mergeExternalVisibility(typeLV);
John McCall5f46c482013-02-21 23:42:58 +0000948
949 if (isExplicitMemberSpecialization(VD)) {
950 explicitSpecSuppressor = VD;
951 }
John McCalldf25c432013-02-16 00:17:33 +0000952
953 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000954 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +0000955 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +0000956 (!LV.isVisibilityExplicit() &&
957 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +0000958 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000959 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000960 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000961 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +0000962
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000963 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +0000964 if (isExplicitMemberSpecialization(redeclTemp)) {
965 explicitSpecSuppressor = temp->getTemplatedDecl();
966 }
967 }
John McCall37bb6c92010-10-29 22:22:43 +0000968 }
969
John McCall5f46c482013-02-21 23:42:58 +0000970 // We should never be looking for an attribute directly on a template.
971 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
972
973 // If this member is an explicit member specialization, and it has
974 // an explicit attribute, ignore visibility from the parent.
975 bool considerClassVisibility = true;
976 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +0000977 // optimization: hasDVA() is true only with explicit visibility.
978 LV.isVisibilityExplicit() &&
979 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +0000980 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
981 considerClassVisibility = false;
982 }
983
984 // Finally, merge in information from the class.
985 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +0000986 return LV;
John McCall8823c652010-08-13 08:35:10 +0000987}
988
David Blaikie68e081d2011-12-20 02:48:34 +0000989void NamedDecl::anchor() { }
990
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000991bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +0000992 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +0000993 return true;
John McCalld396b972011-02-08 19:01:05 +0000994
Richard Smithfbe7b462017-09-22 02:22:32 +0000995 Linkage L = LinkageComputer{}
996 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
997 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +0000998 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +0000999}
1000
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001001ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1002 StringRef name = getName();
1003 if (name.empty()) return SFF_None;
1004
1005 if (name.front() == 'C')
1006 if (name == "CFStringCreateWithFormat" ||
1007 name == "CFStringCreateWithFormatAndArguments" ||
1008 name == "CFStringAppendFormat" ||
1009 name == "CFStringAppendFormatAndArguments")
1010 return SFF_CFString;
1011 return SFF_None;
1012}
1013
Rafael Espindola3ae00052013-05-13 00:12:11 +00001014Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001015 // We don't care about visibility here, so ask for the cheapest
1016 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001017 return LinkageComputer{}
1018 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1019 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001020}
1021
John McCallc273f242010-10-30 11:50:40 +00001022LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001023 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001024}
Ted Kremenek926d8602010-04-20 23:15:35 +00001025
Rafael Espindola9ad61122013-11-26 16:09:08 +00001026static Optional<Visibility>
1027getExplicitVisibilityAux(const NamedDecl *ND,
1028 NamedDecl::ExplicitVisibilityKind kind,
1029 bool IsMostRecent) {
1030 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1031
Rafael Espindola3a52c442013-02-26 19:33:14 +00001032 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001033 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001034 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001035
Rafael Espindola3a52c442013-02-26 19:33:14 +00001036 // If this is a member class of a specialization of a class template
1037 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001038 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001039 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1040 if (InstantiatedFrom)
1041 return getVisibilityOf(InstantiatedFrom, kind);
1042 }
1043
1044 // If there wasn't explicit visibility there, and this is a
1045 // specialization of a class template, check for visibility
1046 // on the pattern.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001047 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001048 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1049 kind);
1050
1051 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001052 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001053 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1054 if (MostRecent != ND)
1055 return getExplicitVisibilityAux(MostRecent, kind, true);
1056 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001057
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001058 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001059 if (Var->isStaticDataMember()) {
1060 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1061 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001062 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001063 }
1064
David Majnemer35b02bc2014-04-29 07:32:26 +00001065 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1066 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1067 kind);
1068
David Blaikie7a30dc52013-02-21 01:47:18 +00001069 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001070 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001071 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001072 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001073 // If the function is a specialization of a template with an
1074 // explicit visibility attribute, use that.
1075 if (FunctionTemplateSpecializationInfo *templateInfo
1076 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001077 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1078 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001079
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001080 // If the function is a member of a specialization of a class template
1081 // and the corresponding decl has explicit visibility, use that.
1082 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1083 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001084 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001085
David Blaikie7a30dc52013-02-21 01:47:18 +00001086 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001087 }
1088
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001089 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001090 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001091 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001092
David Blaikie7a30dc52013-02-21 01:47:18 +00001093 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001094}
1095
Rafael Espindola9ad61122013-11-26 16:09:08 +00001096Optional<Visibility>
1097NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1098 return getExplicitVisibilityAux(this, kind, false);
1099}
1100
George Burgess IV99db3ea2017-08-09 04:02:49 +00001101LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1102 Decl *ContextDecl,
1103 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001104 // This lambda has its linkage/visibility determined by its owner.
Richard Smith405e2db2017-09-20 07:22:00 +00001105 // FIXME: This is wrong. A lambda never formally has linkage; if this
1106 // calculation determines the lambda has external linkage, it should be
1107 // downgraded to VisibleNoLinkage.
Eli Friedman7e346a82013-07-01 20:22:57 +00001108 if (ContextDecl) {
1109 if (isa<ParmVarDecl>(ContextDecl))
1110 DC = ContextDecl->getDeclContext()->getRedeclContext();
1111 else
1112 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1113 }
Faisal Vali98b8e182013-09-29 20:27:06 +00001114
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001115 if (const auto *ND = dyn_cast<NamedDecl>(DC))
Eli Friedman7e346a82013-07-01 20:22:57 +00001116 return getLVForDecl(ND, computation);
Faisal Vali98b8e182013-09-29 20:27:06 +00001117
Richard Smith1283e982017-07-07 20:04:28 +00001118 // FIXME: We have a closure at TU scope with no context declaration. This
1119 // should probably have no linkage.
Eli Friedman7e346a82013-07-01 20:22:57 +00001120 return LinkageInfo::external();
1121}
1122
George Burgess IV99db3ea2017-08-09 04:02:49 +00001123LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1124 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001125 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001126 if (Function->isInAnonymousNamespace() &&
Rafael Espindola593537a2013-05-05 20:15:21 +00001127 !Function->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001128 return LinkageInfo::uniqueExternal();
1129
1130 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001131 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001132 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001133
1134 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001135 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001136 if (Optional<Visibility> Vis =
1137 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001138 LV.mergeVisibility(*Vis, true);
1139 }
1140
1141 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1142 // merging storage classes and visibility attributes, so we don't have to
1143 // look at previous decls in here.
1144
1145 return LV;
1146 }
1147
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001148 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001149 if (Var->hasExternalStorage()) {
Rafael Espindola593537a2013-05-05 20:15:21 +00001150 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
John McCalldf25c432013-02-16 00:17:33 +00001151 return LinkageInfo::uniqueExternal();
1152
John McCalldf25c432013-02-16 00:17:33 +00001153 LinkageInfo LV;
1154 if (Var->getStorageClass() == SC_PrivateExtern)
1155 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001156 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001157 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001158 LV.mergeVisibility(*Vis, true);
1159 }
1160
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001161 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1162 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1163 if (PrevLV.getLinkage())
1164 LV.setLinkage(PrevLV.getLinkage());
1165 LV.mergeVisibility(PrevLV);
1166 }
1167
John McCalldf25c432013-02-16 00:17:33 +00001168 return LV;
1169 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001170
1171 if (!Var->isStaticLocal())
1172 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001173 }
1174
Rafael Espindolaa4184182013-06-17 20:04:51 +00001175 ASTContext &Context = D->getASTContext();
1176 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001177 return LinkageInfo::none();
1178
Eli Friedman7e346a82013-07-01 20:22:57 +00001179 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001180 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001181 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001182
Eli Friedman7e346a82013-07-01 20:22:57 +00001183 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001184 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001185 if (!BD->getBlockManglingNumber())
1186 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001187
Eli Friedman7e346a82013-07-01 20:22:57 +00001188 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1189 BD->getBlockManglingContextDecl(), computation);
1190 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001191 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001192 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001193 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001194 return LinkageInfo::none();
1195
1196 LV = getLVForDecl(FD, computation);
1197 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001198 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001199 return LinkageInfo::none();
1200 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1201 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001202}
1203
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001204static inline const CXXRecordDecl*
1205getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1206 const CXXRecordDecl *Ret = Record;
1207 while (Record && Record->isLambda()) {
1208 Ret = Record;
1209 if (!Record->getParent()) break;
1210 // Get the Containing Class of this Lambda Class
1211 Record = dyn_cast_or_null<CXXRecordDecl>(
1212 Record->getParent()->getParent());
1213 }
1214 return Ret;
1215}
1216
George Burgess IV99db3ea2017-08-09 04:02:49 +00001217LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1218 LVComputationKind computation) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001219 // Internal_linkage attribute overrides other considerations.
1220 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001221 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001222
Ted Kremenek926d8602010-04-20 23:15:35 +00001223 // Objective-C: treat all Objective-C declarations as having external
1224 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001225 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001226 default:
1227 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001228
1229 // Per C++ [basic.link]p2, only the names of objects, references,
1230 // functions, types, templates, namespaces, and values ever have linkage.
1231 //
1232 // Note that the name of a typedef, namespace alias, using declaration,
1233 // and so on are not the name of the corresponding type, namespace, or
1234 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001235 case Decl::ImplicitParam:
1236 case Decl::Label:
1237 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001238 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001239 case Decl::Using:
1240 case Decl::UsingShadow:
1241 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001242 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001243
Richard Smith26210db2015-11-13 03:52:13 +00001244 case Decl::EnumConstant:
1245 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001246 if (D->getASTContext().getLangOpts().CPlusPlus)
1247 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1248 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001249
Richard Smith97135cc2015-11-12 22:19:45 +00001250 case Decl::Typedef:
1251 case Decl::TypeAlias:
1252 // A typedef declaration has linkage if it gives a type a name for
1253 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001254 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001255 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1256 return LinkageInfo::none();
1257 break;
1258
John McCall457a04e2010-10-22 21:05:15 +00001259 case Decl::TemplateTemplateParm: // count these as external
1260 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001261 case Decl::ObjCAtDefsField:
1262 case Decl::ObjCCategory:
1263 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001264 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001265 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001266 case Decl::ObjCMethod:
1267 case Decl::ObjCProperty:
1268 case Decl::ObjCPropertyImpl:
1269 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001270 return getExternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001271
1272 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001273 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001274 if (Record->isLambda()) {
1275 if (!Record->getLambdaManglingNumber()) {
1276 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001277 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001278 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001279
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001280 // This lambda has its linkage/visibility determined:
1281 // - either by the outermost lambda if that lambda has no mangling
1282 // number.
1283 // - or by the parent of the outer most lambda
1284 // This prevents infinite recursion in settings such as nested lambdas
1285 // used in NSDMI's, for e.g.
1286 // struct L {
1287 // int t{};
1288 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1289 // };
1290 const CXXRecordDecl *OuterMostLambda =
1291 getOutermostEnclosingLambda(Record);
1292 if (!OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001293 return getInternalLinkageFor(D);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001294
1295 return getLVForClosure(
1296 OuterMostLambda->getDeclContext()->getRedeclContext(),
1297 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001298 }
1299
1300 break;
1301 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001302 }
1303
Douglas Gregorf73b2822009-11-25 22:24:25 +00001304 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001305 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCalldf25c432013-02-16 00:17:33 +00001306 return getLVForNamespaceScopeDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001307
1308 // C++ [basic.link]p5:
1309 // In addition, a member function, static data member, a named
1310 // class or enumeration of class scope, or an unnamed class or
1311 // enumeration defined in a class-scope typedef declaration such
1312 // that the class or enumeration has the typedef name for linkage
1313 // purposes (7.1.3), has external linkage if the name of the class
1314 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001315 if (D->getDeclContext()->isRecord())
John McCalldf25c432013-02-16 00:17:33 +00001316 return getLVForClassMember(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001317
1318 // C++ [basic.link]p6:
1319 // The name of a function declared in block scope and the name of
1320 // an object declared by a block scope extern declaration have
1321 // linkage. If there is a visible declaration of an entity with
1322 // linkage having the same name and type, ignoring entities
1323 // declared outside the innermost enclosing namespace scope, the
1324 // block scope declaration declares that same entity and receives
1325 // the linkage of the previous declaration. If there is more than
1326 // one such matching entity, the program is ill-formed. Otherwise,
1327 // if no matching entity is found, the block scope entity receives
1328 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001329 if (D->getDeclContext()->isFunctionOrMethod())
1330 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001331
1332 // C++ [basic.link]p6:
1333 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001334 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001335}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001336
George Burgess IV99db3ea2017-08-09 04:02:49 +00001337/// getLVForDecl - Get the linkage and visibility for the given declaration.
1338LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1339 LVComputationKind computation) {
1340 // Internal_linkage attribute overrides other considerations.
1341 if (D->hasAttr<InternalLinkageAttr>())
1342 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001343
Richard Smithfbe7b462017-09-22 02:22:32 +00001344 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001345 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001346
George Burgess IV35cb4f82017-08-09 04:12:17 +00001347 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1348 return *LI;
1349
George Burgess IV99db3ea2017-08-09 04:02:49 +00001350 LinkageInfo LV = computeLVForDecl(D, computation);
1351 if (D->hasCachedLinkage())
1352 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001353
George Burgess IV99db3ea2017-08-09 04:02:49 +00001354 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001355 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001356
1357#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001358 // In C (because of gnu inline) and in c++ with microsoft extensions an
1359 // static can follow an extern, so we can have two decls with different
1360 // linkages.
1361 const LangOptions &Opts = D->getASTContext().getLangOpts();
1362 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1363 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001364
George Burgess IV99db3ea2017-08-09 04:02:49 +00001365 // We have just computed the linkage for this decl. By induction we know
1366 // that all other computed linkages match, check that the one we just
1367 // computed also does.
1368 NamedDecl *Old = nullptr;
1369 for (auto I : D->redecls()) {
1370 auto *T = cast<NamedDecl>(I);
1371 if (T == D)
1372 continue;
1373 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1374 Old = T;
1375 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001376 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001377 }
1378 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001379#endif
1380
George Burgess IV99db3ea2017-08-09 04:02:49 +00001381 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001382}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001383
George Burgess IV99db3ea2017-08-09 04:02:49 +00001384LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001385 return getLVForDecl(D,
1386 LVComputationKind(usesTypeVisibility(D)
1387 ? NamedDecl::VisibilityForType
1388 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001389}
1390
Richard Smithdd8b5332017-09-04 05:37:53 +00001391Module *NamedDecl::getOwningModuleForLinkage() const {
1392 Module *M = getOwningModule();
1393 if (!M)
1394 return nullptr;
1395
1396 switch (M->Kind) {
1397 case Module::ModuleMapModule:
1398 // Module map modules have no special linkage semantics.
1399 return nullptr;
1400
1401 case Module::ModuleInterfaceUnit:
1402 return M;
1403
1404 case Module::GlobalModuleFragment:
1405 // External linkage declarations in the global module have no owning module
1406 // for linkage purposes. But internal linkage declarations in the global
1407 // module fragment of a particular module are owned by that module for
1408 // linkage purposes.
1409 return hasExternalFormalLinkage() ? nullptr : M->Parent;
1410 }
1411
1412 llvm_unreachable("unknown module kind");
1413}
1414
Richard Smith7873de02016-08-11 22:25:46 +00001415void NamedDecl::printName(raw_ostream &os) const {
1416 os << Name;
1417}
1418
Douglas Gregor2ada0482009-02-04 17:27:36 +00001419std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001420 std::string QualName;
1421 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001422 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001423 return OS.str();
1424}
1425
1426void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1427 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1428}
1429
1430void NamedDecl::printQualifiedName(raw_ostream &OS,
1431 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001432 const DeclContext *Ctx = getDeclContext();
1433
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001434 // For ObjC methods, look through categories and use the interface as context.
1435 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1436 if (auto *ID = MD->getClassInterface())
1437 Ctx = ID;
1438
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001439 if (Ctx->isFunctionOrMethod()) {
1440 printName(OS);
1441 return;
1442 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001443
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001444 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001445 ContextsTy Contexts;
1446
1447 // Collect contexts.
1448 while (Ctx && isa<NamedDecl>(Ctx)) {
1449 Contexts.push_back(Ctx);
1450 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001451 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001452
David Majnemerf7e36092016-06-23 00:15:04 +00001453 for (const DeclContext *DC : reverse(Contexts)) {
1454 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001455 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001456 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
David Majnemer6fbeee32016-07-07 04:43:07 +00001457 TemplateSpecializationType::PrintTemplateArgumentList(
1458 OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001459 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001460 if (P.SuppressUnwrittenScope &&
1461 (ND->isAnonymousNamespace() || ND->isInline()))
1462 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001463 if (ND->isAnonymousNamespace()) {
1464 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1465 : "(anonymous namespace)");
1466 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001467 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001468 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001469 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001470 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001471 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001472 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001473 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001474 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001475 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001476 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001477 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001478
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001479 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001480 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001481 unsigned NumParams = FD->getNumParams();
1482 for (unsigned i = 0; i < NumParams; ++i) {
1483 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001484 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001485 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001486 }
1487
1488 if (FT->isVariadic()) {
1489 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001490 OS << ", ";
1491 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001492 }
1493 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001494 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001495 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001496 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1497 // enumerator is declared in the scope that immediately contains
1498 // the enum-specifier. Each scoped enumerator is declared in the
1499 // scope of the enumeration.
1500 if (ED->isScoped() || ED->getIdentifier())
1501 OS << *ED;
1502 else
1503 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001504 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001505 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001506 }
1507 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001508 }
1509
Richard Smith7873de02016-08-11 22:25:46 +00001510 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001511 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001512 else
David Blaikieabe1a392014-04-02 05:58:29 +00001513 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001514}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001515
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001516void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1517 const PrintingPolicy &Policy,
1518 bool Qualified) const {
1519 if (Qualified)
1520 printQualifiedName(OS, Policy);
1521 else
1522 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001523}
1524
Richard Smithe8292b12015-02-10 03:28:10 +00001525template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1526 return true;
1527}
1528static bool isRedeclarableImpl(...) { return false; }
1529static bool isRedeclarable(Decl::Kind K) {
1530 switch (K) {
1531#define DECL(Type, Base) \
1532 case Decl::Type: \
1533 return isRedeclarableImpl((Type##Decl *)nullptr);
1534#define ABSTRACT_DECL(DECL)
1535#include "clang/AST/DeclNodes.inc"
1536 }
1537 llvm_unreachable("unknown decl kind");
1538}
1539
1540bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001541 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1542
Richard Smithfe620d22015-03-05 23:24:12 +00001543 // Never replace one imported declaration with another; we need both results
1544 // when re-exporting.
1545 if (OldD->isFromASTFile() && isFromASTFile())
1546 return false;
1547
Richard Smith5cd86f82015-11-03 03:13:11 +00001548 // A kind mismatch implies that the declaration is not replaced.
1549 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001550 return false;
1551
Richard Smith5cd86f82015-11-03 03:13:11 +00001552 // For method declarations, we never replace. (Why?)
1553 if (isa<ObjCMethodDecl>(this))
1554 return false;
1555
1556 // For parameters, pick the newer one. This is either an error or (in
1557 // Objective-C) permitted as an extension.
1558 if (isa<ParmVarDecl>(this))
1559 return true;
1560
Richard Smithe8292b12015-02-10 03:28:10 +00001561 // Inline namespaces can give us two declarations with the same
1562 // name and kind in the same scope but different contexts; we should
1563 // keep both declarations in this case.
1564 if (!this->getDeclContext()->getRedeclContext()->Equals(
1565 OldD->getDeclContext()->getRedeclContext()))
1566 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001567
Richard Smith5cd86f82015-11-03 03:13:11 +00001568 // Using declarations can be replaced if they import the same name from the
1569 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001570 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001571 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001572 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001573 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001574 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001575 }
Richard Smithe8292b12015-02-10 03:28:10 +00001576 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001577 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001578 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001579 Context.getCanonicalNestedNameSpecifier(
1580 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1581 }
1582
Richard Smithe8292b12015-02-10 03:28:10 +00001583 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
Richard Smith5cd86f82015-11-03 03:13:11 +00001584 // They can be replaced if they nominate the same namespace.
1585 // FIXME: Is this true even if they have different module visibility?
Richard Smithe8292b12015-02-10 03:28:10 +00001586 if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1587 return UD->getNominatedNamespace()->getOriginalNamespace() ==
1588 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1589 ->getOriginalNamespace();
Richard Smithbaf3ca52014-03-17 21:46:03 +00001590
Richard Smith5cd86f82015-11-03 03:13:11 +00001591 if (isRedeclarable(getKind())) {
1592 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1593 return false;
1594
1595 if (IsKnownNewer)
1596 return true;
1597
Richard Smithe8292b12015-02-10 03:28:10 +00001598 // Check whether this is actually newer than OldD. We want to keep the
1599 // newer declaration. This loop will usually only iterate once, because
1600 // OldD is usually the previous declaration.
1601 for (auto D : redecls()) {
1602 if (D == OldD)
1603 break;
1604
1605 // If we reach the canonical declaration, then OldD is not actually older
1606 // than this one.
1607 //
1608 // FIXME: In this case, we should not add this decl to the lookup table.
1609 if (D->isCanonicalDecl())
1610 return false;
1611 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001612
1613 // It's a newer declaration of the same kind of declaration in the same
1614 // scope: we want this decl instead of the existing one.
1615 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001616 }
1617
Richard Smith5cd86f82015-11-03 03:13:11 +00001618 // In all other cases, we need to keep both declarations in case they have
1619 // different visibility. Any attempt to use the name will result in an
1620 // ambiguity if more than one is visible.
1621 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001622}
1623
Douglas Gregoreddf4332009-02-24 20:03:32 +00001624bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001625 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001626}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001627
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001628NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001629 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001630 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001631 ND = UD->getTargetDecl();
1632
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001633 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001634 return AD->getClassInterface();
1635
Richard Smithf2005d32015-12-29 23:34:32 +00001636 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1637 return AD->getNamespace();
1638
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001639 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001640}
1641
John McCalla8ae2222010-04-06 21:38:20 +00001642bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001643 if (!isCXXClassMember())
1644 return false;
1645
John McCalla8ae2222010-04-06 21:38:20 +00001646 const NamedDecl *D = this;
1647 if (isa<UsingShadowDecl>(D))
1648 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1649
John McCall5e77d762013-04-16 07:28:30 +00001650 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001651 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001652 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001653 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001654 return false;
1655}
1656
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001657//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001658// DeclaratorDecl Implementation
1659//===----------------------------------------------------------------------===//
1660
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001661template <typename DeclT>
1662static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1663 if (decl->getNumTemplateParameterLists() > 0)
1664 return decl->getTemplateParameterList(0)->getTemplateLoc();
1665 else
1666 return decl->getInnerLocStart();
1667}
1668
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001669SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001670 TypeSourceInfo *TSI = getTypeSourceInfo();
1671 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001672 return SourceLocation();
1673}
1674
Douglas Gregor14454802011-02-25 02:25:35 +00001675void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1676 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001677 // Make sure the extended decl info is allocated.
1678 if (!hasExtInfo()) {
1679 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001680 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001681 // Allocate external info struct.
1682 DeclInfo = new (getASTContext()) ExtInfo;
1683 // Restore savedTInfo into (extended) decl info.
1684 getExtInfo()->TInfo = savedTInfo;
1685 }
1686 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001687 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001688 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001689 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001690 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001691 if (getExtInfo()->NumTemplParamLists == 0) {
1692 // Save type source info pointer.
1693 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1694 // Deallocate the extended decl info.
1695 getASTContext().Deallocate(getExtInfo());
1696 // Restore savedTInfo into (non-extended) decl info.
1697 DeclInfo = savedTInfo;
1698 }
1699 else
1700 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001701 }
1702 }
1703}
1704
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001705void DeclaratorDecl::setTemplateParameterListsInfo(
1706 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1707 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001708 // Make sure the extended decl info is allocated.
1709 if (!hasExtInfo()) {
1710 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001711 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001712 // Allocate external info struct.
1713 DeclInfo = new (getASTContext()) ExtInfo;
1714 // Restore savedTInfo into (extended) decl info.
1715 getExtInfo()->TInfo = savedTInfo;
1716 }
1717 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001718 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001719}
1720
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001721SourceLocation DeclaratorDecl::getOuterLocStart() const {
1722 return getTemplateOrInnerLocStart(this);
1723}
1724
Abramo Bagnaraea947882011-03-08 16:41:52 +00001725namespace {
1726
1727// Helper function: returns true if QT is or contains a type
1728// having a postfix component.
1729bool typeIsPostfix(clang::QualType QT) {
1730 while (true) {
1731 const Type* T = QT.getTypePtr();
1732 switch (T->getTypeClass()) {
1733 default:
1734 return false;
1735 case Type::Pointer:
1736 QT = cast<PointerType>(T)->getPointeeType();
1737 break;
1738 case Type::BlockPointer:
1739 QT = cast<BlockPointerType>(T)->getPointeeType();
1740 break;
1741 case Type::MemberPointer:
1742 QT = cast<MemberPointerType>(T)->getPointeeType();
1743 break;
1744 case Type::LValueReference:
1745 case Type::RValueReference:
1746 QT = cast<ReferenceType>(T)->getPointeeType();
1747 break;
1748 case Type::PackExpansion:
1749 QT = cast<PackExpansionType>(T)->getPattern();
1750 break;
1751 case Type::Paren:
1752 case Type::ConstantArray:
1753 case Type::DependentSizedArray:
1754 case Type::IncompleteArray:
1755 case Type::VariableArray:
1756 case Type::FunctionProto:
1757 case Type::FunctionNoProto:
1758 return true;
1759 }
1760 }
1761}
1762
1763} // namespace
1764
1765SourceRange DeclaratorDecl::getSourceRange() const {
1766 SourceLocation RangeEnd = getLocation();
1767 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001768 // If the declaration has no name or the type extends past the name take the
1769 // end location of the type.
1770 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001771 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1772 }
1773 return SourceRange(getOuterLocStart(), RangeEnd);
1774}
1775
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001776void QualifierInfo::setTemplateParameterListsInfo(
1777 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001778 // Free previous template parameters (if any).
1779 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001780 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001781 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001782 NumTemplParamLists = 0;
1783 }
1784 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001785 if (!TPLists.empty()) {
1786 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1787 NumTemplParamLists = TPLists.size();
1788 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001789 }
1790}
1791
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001792//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001793// VarDecl Implementation
1794//===----------------------------------------------------------------------===//
1795
Sebastian Redl833ef452010-01-26 22:01:41 +00001796const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1797 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001798 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001799 case SC_Auto: return "auto";
1800 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001801 case SC_PrivateExtern: return "__private_extern__";
1802 case SC_Register: return "register";
1803 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001804 }
1805
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001806 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001807}
1808
Richard Smith053f6c62014-05-16 23:01:30 +00001809VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1810 SourceLocation StartLoc, SourceLocation IdLoc,
1811 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1812 StorageClass SC)
1813 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1814 redeclarable_base(C), Init() {
Benjamin Kramera939c232014-03-15 18:54:13 +00001815 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1816 "VarDeclBitfields too large!");
1817 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1818 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001819 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1820 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001821 AllBits = 0;
1822 VarDeclBits.SClass = SC;
1823 // Everything else is implicitly initialized to false.
1824}
1825
Abramo Bagnaradff19302011-03-08 08:55:46 +00001826VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1827 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001828 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001829 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001830 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001831}
1832
Douglas Gregor72172e92012-01-05 21:55:30 +00001833VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001834 return new (C, ID)
1835 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1836 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001837}
1838
Douglas Gregorbf62d642010-12-06 18:36:25 +00001839void VarDecl::setStorageClass(StorageClass SC) {
1840 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001841 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001842}
1843
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001844VarDecl::TLSKind VarDecl::getTLSKind() const {
1845 switch (VarDeclBits.TSCSpec) {
1846 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001847 if (!hasAttr<ThreadAttr>() &&
1848 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1849 getASTContext().getTargetInfo().isTLSSupported() &&
1850 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001851 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001852 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1853 LangOptions::MSVC2015)) ||
1854 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001855 ? TLS_Dynamic
1856 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001857 case TSCS___thread: // Fall through.
1858 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001859 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001860 case TSCS_thread_local:
1861 return TLS_Dynamic;
1862 }
1863 llvm_unreachable("Unknown thread storage class specifier!");
1864}
1865
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001866SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001867 if (const Expr *Init = getInit()) {
1868 SourceLocation InitEnd = Init->getLocEnd();
Nico Weberbbe13942013-01-22 17:00:09 +00001869 // If Init is implicit, ignore its source range and fallback on
1870 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1871 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001872 return SourceRange(getOuterLocStart(), InitEnd);
1873 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001874 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001875}
1876
Rafael Espindola88510672013-01-04 21:18:45 +00001877template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001878static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001879 // C++ [dcl.link]p1: All function types, function names with external linkage,
1880 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001881 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001882 return NoLanguageLinkage;
1883
1884 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001885 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001886 ASTContext &Context = D.getASTContext();
1887 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001888 return CLanguageLinkage;
1889
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001890 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1891 // language linkage of the names of class members and the function type of
1892 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001893 const DeclContext *DC = D.getDeclContext();
1894 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001895 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001896
1897 // If the first decl is in an extern "C" context, any other redeclaration
1898 // will have C language linkage. If the first one is not in an extern "C"
1899 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001900 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001901 return CLanguageLinkage;
1902 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001903}
1904
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001905template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001906static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001907 // Since the context is ignored for class members, they can only have C++
1908 // language linkage or no language linkage.
1909 const DeclContext *DC = D.getDeclContext();
1910 if (DC->isRecord()) {
1911 assert(D.getASTContext().getLangOpts().CPlusPlus);
1912 return false;
1913 }
1914
1915 return D.getLanguageLinkage() == CLanguageLinkage;
1916}
1917
Rafael Espindolaf4187652013-02-14 01:18:37 +00001918LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00001919 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00001920}
1921
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001922bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00001923 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001924}
1925
Rafael Espindola593537a2013-05-05 20:15:21 +00001926bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001927 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001928}
1929
1930bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00001931 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00001932}
1933
Rafael Espindola8db352d2013-10-17 15:37:26 +00001934VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00001935
Nico Weber7f5015a2015-04-15 21:53:00 +00001936VarDecl::DefinitionKind
1937VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001938 // C++ [basic.def]p2:
1939 // A declaration is a definition unless [...] it contains the 'extern'
1940 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00001941 // it declares a non-inline static data member in a class declaration [...],
1942 // it declares a static data member outside a class definition and the variable
1943 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00001944 // C++1y [temp.expl.spec]p15:
1945 // An explicit specialization of a static data member or an explicit
1946 // specialization of a static data member template is a definition if the
1947 // declaration includes an initializer; otherwise, it is a declaration.
1948 //
1949 // FIXME: How do you declare (but not define) a partial specialization of
1950 // a static data member template outside the containing class?
Richard Smithedbc6e92016-10-14 21:41:24 +00001951 if (isThisDeclarationADemotedDefinition())
1952 return DeclarationOnly;
1953
Sebastian Redl35351a92010-01-31 22:27:38 +00001954 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00001955 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00001956 !(getCanonicalDecl()->isInline() &&
1957 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00001958 (hasInit() ||
1959 // If the first declaration is out-of-line, this may be an
1960 // instantiation of an out-of-line partial specialization of a variable
1961 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001962 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00001963 ? getTemplateSpecializationKind() == TSK_Undeclared
1964 : getTemplateSpecializationKind() !=
1965 TSK_ExplicitSpecialization) ||
1966 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00001967 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00001968 else if (!isOutOfLine() && isInline())
1969 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00001970 else
1971 return DeclarationOnly;
1972 }
1973 // C99 6.7p5:
1974 // A definition of an identifier is a declaration for that identifier that
1975 // [...] causes storage to be reserved for that object.
1976 // Note: that applies for all non-file-scope objects.
1977 // C99 6.9.2p1:
1978 // If the declaration of an identifier for an object has file scope and an
1979 // initializer, the declaration is an external definition for the identifier
1980 if (hasInit())
1981 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00001982
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001983 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00001984 return Definition;
1985
David Majnemerdd0bed12015-05-14 05:19:20 +00001986 if (const auto *SAA = getAttr<SelectAnyAttr>())
1987 if (!SAA->isInherited())
1988 return Definition;
1989
Richard Smith8809a0c2013-09-27 20:14:12 +00001990 // A variable template specialization (other than a static data member
1991 // template or an explicit specialization) is a declaration until we
1992 // instantiate its initializer.
1993 if (isa<VarTemplateSpecializationDecl>(this) &&
1994 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1995 return DeclarationOnly;
1996
Nico Weber608e7682015-04-15 23:04:24 +00001997 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00001998 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00001999
Rafael Espindolabff59562013-04-25 12:11:36 +00002000 // [dcl.link] p7:
2001 // A declaration directly contained in a linkage-specification is treated
2002 // as if it contains the extern specifier for the purpose of determining
2003 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002004 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002005 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002006
Sebastian Redl35351a92010-01-31 22:27:38 +00002007 // C99 6.9.2p2:
2008 // A declaration of an object that has file scope without an initializer,
2009 // and without a storage class specifier or the scs 'static', constitutes
2010 // a tentative definition.
2011 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002012 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002013 return TentativeDefinition;
2014
2015 // What's left is (in C, block-scope) declarations without initializers or
2016 // external storage. These are definitions.
2017 return Definition;
2018}
2019
Sebastian Redl35351a92010-01-31 22:27:38 +00002020VarDecl *VarDecl::getActingDefinition() {
2021 DefinitionKind Kind = isThisDeclarationADefinition();
2022 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002023 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002024
Craig Topper36250ad2014-05-12 05:36:57 +00002025 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002026 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002027 for (auto I : First->redecls()) {
2028 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002029 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002030 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002031 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002032 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002033 }
2034 return LastTentative;
2035}
2036
Daniel Dunbar9d355812012-03-09 01:51:51 +00002037VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002038 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002039 for (auto I : First->redecls()) {
2040 if (I->isThisDeclarationADefinition(C) == Definition)
2041 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002042 }
Craig Topper36250ad2014-05-12 05:36:57 +00002043 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002044}
2045
Daniel Dunbar9d355812012-03-09 01:51:51 +00002046VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002047 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002048
Rafael Espindola8db352d2013-10-17 15:37:26 +00002049 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002050 for (auto I : First->redecls()) {
2051 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002052 if (Kind == Definition)
2053 break;
2054 }
John McCall37bb6c92010-10-29 22:22:43 +00002055
2056 return Kind;
2057}
2058
Sebastian Redl5ca79842010-02-01 20:16:42 +00002059const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002060 for (auto I : redecls()) {
2061 if (auto Expr = I->getInit()) {
2062 D = I;
2063 return Expr;
2064 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002065 }
Craig Topper36250ad2014-05-12 05:36:57 +00002066 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002067}
2068
Chandler Carruth813faed2015-12-30 02:51:00 +00002069bool VarDecl::hasInit() const {
2070 if (auto *P = dyn_cast<ParmVarDecl>(this))
2071 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2072 return false;
2073
2074 return !Init.isNull();
2075}
2076
2077Expr *VarDecl::getInit() {
2078 if (!hasInit())
2079 return nullptr;
2080
2081 if (auto *S = Init.dyn_cast<Stmt *>())
2082 return cast<Expr>(S);
2083
2084 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2085}
2086
2087Stmt **VarDecl::getInitAddress() {
2088 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2089 return &ES->Value;
2090
2091 return Init.getAddrOfPtr1();
2092}
2093
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002094bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002095 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002096 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002097
2098 if (!isStaticDataMember())
2099 return false;
2100
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002101 // If this static data member was instantiated from a static data member of
2102 // a class template, check whether that static data member was defined
2103 // out-of-line.
2104 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2105 return VD->isOutOfLine();
2106
2107 return false;
2108}
2109
Douglas Gregord5058122010-02-11 01:19:42 +00002110void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002111 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002112 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002113 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002114 }
2115
2116 Init = I;
2117}
2118
Daniel Dunbar9d355812012-03-09 01:51:51 +00002119bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002120 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002121
Richard Smith35ecb362012-03-02 04:14:40 +00002122 if (!Lang.CPlusPlus)
2123 return false;
2124
2125 // In C++11, any variable of reference type can be used in a constant
2126 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002127 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002128 return true;
2129
2130 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002131 // not require the variable to be non-volatile, but we consider this to be a
2132 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002133 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002134 return false;
2135
2136 // In C++, const, non-volatile variables of integral or enumeration types
2137 // can be used in constant expressions.
2138 if (getType()->isIntegralOrEnumerationType())
2139 return true;
2140
Richard Smith35ecb362012-03-02 04:14:40 +00002141 // Additionally, in C++11, non-volatile constexpr variables can be used in
2142 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002143 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002144}
2145
Richard Smithd0b4dd62011-12-19 06:19:21 +00002146/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2147/// form, which contains extra information on the evaluated value of the
2148/// initializer.
2149EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002150 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002151 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002152 // Note: EvaluatedStmt contains an APValue, which usually holds
2153 // resources not allocated from the ASTContext. We need to do some
2154 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2155 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002156 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002157 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002158 Init = Eval;
2159 }
2160 return Eval;
2161}
2162
Richard Smithdafff942012-01-14 04:30:29 +00002163APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002164 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002165 return evaluateValue(Notes);
2166}
2167
2168APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002169 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002170 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2171
2172 // We only produce notes indicating why an initializer is non-constant the
2173 // first time it is evaluated. FIXME: The notes won't always be emitted the
2174 // first time we try evaluation, so might not be produced at all.
2175 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002176 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002177
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002178 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002179 assert(!Init->isValueDependent());
2180
2181 if (Eval->IsEvaluating) {
2182 // FIXME: Produce a diagnostic for self-initialization.
2183 Eval->CheckedICE = true;
2184 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002185 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002186 }
2187
2188 Eval->IsEvaluating = true;
2189
2190 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2191 this, Notes);
2192
Manuel Klimeka7328992013-06-03 13:51:33 +00002193 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2194 // or that it's empty (so that there's nothing to clean up) if evaluation
2195 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002196 if (!Result)
2197 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002198 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002199 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002200
2201 Eval->IsEvaluating = false;
2202 Eval->WasEvaluated = true;
2203
2204 // In C++11, we have determined whether the initializer was a constant
2205 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002206 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002207 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002208 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002209 }
2210
Craig Topper36250ad2014-05-12 05:36:57 +00002211 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002212}
2213
Chandler Carruth813faed2015-12-30 02:51:00 +00002214APValue *VarDecl::getEvaluatedValue() const {
2215 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2216 if (Eval->WasEvaluated)
2217 return &Eval->Evaluated;
2218
2219 return nullptr;
2220}
2221
2222bool VarDecl::isInitKnownICE() const {
2223 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2224 return Eval->CheckedICE;
2225
2226 return false;
2227}
2228
2229bool VarDecl::isInitICE() const {
2230 assert(isInitKnownICE() &&
2231 "Check whether we already know that the initializer is an ICE");
2232 return Init.get<EvaluatedStmt *>()->IsICE;
2233}
2234
Richard Smithd0b4dd62011-12-19 06:19:21 +00002235bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002236 // Initializers of weak variables are never ICEs.
2237 if (isWeak())
2238 return false;
2239
Richard Smithd0b4dd62011-12-19 06:19:21 +00002240 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2241 if (Eval->CheckedICE)
2242 // We have already checked whether this subexpression is an
2243 // integral constant expression.
2244 return Eval->IsICE;
2245
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002246 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002247 assert(!Init->isValueDependent());
2248
2249 // In C++11, evaluate the initializer to check whether it's a constant
2250 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002251 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002252 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002253 evaluateValue(Notes);
2254 return Eval->IsICE;
2255 }
2256
2257 // It's an ICE whether or not the definition we found is
2258 // out-of-line. See DR 721 and the discussion in Clang PR
2259 // 6206 for details.
2260
2261 if (Eval->CheckingICE)
2262 return false;
2263 Eval->CheckingICE = true;
2264
2265 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2266 Eval->CheckingICE = false;
2267 Eval->CheckedICE = true;
2268 return Eval->IsICE;
2269}
2270
Richard Smith2195ec92017-04-21 01:15:13 +00002271template<typename DeclT>
2272static DeclT *getDefinitionOrSelf(DeclT *D) {
2273 assert(D);
2274 if (auto *Def = D->getDefinition())
2275 return Def;
2276 return D;
2277}
2278
Richard Smithedbc6e92016-10-14 21:41:24 +00002279VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2280 // If it's a variable template specialization, find the template or partial
2281 // specialization from which it was instantiated.
2282 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2283 auto From = VDTemplSpec->getInstantiatedFrom();
2284 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2285 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2286 if (NewVTD->isMemberSpecialization())
2287 break;
2288 VTD = NewVTD;
2289 }
Richard Smith2195ec92017-04-21 01:15:13 +00002290 return getDefinitionOrSelf(VTD->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002291 }
2292 if (auto *VTPSD =
2293 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2294 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2295 if (NewVTPSD->isMemberSpecialization())
2296 break;
2297 VTPSD = NewVTPSD;
2298 }
Richard Smith2195ec92017-04-21 01:15:13 +00002299 return getDefinitionOrSelf<VarDecl>(VTPSD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002300 }
2301 }
2302
2303 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2304 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2305 VarDecl *VD = getInstantiatedFromStaticDataMember();
2306 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2307 VD = NewVD;
Richard Smith2195ec92017-04-21 01:15:13 +00002308 return getDefinitionOrSelf(VD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002309 }
2310 }
2311
2312 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002313 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2314 if (VarTemplate->isMemberSpecialization())
2315 break;
2316 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2317 }
2318
Richard Smith2195ec92017-04-21 01:15:13 +00002319 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002320 }
2321 return nullptr;
2322}
2323
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002324VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002325 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002326 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002327
2328 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002329}
2330
Douglas Gregor3c74d412009-10-14 20:14:33 +00002331TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002332 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002333 return Spec->getSpecializationKind();
2334
Sebastian Redl35351a92010-01-31 22:27:38 +00002335 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002336 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002337
Douglas Gregor86d142a2009-10-08 07:24:58 +00002338 return TSK_Undeclared;
2339}
2340
Richard Smith8809a0c2013-09-27 20:14:12 +00002341SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002342 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002343 return Spec->getPointOfInstantiation();
2344
2345 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2346 return MSI->getPointOfInstantiation();
2347
2348 return SourceLocation();
2349}
2350
Larisse Voufo39a1e502013-08-06 01:03:05 +00002351VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2352 return getASTContext().getTemplateOrSpecializationInfo(this)
2353 .dyn_cast<VarTemplateDecl *>();
2354}
2355
2356void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2357 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2358}
2359
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002360MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002361 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002362 // FIXME: Remove ?
2363 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2364 return getASTContext().getTemplateOrSpecializationInfo(this)
2365 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002366 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002367}
2368
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002369void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2370 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002371 assert((isa<VarTemplateSpecializationDecl>(this) ||
2372 getMemberSpecializationInfo()) &&
2373 "not a variable or static data member template specialization");
2374
Larisse Voufo39a1e502013-08-06 01:03:05 +00002375 if (VarTemplateSpecializationDecl *Spec =
2376 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2377 Spec->setSpecializationKind(TSK);
2378 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2379 Spec->getPointOfInstantiation().isInvalid())
2380 Spec->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002381 }
2382
2383 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2384 MSI->setTemplateSpecializationKind(TSK);
2385 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2386 MSI->getPointOfInstantiation().isInvalid())
2387 MSI->setPointOfInstantiation(PointOfInstantiation);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002388 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002389}
2390
2391void
2392VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2393 TemplateSpecializationKind TSK) {
2394 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2395 "Previous template or instantiation?");
2396 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002397}
2398
Sebastian Redl833ef452010-01-26 22:01:41 +00002399//===----------------------------------------------------------------------===//
2400// ParmVarDecl Implementation
2401//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002402
Sebastian Redl833ef452010-01-26 22:01:41 +00002403ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002404 SourceLocation StartLoc,
2405 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002406 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002407 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002408 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002409 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002410}
2411
Reid Kleckner8a365022013-06-24 17:51:48 +00002412QualType ParmVarDecl::getOriginalType() const {
2413 TypeSourceInfo *TSI = getTypeSourceInfo();
2414 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002415 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002416 return DT->getOriginalType();
2417 return T;
2418}
2419
Douglas Gregor72172e92012-01-05 21:55:30 +00002420ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002421 return new (C, ID)
2422 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2423 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002424}
2425
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002426SourceRange ParmVarDecl::getSourceRange() const {
2427 if (!hasInheritedDefaultArg()) {
2428 SourceRange ArgRange = getDefaultArgRange();
2429 if (ArgRange.isValid())
2430 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2431 }
2432
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002433 // DeclaratorDecl considers the range of postfix types as overlapping with the
2434 // declaration name, but this is not the case with parameters in ObjC methods.
2435 if (isa<ObjCMethodDecl>(getDeclContext()))
2436 return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2437
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002438 return DeclaratorDecl::getSourceRange();
2439}
2440
Sebastian Redl833ef452010-01-26 22:01:41 +00002441Expr *ParmVarDecl::getDefaultArg() {
2442 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2443 assert(!hasUninstantiatedDefaultArg() &&
2444 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002445
Sebastian Redl833ef452010-01-26 22:01:41 +00002446 Expr *Arg = getInit();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002447 if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002448 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002449
Sebastian Redl833ef452010-01-26 22:01:41 +00002450 return Arg;
2451}
2452
Chandler Carruth813faed2015-12-30 02:51:00 +00002453void ParmVarDecl::setDefaultArg(Expr *defarg) {
2454 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2455 Init = defarg;
2456}
Sebastian Redl833ef452010-01-26 22:01:41 +00002457
Chandler Carruth813faed2015-12-30 02:51:00 +00002458SourceRange ParmVarDecl::getDefaultArgRange() const {
2459 switch (ParmVarDeclBits.DefaultArgKind) {
2460 case DAK_None:
2461 case DAK_Unparsed:
2462 // Nothing we can do here.
2463 return SourceRange();
2464
2465 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002466 return getUninstantiatedDefaultArg()->getSourceRange();
2467
Chandler Carruth813faed2015-12-30 02:51:00 +00002468 case DAK_Normal:
2469 if (const Expr *E = getInit())
2470 return E->getSourceRange();
2471
2472 // Missing an actual expression, may be invalid.
2473 return SourceRange();
2474 }
2475 llvm_unreachable("Invalid default argument kind.");
2476}
2477
2478void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2479 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2480 Init = arg;
2481}
2482
2483Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2484 assert(hasUninstantiatedDefaultArg() &&
2485 "Wrong kind of initialization expression!");
2486 return cast_or_null<Expr>(Init.get<Stmt *>());
2487}
2488
2489bool ParmVarDecl::hasDefaultArg() const {
2490 // FIXME: We should just return false for DAK_None here once callers are
2491 // prepared for the case that we encountered an invalid default argument and
2492 // were unable to even build an invalid expression.
2493 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2494 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002495}
2496
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002497bool ParmVarDecl::isParameterPack() const {
2498 return isa<PackExpansionType>(getType());
2499}
2500
Ted Kremenek540017e2011-10-06 05:00:56 +00002501void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2502 getASTContext().setParameterIndex(this, parameterIndex);
2503 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2504}
2505
2506unsigned ParmVarDecl::getParameterIndexLarge() const {
2507 return getASTContext().getParameterIndex(this);
2508}
2509
Nuno Lopes394ec982008-12-17 23:39:55 +00002510//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002511// FunctionDecl Implementation
2512//===----------------------------------------------------------------------===//
2513
Benjamin Kramer9170e912013-02-22 15:46:01 +00002514void FunctionDecl::getNameForDiagnostic(
2515 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2516 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002517 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2518 if (TemplateArgs)
Benjamin Kramer9170e912013-02-22 15:46:01 +00002519 TemplateSpecializationType::PrintTemplateArgumentList(
David Majnemer6fbeee32016-07-07 04:43:07 +00002520 OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002521}
2522
Ted Kremenek186a0742010-04-29 16:49:01 +00002523bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002524 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002525 return FT->isVariadic();
2526 return false;
2527}
2528
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002529bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002530 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002531 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002532 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002533 return true;
2534 }
2535 }
2536
2537 return false;
2538}
2539
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002540bool FunctionDecl::hasTrivialBody() const
2541{
2542 Stmt *S = getBody();
2543 if (!S) {
2544 // Since we don't have a body for this function, we don't know if it's
2545 // trivial or not.
2546 return false;
2547 }
2548
2549 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2550 return true;
2551 return false;
2552}
2553
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002554bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002555 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002556 if (I->isThisDeclarationADefinition()) {
2557 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002558 return true;
2559 }
2560 }
2561
2562 return false;
2563}
2564
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002565Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002566 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002567 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002568
2569 if (Definition->Body)
2570 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002571
Craig Topper36250ad2014-05-12 05:36:57 +00002572 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002573}
2574
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002575void FunctionDecl::setBody(Stmt *B) {
2576 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002577 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002578 EndRangeLoc = B->getLocEnd();
2579}
2580
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002581void FunctionDecl::setPure(bool P) {
2582 IsPure = P;
2583 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002584 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002585 Parent->markedVirtualFunctionPure();
2586}
2587
Richard Smith8d0dc312013-07-21 23:12:18 +00002588template<std::size_t Len>
2589static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2590 IdentifierInfo *II = ND->getIdentifier();
2591 return II && II->isStr(Str);
2592}
2593
Douglas Gregor16618f22009-09-12 00:17:51 +00002594bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002595 const TranslationUnitDecl *tunit =
2596 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2597 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002598 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002599 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002600}
2601
David Majnemerc729b0b2013-09-16 22:44:20 +00002602bool FunctionDecl::isMSVCRTEntryPoint() const {
2603 const TranslationUnitDecl *TUnit =
2604 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2605 if (!TUnit)
2606 return false;
2607
2608 // Even though we aren't really targeting MSVCRT if we are freestanding,
2609 // semantic analysis for these functions remains the same.
2610
2611 // MSVCRT entry points only exist on MSVCRT targets.
2612 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2613 return false;
2614
2615 // Nameless functions like constructors cannot be entry points.
2616 if (!getIdentifier())
2617 return false;
2618
2619 return llvm::StringSwitch<bool>(getName())
2620 .Cases("main", // an ANSI console app
2621 "wmain", // a Unicode console App
2622 "WinMain", // an ANSI GUI app
2623 "wWinMain", // a Unicode GUI app
2624 "DllMain", // a DLL
2625 true)
2626 .Default(false);
2627}
2628
John McCall53ffd372011-05-15 17:49:20 +00002629bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2630 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2631 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2632 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2633 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2634 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2635
Richard Smithf6004412014-01-19 23:25:37 +00002636 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2637 return false;
John McCall53ffd372011-05-15 17:49:20 +00002638
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002639 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002640 if (proto->getNumParams() != 2 || proto->isVariadic())
2641 return false;
John McCall53ffd372011-05-15 17:49:20 +00002642
2643 ASTContext &Context =
2644 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2645 ->getASTContext();
2646
2647 // The result type and first argument type are constant across all
2648 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002649 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002650}
2651
Akira Hatanakacae83f72017-06-29 18:48:40 +00002652bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002653 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2654 return false;
2655 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2656 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2657 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2658 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2659 return false;
2660
2661 if (isa<CXXRecordDecl>(getDeclContext()))
2662 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002663
2664 // This can only fail for an invalid 'operator new' declaration.
2665 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2666 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002667
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002668 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002669 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002670 return false;
2671
2672 // If this is a single-parameter function, it must be a replaceable global
2673 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002674 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002675 return true;
2676
Richard Smithb2f0f052016-10-10 18:54:32 +00002677 unsigned Params = 1;
2678 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002679 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002680
2681 auto Consume = [&] {
2682 ++Params;
2683 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2684 };
2685
2686 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2687 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002688 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002689 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2690 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2691 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2692 IsSizedDelete = true;
2693 Consume();
2694 }
2695
2696 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2697 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002698 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2699 if (IsAligned)
2700 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002701 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002702 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002703
2704 // Finally, if this is not a sized delete, the final parameter can
2705 // be a 'const std::nothrow_t&'.
2706 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2707 Ty = Ty->getPointeeType();
2708 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2709 return false;
2710 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2711 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2712 Consume();
2713 }
2714
2715 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002716}
2717
Rafael Espindolaf4187652013-02-14 01:18:37 +00002718LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002719 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002720}
2721
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002722bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002723 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002724}
2725
Rafael Espindola593537a2013-05-05 20:15:21 +00002726bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002727 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002728}
2729
2730bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002731 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002732}
2733
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002734bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002735 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002736 return Method->isStatic();
2737
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002738 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002739 return false;
2740
Mike Stump11289f42009-09-09 15:08:12 +00002741 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002742 DC->isNamespace();
2743 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002744 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002745 if (!Namespace->getDeclName())
2746 return false;
2747 break;
2748 }
2749 }
2750
2751 return true;
2752}
2753
Richard Smith10876ef2013-01-17 01:30:42 +00002754bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002755 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2756 hasAttr<C11NoReturnAttr>())
2757 return true;
2758
2759 if (auto *FnTy = getType()->getAs<FunctionType>())
2760 return FnTy->getNoReturnAttr();
2761
2762 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002763}
2764
Sebastian Redl833ef452010-01-26 22:01:41 +00002765void
2766FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002767 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002768
2769 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2770 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002771 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002772 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002773 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002774 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00002775
Axel Naumannfbc7b982011-11-08 18:21:06 +00002776 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00002777 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00002778}
2779
Rafael Espindola8db352d2013-10-17 15:37:26 +00002780FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002781
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002782/// \brief Returns a value indicating whether this function
2783/// corresponds to a builtin function.
2784///
2785/// The function corresponds to a built-in function if it is
2786/// declared at translation scope or within an extern "C" block and
2787/// its name matches with the name of a builtin. The returned value
2788/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002789/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002790/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002791unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002792 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002793 return 0;
2794
2795 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002796 if (!BuiltinID)
2797 return 0;
2798
2799 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00002800 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002801 const auto *LinkageDecl =
2802 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00002803 // In C++, the first declaration of a builtin is always inside an implicit
2804 // extern "C".
2805 // FIXME: A recognised library function may not be directly in an extern "C"
2806 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00002807 if (!LinkageDecl) {
2808 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00002809 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00002810 return Builtin::BI__GetExceptionInfo;
2811 return 0;
2812 }
2813 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00002814 return 0;
2815 }
2816
2817 // If the function is marked "overloadable", it has a different mangled name
2818 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002819 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00002820 return 0;
2821
Douglas Gregore711f702009-02-14 18:57:46 +00002822 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2823 return BuiltinID;
2824
2825 // This function has the name of a known C library
2826 // function. Determine whether it actually refers to the C library
2827 // function or whether it just has the same name.
2828
Douglas Gregora908e7f2009-02-17 03:23:10 +00002829 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00002830 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00002831 return 0;
2832
Anastasia Stulova1202de32016-02-12 12:07:04 +00002833 // OpenCL v1.2 s6.9.f - The library functions defined in
2834 // the C99 standard headers are not available.
2835 if (Context.getLangOpts().OpenCL &&
2836 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2837 return 0;
2838
Warren Hunt445d83e2013-11-01 23:46:51 +00002839 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002840}
2841
2842
Chris Lattner47c0d002009-04-25 06:03:53 +00002843/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00002844/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00002845/// after it has been created.
2846unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002847 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002848 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002849}
2850
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002851void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002852 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00002853 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00002854 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00002855
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002856 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002857 if (!NewParamInfo.empty()) {
2858 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2859 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00002860 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002861}
Chris Lattner41943152007-01-25 04:52:46 +00002862
Chris Lattner58258242008-04-10 02:22:51 +00002863/// getMinRequiredArguments - Returns the minimum number of arguments
2864/// needed to call this function. This may be fewer than the number of
2865/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00002866/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00002867unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002868 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00002869 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00002870
Richard Smith91151782014-04-01 19:18:16 +00002871 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00002872 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00002873 if (!Param->isParameterPack() && !Param->hasDefaultArg())
2874 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00002875 return NumRequiredArgs;
2876}
2877
David Majnemer54e3ba52014-04-02 23:17:29 +00002878/// \brief The combination of the extern and inline keywords under MSVC forces
2879/// the function to be required.
2880///
2881/// Note: This function assumes that we will only get called when isInlined()
2882/// would return true for this FunctionDecl.
2883bool FunctionDecl::isMSExternInline() const {
2884 assert(isInlined() && "expected to get called on an inlined function!");
2885
2886 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00002887 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2888 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00002889 return false;
2890
David Majnemer73768702015-03-20 00:02:27 +00002891 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2892 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002893 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002894 return true;
2895
2896 return false;
2897}
2898
2899static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2900 if (Redecl->getStorageClass() != SC_Extern)
2901 return false;
2902
2903 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2904 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00002905 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00002906 return false;
2907
2908 return true;
2909}
2910
Eli Friedman1b125c32012-02-07 03:50:18 +00002911static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2912 // Only consider file-scope declarations in this test.
2913 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2914 return false;
2915
2916 // Only consider explicit declarations; the presence of a builtin for a
2917 // libcall shouldn't affect whether a definition is externally visible.
2918 if (Redecl->isImplicit())
2919 return false;
2920
2921 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2922 return true; // Not an inline definition
2923
2924 return false;
2925}
2926
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002927/// \brief For a function declaration in C or C++, determine whether this
2928/// declaration causes the definition to be externally visible.
2929///
David Majnemer54e3ba52014-04-02 23:17:29 +00002930/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00002931/// of redeclarations of the given functions causes
2932/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002933bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00002934 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002935 "Must have a declaration without a body.");
2936
2937 ASTContext &Context = getASTContext();
2938
David Majnemer54e3ba52014-04-02 23:17:29 +00002939 if (Context.getLangOpts().MSVCCompat) {
2940 const FunctionDecl *Definition;
2941 if (hasBody(Definition) && Definition->isInlined() &&
2942 redeclForcesDefMSVC(this))
2943 return true;
2944 }
2945
David Blaikiebbafb8a2012-03-11 07:00:24 +00002946 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002947 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2948 // an externally visible definition.
2949 //
2950 // FIXME: What happens if gnu_inline gets added on after the first
2951 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002952 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002953 return false;
2954
2955 const FunctionDecl *Prev = this;
2956 bool FoundBody = false;
2957 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002958 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002959
2960 if (Prev->Body) {
2961 // If it's not the case that both 'inline' and 'extern' are
2962 // specified on the definition, then it is always externally visible.
2963 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002964 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00002965 return false;
2966 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002967 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002968 return false;
2969 }
2970 }
2971 return FoundBody;
2972 }
2973
David Blaikiebbafb8a2012-03-11 07:00:24 +00002974 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002975 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002976
2977 // C99 6.7.4p6:
2978 // [...] If all of the file scope declarations for a function in a
2979 // translation unit include the inline function specifier without extern,
2980 // then the definition in that translation unit is an inline definition.
2981 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002982 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00002983 const FunctionDecl *Prev = this;
2984 bool FoundBody = false;
2985 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00002986 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00002987 if (RedeclForcesDefC99(Prev))
2988 return false;
2989 }
2990 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002991}
2992
Alp Tokerd0787eb2014-07-02 01:47:15 +00002993SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2994 const TypeSourceInfo *TSI = getTypeSourceInfo();
2995 if (!TSI)
2996 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00002997 FunctionTypeLoc FTL =
2998 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2999 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003000 return SourceRange();
3001
Alp Tokerf5b10792014-07-02 12:55:58 +00003002 // Skip self-referential return types.
3003 const SourceManager &SM = getASTContext().getSourceManager();
3004 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3005 SourceLocation Boundary = getNameInfo().getLocStart();
3006 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3007 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3008 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003009
Alp Tokerf5b10792014-07-02 12:55:58 +00003010 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003011}
3012
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003013SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3014 const TypeSourceInfo *TSI = getTypeSourceInfo();
3015 if (!TSI)
3016 return SourceRange();
3017 FunctionTypeLoc FTL =
3018 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3019 if (!FTL)
3020 return SourceRange();
3021
3022 return FTL.getExceptionSpecRange();
3023}
3024
Aaron Ballmane7964782016-03-07 22:44:55 +00003025const Attr *FunctionDecl::getUnusedResultAttr() const {
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003026 QualType RetType = getReturnType();
3027 if (RetType->isRecordType()) {
Erich Keane4b87d812017-04-19 21:24:55 +00003028 if (const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl()) {
Aaron Ballmane7964782016-03-07 22:44:55 +00003029 if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
3030 return R;
3031 }
3032 } else if (const auto *ET = RetType->getAs<EnumType>()) {
3033 if (const EnumDecl *ED = ET->getDecl()) {
3034 if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
3035 return R;
3036 }
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003037 }
Aaron Ballmane7964782016-03-07 22:44:55 +00003038 return getAttr<WarnUnusedResultAttr>();
Kaelyn Takata0a2e84c2015-04-09 19:43:04 +00003039}
3040
Richard Smithf3814ad2013-01-25 00:08:28 +00003041/// \brief For an inline function definition in C, or for a gnu_inline function
3042/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003043///
3044/// Inline function definitions are always available for inlining optimizations.
3045/// However, depending on the language dialect, declaration specifiers, and
3046/// attributes, the definition of an inline function may or may not be
3047/// "externally" visible to other translation units in the program.
3048///
3049/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003050/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003051/// inline definition becomes externally visible (C99 6.7.4p6).
3052///
3053/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3054/// definition, we use the GNU semantics for inline, which are nearly the
3055/// opposite of C99 semantics. In particular, "inline" by itself will create
3056/// an externally visible symbol, but "extern inline" will not create an
3057/// externally visible symbol.
3058bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Manuel Klimekda7456a2016-11-01 10:30:50 +00003059 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3060 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003061 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003062 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00003063
David Blaikiebbafb8a2012-03-11 07:00:24 +00003064 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003065 // Note: If you change the logic here, please change
3066 // doesDeclarationForceExternallyVisibleDefinition as well.
3067 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003068 // If it's not the case that both 'inline' and 'extern' are
3069 // specified on the definition, then this inline definition is
3070 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003071 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003072 return true;
3073
3074 // If any declaration is 'inline' but not 'extern', then this definition
3075 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003076 for (auto Redecl : redecls()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00003077 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003078 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003079 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00003080 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00003081
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003082 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003083 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003084
Richard Smithf3814ad2013-01-25 00:08:28 +00003085 // The rest of this function is C-only.
3086 assert(!Context.getLangOpts().CPlusPlus &&
3087 "should not use C inline rules in C++");
3088
Douglas Gregor299d76e2009-09-13 07:46:26 +00003089 // C99 6.7.4p6:
3090 // [...] If all of the file scope declarations for a function in a
3091 // translation unit include the inline function specifier without extern,
3092 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003093 for (auto Redecl : redecls()) {
3094 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003095 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003096 }
3097
3098 // C99 6.7.4p6:
3099 // An inline definition does not provide an external definition for the
3100 // function, and does not forbid an external definition in another
3101 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003102 return false;
3103}
3104
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003105/// getOverloadedOperator - Which C++ overloaded operator this
3106/// function represents, if any.
3107OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003108 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3109 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003110 else
3111 return OO_None;
3112}
3113
Alexis Huntc88db062010-01-13 09:01:02 +00003114/// getLiteralIdentifier - The literal suffix identifier this function
3115/// represents, if any.
3116const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3117 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3118 return getDeclName().getCXXLiteralIdentifier();
3119 else
Craig Topper36250ad2014-05-12 05:36:57 +00003120 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003121}
3122
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003123FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3124 if (TemplateOrSpecialization.isNull())
3125 return TK_NonTemplate;
3126 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3127 return TK_FunctionTemplate;
3128 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3129 return TK_MemberSpecialization;
3130 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3131 return TK_FunctionTemplateSpecialization;
3132 if (TemplateOrSpecialization.is
3133 <DependentFunctionTemplateSpecializationInfo*>())
3134 return TK_DependentFunctionTemplateSpecialization;
3135
David Blaikie83d382b2011-09-23 05:06:16 +00003136 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003137}
3138
Douglas Gregord801b062009-10-07 23:56:10 +00003139FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003140 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003141 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003142
3143 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003144}
3145
Chandler Carruth21c90602015-12-30 03:24:14 +00003146MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3147 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3148}
3149
Douglas Gregord801b062009-10-07 23:56:10 +00003150void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003151FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3152 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003153 TemplateSpecializationKind TSK) {
3154 assert(TemplateOrSpecialization.isNull() &&
3155 "Member function is already a specialization");
3156 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003157 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003158 TemplateOrSpecialization = Info;
3159}
3160
Chandler Carruth21c90602015-12-30 03:24:14 +00003161FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3162 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3163}
3164
3165void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3166 TemplateOrSpecialization = Template;
3167}
3168
Douglas Gregorafca3b42009-10-27 20:53:28 +00003169bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003170 // If the function is invalid, it can't be implicitly instantiated.
3171 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003172 return false;
3173
3174 switch (getTemplateSpecializationKind()) {
3175 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003176 case TSK_ExplicitInstantiationDefinition:
3177 return false;
3178
3179 case TSK_ImplicitInstantiation:
3180 return true;
3181
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003182 // It is possible to instantiate TSK_ExplicitSpecialization kind
3183 // if the FunctionDecl has a class scope specialization pattern.
3184 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003185 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003186
Douglas Gregorafca3b42009-10-27 20:53:28 +00003187 case TSK_ExplicitInstantiationDeclaration:
3188 // Handled below.
3189 break;
3190 }
3191
3192 // Find the actual template from which we will instantiate.
3193 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003194 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003195 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003196 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00003197
3198 // C++0x [temp.explicit]p9:
3199 // Except for inline functions, other explicit instantiation declarations
3200 // have the effect of suppressing the implicit instantiation of the entity
3201 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003202 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003203 return true;
3204
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003205 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003206}
3207
3208bool FunctionDecl::isTemplateInstantiation() const {
3209 switch (getTemplateSpecializationKind()) {
3210 case TSK_Undeclared:
3211 case TSK_ExplicitSpecialization:
3212 return false;
3213 case TSK_ImplicitInstantiation:
3214 case TSK_ExplicitInstantiationDeclaration:
3215 case TSK_ExplicitInstantiationDefinition:
3216 return true;
3217 }
3218 llvm_unreachable("All TSK values handled.");
3219}
Douglas Gregorafca3b42009-10-27 20:53:28 +00003220
3221FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003222 // Handle class scope explicit specialization special case.
Richard Smith2195ec92017-04-21 01:15:13 +00003223 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3224 if (auto *Spec = getClassScopeSpecializationPattern())
3225 return getDefinitionOrSelf(Spec);
3226 return nullptr;
3227 }
3228
Faisal Valib90b2112014-04-03 16:32:21 +00003229 // If this is a generic lambda call operator specialization, its
3230 // instantiation pattern is always its primary template's pattern
3231 // even if its primary template was instantiated from another
3232 // member template (which happens with nested generic lambdas).
3233 // Since a lambda's call operator's body is transformed eagerly,
3234 // we don't have to go hunting for a prototype definition template
3235 // (i.e. instantiated-from-member-template) to use as an instantiation
3236 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003237
Faisal Valib90b2112014-04-03 16:32:21 +00003238 if (isGenericLambdaCallOperatorSpecialization(
3239 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003240 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3241 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003242 }
Richard Smith2195ec92017-04-21 01:15:13 +00003243
Douglas Gregorafca3b42009-10-27 20:53:28 +00003244 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3245 while (Primary->getInstantiatedFromMemberTemplate()) {
3246 // If we have hit a point where the user provided a specialization of
3247 // this template, we're done looking.
3248 if (Primary->isMemberSpecialization())
3249 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003250 Primary = Primary->getInstantiatedFromMemberTemplate();
3251 }
Richard Smith2195ec92017-04-21 01:15:13 +00003252
3253 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Douglas Gregorafca3b42009-10-27 20:53:28 +00003254 }
Richard Smith2195ec92017-04-21 01:15:13 +00003255
3256 if (auto *MFD = getInstantiatedFromMemberFunction())
3257 return getDefinitionOrSelf(MFD);
3258
3259 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003260}
3261
Douglas Gregor70d83e22009-06-29 17:30:29 +00003262FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003263 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003264 = TemplateOrSpecialization
3265 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003266 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003267 }
Craig Topper36250ad2014-05-12 05:36:57 +00003268 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003269}
3270
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003271FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3272 return getASTContext().getClassScopeSpecializationPattern(this);
3273}
3274
Chandler Carruth21c90602015-12-30 03:24:14 +00003275FunctionTemplateSpecializationInfo *
3276FunctionDecl::getTemplateSpecializationInfo() const {
3277 return TemplateOrSpecialization
3278 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3279}
3280
Douglas Gregor70d83e22009-06-29 17:30:29 +00003281const TemplateArgumentList *
3282FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003283 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003284 = TemplateOrSpecialization
3285 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003286 return Info->TemplateArguments;
3287 }
Craig Topper36250ad2014-05-12 05:36:57 +00003288 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003289}
3290
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003291const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003292FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3293 if (FunctionTemplateSpecializationInfo *Info
3294 = TemplateOrSpecialization
3295 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3296 return Info->TemplateArgumentsAsWritten;
3297 }
Craig Topper36250ad2014-05-12 05:36:57 +00003298 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003299}
3300
Mike Stump11289f42009-09-09 15:08:12 +00003301void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003302FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3303 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003304 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003305 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003306 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003307 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3308 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003309 assert(TSK != TSK_Undeclared &&
3310 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003311 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003312 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003313 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003314 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3315 TemplateArgs,
3316 TemplateArgsAsWritten,
3317 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003318 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003319 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003320}
3321
John McCallb9c78482010-04-08 09:05:18 +00003322void
3323FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3324 const UnresolvedSetImpl &Templates,
3325 const TemplateArgumentListInfo &TemplateArgs) {
3326 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003327 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003328 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3329 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003330 TemplateOrSpecialization = Info;
3331}
3332
James Y Knight7a22b242015-08-06 20:26:32 +00003333DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003334FunctionDecl::getDependentSpecializationInfo() const {
3335 return TemplateOrSpecialization
3336 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3337}
3338
3339DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003340DependentFunctionTemplateSpecializationInfo::Create(
3341 ASTContext &Context, const UnresolvedSetImpl &Ts,
3342 const TemplateArgumentListInfo &TArgs) {
3343 void *Buffer = Context.Allocate(
3344 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3345 TArgs.size(), Ts.size()));
3346 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3347}
3348
John McCallb9c78482010-04-08 09:05:18 +00003349DependentFunctionTemplateSpecializationInfo::
3350DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3351 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003352 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
John McCallb9c78482010-04-08 09:05:18 +00003353
James Y Knight53c76162015-07-17 18:21:37 +00003354 NumTemplates = Ts.size();
3355 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003356
James Y Knight7a22b242015-08-06 20:26:32 +00003357 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003358 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3359 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3360
James Y Knight7a22b242015-08-06 20:26:32 +00003361 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003362 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3363 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3364}
3365
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003366TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003367 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003368 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003369 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003370 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003371 if (FTSInfo)
3372 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003373
Douglas Gregord801b062009-10-07 23:56:10 +00003374 MemberSpecializationInfo *MSInfo
3375 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3376 if (MSInfo)
3377 return MSInfo->getTemplateSpecializationKind();
3378
3379 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003380}
3381
Mike Stump11289f42009-09-09 15:08:12 +00003382void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003383FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3384 SourceLocation PointOfInstantiation) {
3385 if (FunctionTemplateSpecializationInfo *FTSInfo
3386 = TemplateOrSpecialization.dyn_cast<
3387 FunctionTemplateSpecializationInfo*>()) {
3388 FTSInfo->setTemplateSpecializationKind(TSK);
3389 if (TSK != TSK_ExplicitSpecialization &&
3390 PointOfInstantiation.isValid() &&
3391 FTSInfo->getPointOfInstantiation().isInvalid())
3392 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3393 } else if (MemberSpecializationInfo *MSInfo
3394 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3395 MSInfo->setTemplateSpecializationKind(TSK);
3396 if (TSK != TSK_ExplicitSpecialization &&
3397 PointOfInstantiation.isValid() &&
3398 MSInfo->getPointOfInstantiation().isInvalid())
3399 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3400 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003401 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003402}
3403
3404SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003405 if (FunctionTemplateSpecializationInfo *FTSInfo
3406 = TemplateOrSpecialization.dyn_cast<
3407 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003408 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003409 else if (MemberSpecializationInfo *MSInfo
3410 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003411 return MSInfo->getPointOfInstantiation();
3412
3413 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003414}
3415
Douglas Gregor6411b922009-09-11 20:15:17 +00003416bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003417 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003418 return true;
3419
3420 // If this function was instantiated from a member function of a
3421 // class template, check whether that member function was defined out-of-line.
3422 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3423 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003424 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003425 return Definition->isOutOfLine();
3426 }
3427
3428 // If this function was instantiated from a function template,
3429 // check whether that function template was defined out-of-line.
3430 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3431 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003432 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003433 return Definition->isOutOfLine();
3434 }
3435
3436 return false;
3437}
3438
Abramo Bagnaraea947882011-03-08 16:41:52 +00003439SourceRange FunctionDecl::getSourceRange() const {
3440 return SourceRange(getOuterLocStart(), EndRangeLoc);
3441}
3442
Anna Zaks28db7ce2012-01-18 02:45:01 +00003443unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003444 IdentifierInfo *FnInfo = getIdentifier();
3445
3446 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003447 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003448
3449 // Builtin handling.
3450 switch (getBuiltinID()) {
3451 case Builtin::BI__builtin_memset:
3452 case Builtin::BI__builtin___memset_chk:
3453 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003454 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003455
3456 case Builtin::BI__builtin_memcpy:
3457 case Builtin::BI__builtin___memcpy_chk:
3458 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003459 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003460
3461 case Builtin::BI__builtin_memmove:
3462 case Builtin::BI__builtin___memmove_chk:
3463 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003464 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003465
3466 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003467 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003468 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003469
Anna Zaks201d4892012-01-13 21:52:01 +00003470 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003471 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003472 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003473
3474 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003475 case Builtin::BImemcmp:
3476 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003477
3478 case Builtin::BI__builtin_strncpy:
3479 case Builtin::BI__builtin___strncpy_chk:
3480 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003481 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003482
3483 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003484 case Builtin::BIstrncmp:
3485 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003486
3487 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003488 case Builtin::BIstrncasecmp:
3489 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003490
3491 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003492 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003493 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003494 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003495
3496 case Builtin::BI__builtin_strndup:
3497 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003498 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003499
Anna Zaks314cd092012-02-01 19:08:57 +00003500 case Builtin::BI__builtin_strlen:
3501 case Builtin::BIstrlen:
3502 return Builtin::BIstrlen;
3503
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003504 case Builtin::BI__builtin_bzero:
3505 case Builtin::BIbzero:
3506 return Builtin::BIbzero;
3507
Anna Zaks201d4892012-01-13 21:52:01 +00003508 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003509 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003510 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003511 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003512 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003513 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003514 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003515 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003516 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003517 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003518 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003519 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003520 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003521 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003522 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003523 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003524 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003525 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003526 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003527 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003528 else if (FnInfo->isStr("strlen"))
3529 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003530 else if (FnInfo->isStr("bzero"))
3531 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003532 }
3533 break;
3534 }
Anna Zaks22122702012-01-17 00:37:07 +00003535 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003536}
3537
Chris Lattner59a25942008-03-31 00:36:02 +00003538//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003539// FieldDecl Implementation
3540//===----------------------------------------------------------------------===//
3541
Jay Foad39c79802011-01-12 09:06:06 +00003542FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003543 SourceLocation StartLoc, SourceLocation IdLoc,
3544 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003545 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003546 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003547 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3548 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003549}
3550
Douglas Gregor72172e92012-01-05 21:55:30 +00003551FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003552 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3553 SourceLocation(), nullptr, QualType(), nullptr,
3554 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003555}
3556
Sebastian Redl833ef452010-01-26 22:01:41 +00003557bool FieldDecl::isAnonymousStructOrUnion() const {
3558 if (!isImplicit() || getDeclName())
3559 return false;
3560
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003561 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003562 return Record->getDecl()->isAnonymousStructOrUnion();
3563
3564 return false;
3565}
3566
Richard Smithcaf33902011-10-10 18:28:20 +00003567unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3568 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003569 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00003570}
3571
John McCall4e819612011-01-20 07:57:12 +00003572unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003573 const FieldDecl *Canonical = getCanonicalDecl();
3574 if (Canonical != this)
3575 return Canonical->getFieldIndex();
3576
John McCall4e819612011-01-20 07:57:12 +00003577 if (CachedFieldIndex) return CachedFieldIndex - 1;
3578
Richard Smithd62306a2011-11-10 06:34:14 +00003579 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00003580 const RecordDecl *RD = getParent();
Richard Smithd62306a2011-11-10 06:34:14 +00003581
Hans Wennborga302cd92014-08-21 16:06:57 +00003582 for (auto *Field : RD->fields()) {
3583 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3584 ++Index;
3585 }
John McCall4e819612011-01-20 07:57:12 +00003586
Richard Smithd62306a2011-11-10 06:34:14 +00003587 assert(CachedFieldIndex && "failed to find field in parent");
3588 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003589}
3590
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003591SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00003592 const Expr *FinalExpr = getInClassInitializer();
3593 if (!FinalExpr)
3594 FinalExpr = getBitWidth();
3595 if (FinalExpr)
3596 return SourceRange(getInnerLocStart(), FinalExpr->getLocEnd());
3597 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00003598}
3599
3600void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003601 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003602 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003603 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00003604 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003605 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003606 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3607 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003608}
3609
Sebastian Redl833ef452010-01-26 22:01:41 +00003610//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003611// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003612//===----------------------------------------------------------------------===//
3613
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003614SourceLocation TagDecl::getOuterLocStart() const {
3615 return getTemplateOrInnerLocStart(this);
3616}
3617
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003618SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003619 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003620 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003621 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003622}
3623
Rafael Espindola8db352d2013-10-17 15:37:26 +00003624TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003625
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003626void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003627 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003628 if (const Type *T = getTypeForDecl()) {
3629 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003630 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003631 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003632 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003633}
3634
Douglas Gregordee1be82009-01-17 00:42:38 +00003635void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003636 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00003637
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003638 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003639 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003640 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003641 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003642 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003643 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003644}
3645
3646void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003647 assert((!isa<CXXRecordDecl>(this) ||
3648 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3649 "definition completed but not started");
3650
John McCallf937c022011-10-07 06:10:15 +00003651 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00003652 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003653
3654 if (ASTMutationListener *L = getASTMutationListener())
3655 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003656}
3657
John McCallf937c022011-10-07 06:10:15 +00003658TagDecl *TagDecl::getDefinition() const {
3659 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003660 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003661
3662 // If it's possible for us to have an out-of-date definition, check now.
3663 if (MayHaveOutOfDateDef) {
3664 if (IdentifierInfo *II = getIdentifier()) {
3665 if (II->isOutOfDate()) {
3666 updateOutOfDate(*II);
3667 }
3668 }
3669 }
3670
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003671 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003672 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003673
Aaron Ballman86c93902014-03-06 23:45:36 +00003674 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003675 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003676 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003677
Craig Topper36250ad2014-05-12 05:36:57 +00003678 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003679}
3680
Douglas Gregor14454802011-02-25 02:25:35 +00003681void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3682 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003683 // Make sure the extended qualifier info is allocated.
3684 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003685 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003686 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003687 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003688 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003689 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003690 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003691 if (getExtInfo()->NumTemplParamLists == 0) {
3692 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003693 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003694 }
3695 else
3696 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003697 }
3698 }
3699}
3700
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003701void TagDecl::setTemplateParameterListsInfo(
3702 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3703 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003704 // Make sure the extended decl info is allocated.
3705 if (!hasExtInfo())
3706 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003707 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003708 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003709 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003710}
3711
Ted Kremenek21475702008-09-05 17:16:31 +00003712//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003713// EnumDecl Implementation
3714//===----------------------------------------------------------------------===//
3715
David Blaikie68e081d2011-12-20 02:48:34 +00003716void EnumDecl::anchor() { }
3717
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003718EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3719 SourceLocation StartLoc, SourceLocation IdLoc,
3720 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003721 EnumDecl *PrevDecl, bool IsScoped,
3722 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003723 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3724 IsScoped, IsScopedUsingClassTag, IsFixed);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003725 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
Sebastian Redl833ef452010-01-26 22:01:41 +00003726 C.getTypeDeclType(Enum, PrevDecl);
3727 return Enum;
3728}
3729
Douglas Gregor72172e92012-01-05 21:55:30 +00003730EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003731 EnumDecl *Enum =
3732 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3733 nullptr, nullptr, false, false, false);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003734 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3735 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003736}
3737
Alp Tokerb9fa5122014-01-06 11:31:18 +00003738SourceRange EnumDecl::getIntegerTypeRange() const {
3739 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3740 return TI->getTypeLoc().getSourceRange();
3741 return SourceRange();
3742}
3743
Douglas Gregord5058122010-02-11 01:19:42 +00003744void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00003745 QualType NewPromotionType,
3746 unsigned NumPositiveBits,
3747 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00003748 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00003749 if (!IntegerType)
3750 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00003751 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00003752 setNumPositiveBits(NumPositiveBits);
3753 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00003754 TagDecl::completeDefinition();
3755}
3756
Akira Hatanaka3c268af2017-03-21 02:23:00 +00003757bool EnumDecl::isClosed() const {
3758 if (const auto *A = getAttr<EnumExtensibilityAttr>())
3759 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
3760 return true;
3761}
3762
3763bool EnumDecl::isClosedFlag() const {
3764 return isClosed() && hasAttr<FlagEnumAttr>();
3765}
3766
3767bool EnumDecl::isClosedNonFlag() const {
3768 return isClosed() && !hasAttr<FlagEnumAttr>();
3769}
3770
Richard Smith7d137e32012-03-23 03:33:32 +00003771TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3772 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3773 return MSI->getTemplateSpecializationKind();
3774
3775 return TSK_Undeclared;
3776}
3777
3778void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3779 SourceLocation PointOfInstantiation) {
3780 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3781 assert(MSI && "Not an instantiated member enumeration?");
3782 MSI->setTemplateSpecializationKind(TSK);
3783 if (TSK != TSK_ExplicitSpecialization &&
3784 PointOfInstantiation.isValid() &&
3785 MSI->getPointOfInstantiation().isInvalid())
3786 MSI->setPointOfInstantiation(PointOfInstantiation);
3787}
3788
Richard Smith6739a102016-05-05 00:56:12 +00003789EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3790 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3791 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3792 EnumDecl *ED = getInstantiatedFromMemberEnum();
3793 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3794 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00003795 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00003796 }
3797 }
3798
3799 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3800 "couldn't find pattern for enum instantiation");
3801 return nullptr;
3802}
3803
Richard Smith4b38ded2012-03-14 23:13:10 +00003804EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3805 if (SpecializationInfo)
3806 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3807
Craig Topper36250ad2014-05-12 05:36:57 +00003808 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00003809}
3810
3811void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3812 TemplateSpecializationKind TSK) {
3813 assert(!SpecializationInfo && "Member enum is already a specialization");
3814 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3815}
3816
Sebastian Redl833ef452010-01-26 22:01:41 +00003817//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00003818// RecordDecl Implementation
3819//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00003820
Richard Smith053f6c62014-05-16 23:01:30 +00003821RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3822 DeclContext *DC, SourceLocation StartLoc,
3823 SourceLocation IdLoc, IdentifierInfo *Id,
3824 RecordDecl *PrevDecl)
3825 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00003826 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003827 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00003828 HasObjectMember = false;
Fariborz Jahanian78652202013-01-25 23:57:05 +00003829 HasVolatileMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003830 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00003831 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00003832}
3833
Jay Foad39c79802011-01-12 09:06:06 +00003834RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003835 SourceLocation StartLoc, SourceLocation IdLoc,
3836 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00003837 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3838 StartLoc, IdLoc, Id, PrevDecl);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003839 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3840
Ted Kremenek21475702008-09-05 17:16:31 +00003841 C.getTypeDeclType(R, PrevDecl);
3842 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00003843}
3844
Douglas Gregor72172e92012-01-05 21:55:30 +00003845RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003846 RecordDecl *R =
3847 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3848 SourceLocation(), nullptr, nullptr);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003849 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3850 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003851}
3852
Douglas Gregordfcad112009-03-25 15:59:44 +00003853bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00003854 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00003855 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3856}
3857
Alexey Bataev39c81e22014-08-28 04:28:19 +00003858bool RecordDecl::isLambda() const {
3859 if (auto RD = dyn_cast<CXXRecordDecl>(this))
3860 return RD->isLambda();
3861 return false;
3862}
3863
Alexey Bataev330de032014-10-29 12:21:55 +00003864bool RecordDecl::isCapturedRecord() const {
3865 return hasAttr<CapturedRecordAttr>();
3866}
3867
3868void RecordDecl::setCapturedRecord() {
3869 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3870}
3871
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003872RecordDecl::field_iterator RecordDecl::field_begin() const {
3873 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3874 LoadFieldsFromExternalStorage();
3875
3876 return field_iterator(decl_iterator(FirstDecl));
3877}
3878
Douglas Gregorb11aad82011-02-19 18:51:44 +00003879/// completeDefinition - Notes that the definition of this type is now
3880/// complete.
3881void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00003882 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00003883 TagDecl::completeDefinition();
3884}
3885
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003886/// isMsStruct - Get whether or not this record uses ms_struct layout.
3887/// This which can be turned on with an attribute, pragma, or the
3888/// -mms-bitfields command-line option.
3889bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00003890 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00003891}
3892
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003893void RecordDecl::LoadFieldsFromExternalStorage() const {
3894 ExternalASTSource *Source = getASTContext().getExternalSource();
3895 assert(hasExternalLexicalStorage() && Source && "No external storage?");
3896
3897 // Notify that we have a RecordDecl doing some initialization.
3898 ExternalASTSource::Deserializing TheFields(Source);
3899
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003900 SmallVector<Decl*, 64> Decls;
Richard Smith3cb15722015-08-05 22:41:45 +00003901 LoadedFieldsFromExternalStorage = true;
3902 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3903 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3904 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003905
3906#ifndef NDEBUG
3907 // Check that all decls we got were FieldDecls.
3908 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00003909 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003910#endif
3911
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003912 if (Decls.empty())
3913 return;
3914
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003915 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00003916 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00003917}
3918
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003919bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3920 ASTContext &Context = getASTContext();
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003921 if (!Context.getLangOpts().Sanitize.hasOneOf(
3922 SanitizerKind::Address | SanitizerKind::KernelAddress) ||
Alexey Samsonova0416102014-11-11 01:26:14 +00003923 !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003924 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003925 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003926 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003927 // We may be able to relax some of these requirements.
3928 int ReasonToReject = -1;
3929 if (!CXXRD || CXXRD->isExternCContext())
3930 ReasonToReject = 0; // is not C++.
3931 else if (CXXRD->hasAttr<PackedAttr>())
3932 ReasonToReject = 1; // is packed.
3933 else if (CXXRD->isUnion())
3934 ReasonToReject = 2; // is a union.
3935 else if (CXXRD->isTriviallyCopyable())
3936 ReasonToReject = 3; // is trivially copyable.
3937 else if (CXXRD->hasTrivialDestructor())
3938 ReasonToReject = 4; // has trivial destructor.
3939 else if (CXXRD->isStandardLayout())
3940 ReasonToReject = 5; // is standard layout.
Alexey Samsonov33e00e22014-10-16 23:50:26 +00003941 else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00003942 ReasonToReject = 6; // is in a blacklisted file.
3943 else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3944 "field-padding"))
3945 ReasonToReject = 7; // is blacklisted.
3946
3947 if (EmitRemark) {
3948 if (ReasonToReject >= 0)
3949 Context.getDiagnostics().Report(
3950 getLocation(),
3951 diag::remark_sanitize_address_insert_extra_padding_rejected)
3952 << getQualifiedNameAsString() << ReasonToReject;
3953 else
3954 Context.getDiagnostics().Report(
3955 getLocation(),
3956 diag::remark_sanitize_address_insert_extra_padding_accepted)
3957 << getQualifiedNameAsString();
3958 }
3959 return ReasonToReject < 0;
3960}
3961
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003962const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3963 for (const auto *I : fields()) {
3964 if (I->getIdentifier())
3965 return I;
3966
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003967 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003968 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003969 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003970 return NamedDataMember;
3971 }
3972
3973 // We didn't find a named data member.
3974 return nullptr;
3975}
3976
3977
Steve Naroff415d3d52008-10-08 17:01:13 +00003978//===----------------------------------------------------------------------===//
3979// BlockDecl Implementation
3980//===----------------------------------------------------------------------===//
3981
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003982void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003983 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00003984
Steve Naroffc4b30e52009-03-13 16:56:44 +00003985 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003986 if (!NewParamInfo.empty()) {
3987 NumParams = NewParamInfo.size();
3988 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3989 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00003990 }
3991}
3992
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003993void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3994 bool CapturesCXXThis) {
3995 this->CapturesCXXThis = CapturesCXXThis;
3996 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00003997
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00003998 if (Captures.empty()) {
3999 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004000 return;
4001 }
4002
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004003 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004004}
Sebastian Redl833ef452010-01-26 22:01:41 +00004005
John McCallce45f882011-06-15 22:51:16 +00004006bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004007 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004008 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004009 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004010 return true;
4011
4012 return false;
4013}
4014
Douglas Gregor70226da2010-12-21 16:27:07 +00004015SourceRange BlockDecl::getSourceRange() const {
4016 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
4017}
Sebastian Redl833ef452010-01-26 22:01:41 +00004018
4019//===----------------------------------------------------------------------===//
4020// Other Decl Allocation/Deallocation Method Implementations
4021//===----------------------------------------------------------------------===//
4022
David Blaikie68e081d2011-12-20 02:48:34 +00004023void TranslationUnitDecl::anchor() { }
4024
Sebastian Redl833ef452010-01-26 22:01:41 +00004025TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004026 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004027}
4028
Nico Weber66220292016-03-02 17:28:48 +00004029void PragmaCommentDecl::anchor() { }
4030
4031PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4032 TranslationUnitDecl *DC,
4033 SourceLocation CommentLoc,
4034 PragmaMSCommentKind CommentKind,
4035 StringRef Arg) {
4036 PragmaCommentDecl *PCD =
4037 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4038 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4039 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4040 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4041 return PCD;
4042}
4043
4044PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4045 unsigned ID,
4046 unsigned ArgSize) {
4047 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4048 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4049}
4050
Nico Webercbbaeb12016-03-02 19:28:54 +00004051void PragmaDetectMismatchDecl::anchor() { }
4052
4053PragmaDetectMismatchDecl *
4054PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4055 SourceLocation Loc, StringRef Name,
4056 StringRef Value) {
4057 size_t ValueStart = Name.size() + 1;
4058 PragmaDetectMismatchDecl *PDMD =
4059 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4060 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4061 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4062 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4063 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4064 Value.size());
4065 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4066 return PDMD;
4067}
4068
4069PragmaDetectMismatchDecl *
4070PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4071 unsigned NameValueSize) {
4072 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4073 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4074}
Nico Weber66220292016-03-02 17:28:48 +00004075
Richard Smithf19e1272015-03-07 00:04:49 +00004076void ExternCContextDecl::anchor() { }
4077
4078ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4079 TranslationUnitDecl *DC) {
4080 return new (C, DC) ExternCContextDecl(DC);
4081}
4082
David Blaikie68e081d2011-12-20 02:48:34 +00004083void LabelDecl::anchor() { }
4084
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004085LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004086 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004087 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004088}
4089
4090LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4091 SourceLocation IdentL, IdentifierInfo *II,
4092 SourceLocation GnuLabelL) {
4093 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004094 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004095}
4096
Douglas Gregor72172e92012-01-05 21:55:30 +00004097LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004098 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4099 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004100}
4101
Ehsan Akhgari31097582014-09-22 02:21:54 +00004102void LabelDecl::setMSAsmLabel(StringRef Name) {
4103 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4104 memcpy(Buffer, Name.data(), Name.size());
4105 Buffer[Name.size()] = '\0';
4106 MSAsmName = Buffer;
4107}
4108
David Blaikie68e081d2011-12-20 02:48:34 +00004109void ValueDecl::anchor() { }
4110
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004111bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004112 for (const auto *I : attrs())
4113 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004114 return true;
4115
4116 return isWeakImported();
4117}
4118
David Blaikie68e081d2011-12-20 02:48:34 +00004119void ImplicitParamDecl::anchor() { }
4120
Sebastian Redl833ef452010-01-26 22:01:41 +00004121ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004122 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004123 IdentifierInfo *Id, QualType Type,
4124 ImplicitParamKind ParamKind) {
4125 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4126}
4127
4128ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4129 ImplicitParamKind ParamKind) {
4130 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004131}
4132
Richard Smithf7981722013-11-22 09:01:48 +00004133ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004134 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004135 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004136}
4137
Sebastian Redl833ef452010-01-26 22:01:41 +00004138FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004139 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004140 const DeclarationNameInfo &NameInfo,
4141 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004142 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004143 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004144 bool hasWrittenPrototype,
4145 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004146 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004147 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4148 SC, isInlineSpecified, isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00004149 New->HasWrittenPrototype = hasWrittenPrototype;
4150 return New;
4151}
4152
Douglas Gregor72172e92012-01-05 21:55:30 +00004153FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004154 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004155 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004156 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004157}
4158
Sebastian Redl833ef452010-01-26 22:01:41 +00004159BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004160 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004161}
4162
Douglas Gregor72172e92012-01-05 21:55:30 +00004163BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004164 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004165}
4166
Chandler Carruth21c90602015-12-30 03:24:14 +00004167CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4168 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4169 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4170
Ben Langmuir37943a72013-05-03 19:00:33 +00004171CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4172 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004173 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004174 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004175}
4176
Ben Langmuirce914fc2013-05-03 19:20:19 +00004177CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004178 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004179 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004180 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004181}
4182
Chandler Carruth21c90602015-12-30 03:24:14 +00004183Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4184void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4185
4186bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4187void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4188
Sebastian Redl833ef452010-01-26 22:01:41 +00004189EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4190 SourceLocation L,
4191 IdentifierInfo *Id, QualType T,
4192 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004193 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004194}
4195
Douglas Gregor72172e92012-01-05 21:55:30 +00004196EnumConstantDecl *
4197EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004198 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4199 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004200}
4201
David Blaikie68e081d2011-12-20 02:48:34 +00004202void IndirectFieldDecl::anchor() { }
4203
Richard Smith9f951822016-01-06 22:49:11 +00004204IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4205 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004206 QualType T,
4207 MutableArrayRef<NamedDecl *> CH)
4208 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4209 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004210 // In C++, indirect field declarations conflict with tag declarations in the
4211 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4212 if (C.getLangOpts().CPlusPlus)
4213 IdentifierNamespace |= IDNS_Tag;
4214}
4215
Benjamin Kramer39593702010-11-21 14:11:41 +00004216IndirectFieldDecl *
4217IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004218 IdentifierInfo *Id, QualType T,
4219 llvm::MutableArrayRef<NamedDecl *> CH) {
4220 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004221}
4222
Douglas Gregor72172e92012-01-05 21:55:30 +00004223IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4224 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004225 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004226 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004227}
4228
Douglas Gregorbe996932010-09-01 20:41:53 +00004229SourceRange EnumConstantDecl::getSourceRange() const {
4230 SourceLocation End = getLocation();
4231 if (Init)
4232 End = Init->getLocEnd();
4233 return SourceRange(getLocation(), End);
4234}
4235
David Blaikie68e081d2011-12-20 02:48:34 +00004236void TypeDecl::anchor() { }
4237
Sebastian Redl833ef452010-01-26 22:01:41 +00004238TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004239 SourceLocation StartLoc, SourceLocation IdLoc,
4240 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004241 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004242}
4243
David Blaikie68e081d2011-12-20 02:48:34 +00004244void TypedefNameDecl::anchor() { }
4245
Richard Smith42413142015-05-15 20:05:43 +00004246TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4247 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4248 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4249 auto *ThisTypedef = this;
4250 if (AnyRedecl && OwningTypedef) {
4251 OwningTypedef = OwningTypedef->getCanonicalDecl();
4252 ThisTypedef = ThisTypedef->getCanonicalDecl();
4253 }
4254 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004255 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004256 }
Richard Smitha5230222015-03-27 01:37:43 +00004257
4258 return nullptr;
4259}
4260
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004261bool TypedefNameDecl::isTransparentTagSlow() const {
4262 auto determineIsTransparent = [&]() {
4263 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4264 if (auto *TD = TT->getDecl()) {
4265 if (TD->getName() != getName())
4266 return false;
4267 SourceLocation TTLoc = getLocation();
4268 SourceLocation TDLoc = TD->getLocation();
4269 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4270 return false;
4271 SourceManager &SM = getASTContext().getSourceManager();
4272 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4273 }
4274 }
4275 return false;
4276 };
4277
4278 bool isTransparent = determineIsTransparent();
4279 CacheIsTransparentTag = 1;
4280 if (isTransparent)
4281 CacheIsTransparentTag |= 0x2;
4282 return isTransparent;
4283}
4284
Douglas Gregor72172e92012-01-05 21:55:30 +00004285TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004286 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004287 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004288}
4289
Richard Smithdda56e42011-04-15 14:24:37 +00004290TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4291 SourceLocation StartLoc,
4292 SourceLocation IdLoc, IdentifierInfo *Id,
4293 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004294 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004295}
4296
Douglas Gregor72172e92012-01-05 21:55:30 +00004297TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004298 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4299 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004300}
4301
Abramo Bagnaraea947882011-03-08 16:41:52 +00004302SourceRange TypedefDecl::getSourceRange() const {
4303 SourceLocation RangeEnd = getLocation();
4304 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4305 if (typeIsPostfix(TInfo->getType()))
4306 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4307 }
4308 return SourceRange(getLocStart(), RangeEnd);
4309}
4310
Richard Smithdda56e42011-04-15 14:24:37 +00004311SourceRange TypeAliasDecl::getSourceRange() const {
4312 SourceLocation RangeEnd = getLocStart();
4313 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4314 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4315 return SourceRange(getLocStart(), RangeEnd);
4316}
4317
David Blaikie68e081d2011-12-20 02:48:34 +00004318void FileScopeAsmDecl::anchor() { }
4319
Sebastian Redl833ef452010-01-26 22:01:41 +00004320FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004321 StringLiteral *Str,
4322 SourceLocation AsmLoc,
4323 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004324 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004325}
Douglas Gregorba345522011-12-02 23:23:56 +00004326
Richard Smithf7981722013-11-22 09:01:48 +00004327FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004328 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004329 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4330 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004331}
4332
Michael Han84324352013-02-22 17:15:32 +00004333void EmptyDecl::anchor() {}
4334
4335EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004336 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004337}
4338
4339EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004340 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004341}
4342
Douglas Gregorba345522011-12-02 23:23:56 +00004343//===----------------------------------------------------------------------===//
4344// ImportDecl Implementation
4345//===----------------------------------------------------------------------===//
4346
4347/// \brief Retrieve the number of module identifiers needed to name the given
4348/// module.
4349static unsigned getNumModuleIdentifiers(Module *Mod) {
4350 unsigned Result = 1;
4351 while (Mod->Parent) {
4352 Mod = Mod->Parent;
4353 ++Result;
4354 }
4355 return Result;
4356}
4357
Douglas Gregor22d09742012-01-03 18:04:46 +00004358ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004359 Module *Imported,
4360 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00004361 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004362 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004363{
4364 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004365 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004366 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4367 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004368}
4369
Douglas Gregor22d09742012-01-03 18:04:46 +00004370ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004371 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00004372 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00004373 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00004374{
James Y Knight7a22b242015-08-06 20:26:32 +00004375 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004376}
4377
Richard Smithf7981722013-11-22 09:01:48 +00004378ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004379 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004380 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004381 return new (C, DC,
4382 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004383 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004384}
4385
Richard Smithf7981722013-11-22 09:01:48 +00004386ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004387 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004388 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004389 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004390 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4391 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004392 Import->setImplicit();
4393 return Import;
4394}
4395
Douglas Gregor72172e92012-01-05 21:55:30 +00004396ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4397 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004398 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004399 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004400}
4401
4402ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4403 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004404 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004405
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004406 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004407 return llvm::makeArrayRef(StoredLocs,
4408 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004409}
4410
4411SourceRange ImportDecl::getSourceRange() const {
4412 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004413 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4414
Douglas Gregorba345522011-12-02 23:23:56 +00004415 return SourceRange(getLocation(), getIdentifierLocs().back());
4416}
Richard Smith8df390f2016-09-08 23:14:54 +00004417
4418//===----------------------------------------------------------------------===//
4419// ExportDecl Implementation
4420//===----------------------------------------------------------------------===//
4421
4422void ExportDecl::anchor() {}
4423
4424ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4425 SourceLocation ExportLoc) {
4426 return new (C, DC) ExportDecl(DC, ExportLoc);
4427}
4428
4429ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4430 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4431}