blob: 0d30f64b992e0cd6a76c87ec187bb7c2687748ab [file] [log] [blame]
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001//===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
Chris Lattnera11999d2006-10-15 22:34:45 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnera11999d2006-10-15 22:34:45 +00006//
7//===----------------------------------------------------------------------===//
8//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +00009// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000010//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Decl.h"
George Burgess IV99db3ea2017-08-09 04:02:49 +000014#include "Linkage.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000015#include "clang/AST/ASTContext.h"
Richard Trieu0f25c742018-12-14 03:35:10 +000016#include "clang/AST/ASTDiagnostic.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"
Reid Kleckner60573ae2019-11-15 17:31:55 -080019#include "clang/AST/Attr.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000020#include "clang/AST/CanonicalType.h"
21#include "clang/AST/DeclBase.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000024#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/AST/DeclTemplate.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000026#include "clang/AST/DeclarationName.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000027#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000028#include "clang/AST/ExprCXX.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000029#include "clang/AST/ExternalASTSource.h"
Richard Trieue6caa262017-12-23 00:41:01 +000030#include "clang/AST/ODRHash.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000031#include "clang/AST/PrettyDeclStackTrace.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000032#include "clang/AST/PrettyPrinter.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000033#include "clang/AST/Redeclarable.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000034#include "clang/AST/Stmt.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000035#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000037#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000038#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000039#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000040#include "clang/Basic/LLVM.h"
41#include "clang/Basic/LangOptions.h"
42#include "clang/Basic/Linkage.h"
Douglas Gregorba345522011-12-02 23:23:56 +000043#include "clang/Basic/Module.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000044#include "clang/Basic/PartialDiagnostic.h"
45#include "clang/Basic/SanitizerBlacklist.h"
46#include "clang/Basic/Sanitizers.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/SourceManager.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000049#include "clang/Basic/Specifiers.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000050#include "clang/Basic/TargetCXXABI.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000051#include "clang/Basic/TargetInfo.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000052#include "clang/Basic/Visibility.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000053#include "llvm/ADT/APSInt.h"
54#include "llvm/ADT/ArrayRef.h"
55#include "llvm/ADT/None.h"
56#include "llvm/ADT/Optional.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/SmallVector.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000059#include "llvm/ADT/StringRef.h"
Reid Kleckner60573ae2019-11-15 17:31:55 -080060#include "llvm/ADT/StringSwitch.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000061#include "llvm/ADT/Triple.h"
62#include "llvm/Support/Casting.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000063#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000064#include "llvm/Support/raw_ostream.h"
David Blaikie9c70e042011-09-21 18:16:56 +000065#include <algorithm>
Eugene Zelenkode0215c2017-11-13 23:01:27 +000066#include <cassert>
67#include <cstddef>
68#include <cstring>
69#include <memory>
70#include <string>
71#include <tuple>
72#include <type_traits>
David Blaikie9c70e042011-09-21 18:16:56 +000073
Chris Lattner6d9a6852006-10-25 05:11:20 +000074using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000075
Richard Smith0b87e072013-10-07 08:02:11 +000076Decl *clang::getPrimaryMergedDecl(Decl *D) {
77 return D->getASTContext().getPrimaryMergedDecl(D);
78}
79
Jordan Rose1e879d82018-03-23 00:07:18 +000080void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
81 SourceLocation Loc = this->Loc;
82 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
83 if (Loc.isValid()) {
84 Loc.print(OS, Context.getSourceManager());
85 OS << ": ";
86 }
87 OS << Message;
88
89 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
90 OS << " '";
91 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
92 OS << "'";
93 }
94
95 OS << '\n';
96}
97
Richard Smith73b21d82014-09-03 02:33:22 +000098// Defined here so that it can be inlined into its direct callers.
99bool Decl::isOutOfLine() const {
100 return !getLexicalDeclContext()->Equals(getDeclContext());
101}
102
Richard Smith42413142015-05-15 20:05:43 +0000103TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
104 : Decl(TranslationUnit, nullptr, SourceLocation()),
Eugene Zelenkode0215c2017-11-13 23:01:27 +0000105 DeclContext(TranslationUnit), Ctx(ctx) {}
Richard Smith42413142015-05-15 20:05:43 +0000106
Chris Lattner88f70d62008-03-15 05:43:15 +0000107//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000108// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000109//===----------------------------------------------------------------------===//
110
John McCalldf25c432013-02-16 00:17:33 +0000111// Visibility rules aren't rigorously externally specified, but here
112// are the basic principles behind what we implement:
113//
114// 1. An explicit visibility attribute is generally a direct expression
115// of the user's intent and should be honored. Only the innermost
116// visibility attribute applies. If no visibility attribute applies,
117// global visibility settings are considered.
118//
119// 2. There is one caveat to the above: on or in a template pattern,
120// an explicit visibility attribute is just a default rule, and
121// visibility can be decreased by the visibility of template
122// arguments. But this, too, has an exception: an attribute on an
123// explicit specialization or instantiation causes all the visibility
124// restrictions of the template arguments to be ignored.
125//
126// 3. A variable that does not otherwise have explicit visibility can
127// be restricted by the visibility of its type.
128//
129// 4. A visibility restriction is explicit if it comes from an
130// attribute (or something like it), not a global visibility setting.
131// When emitting a reference to an external symbol, visibility
132// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +0000133//
134// 5. When computing the visibility of a non-type, including a
135// non-type member of a class, only non-type visibility restrictions
136// are considered: the 'visibility' attribute, global value-visibility
137// settings, and a few special cases like __private_extern.
138//
139// 6. When computing the visibility of a type, including a type member
140// of a class, only type visibility restrictions are considered:
141// the 'type_visibility' attribute and global type-visibility settings.
142// However, a 'visibility' attribute counts as a 'type_visibility'
143// attribute on any declaration that only has the former.
144//
145// The visibility of a "secondary" entity, like a template argument,
146// is computed using the kind of that entity, not the kind of the
147// primary entity for which we are computing visibility. For example,
148// the visibility of a specialization of either of these templates:
149// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
150// template <class T, bool (&compare)(T, X)> class matcher;
151// is restricted according to the type visibility of the argument 'T',
152// the type visibility of 'bool(&)(T,X)', and the value visibility of
153// the argument function 'compare'. That 'has_match' is a value
154// and 'matcher' is a type only matters when looking for attributes
155// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000156
John McCalld041a9b2013-02-20 01:54:26 +0000157/// Does this computation kind permit us to consider additional
158/// visibility settings from attributes and the like?
159static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000160 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000161}
162
163/// Given an LVComputationKind, return one of the same type/value sort
164/// that records that it already has explicit visibility.
165static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000166withExplicitVisibilityAlready(LVComputationKind Kind) {
167 Kind.IgnoreExplicitVisibility = true;
168 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000169}
170
David Blaikie05785d12013-02-20 22:23:23 +0000171static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000173 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000174 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000175 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000176}
177
John McCalldf25c432013-02-16 00:17:33 +0000178/// Is the given declaration a "type" or a "value" for the purposes of
179/// visibility computation?
180static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000181 return isa<TypeDecl>(D) ||
182 isa<ClassTemplateDecl>(D) ||
183 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000184}
185
John McCall5f46c482013-02-21 23:42:58 +0000186/// Does the given declaration have member specialization information,
187/// and if so, is it an explicit specialization?
188template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000189std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000190isExplicitMemberSpecialization(const T *D) {
191 if (const MemberSpecializationInfo *member =
192 D->getMemberSpecializationInfo()) {
193 return member->isExplicitSpecialization();
194 }
195 return false;
196}
197
198/// For templates, this question is easier: a member template can't be
199/// explicitly instantiated, so there's a single bit indicating whether
200/// or not this is an explicit member specialization.
201static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
202 return D->isMemberSpecialization();
203}
204
John McCalld041a9b2013-02-20 01:54:26 +0000205/// Given a visibility attribute, return the explicit visibility
206/// associated with it.
207template <class T>
208static Visibility getVisibilityFromAttr(const T *attr) {
209 switch (attr->getVisibility()) {
210 case T::Default:
211 return DefaultVisibility;
212 case T::Hidden:
213 return HiddenVisibility;
214 case T::Protected:
215 return ProtectedVisibility;
216 }
217 llvm_unreachable("bad visibility kind");
218}
219
John McCalldf25c432013-02-16 00:17:33 +0000220/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000221static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000222 NamedDecl::ExplicitVisibilityKind kind) {
223 // If we're ultimately computing the visibility of a type, look for
224 // a 'type_visibility' attribute before looking for 'visibility'.
225 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000226 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000227 return getVisibilityFromAttr(A);
228 }
229 }
230
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000231 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000232 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000233 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000234 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000235
David Blaikie7a30dc52013-02-21 01:47:18 +0000236 return None;
John McCall457a04e2010-10-22 21:05:15 +0000237}
238
George Burgess IV99db3ea2017-08-09 04:02:49 +0000239LinkageInfo LinkageComputer::getLVForType(const Type &T,
240 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000241 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000242 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000243 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000244}
245
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000246/// Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000247/// template parameter list. For visibility purposes, template
248/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000249LinkageInfo LinkageComputer::getLVForTemplateParameterList(
250 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000251 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000252 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000253 // Template type parameters are the most common and never
254 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000255 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000256 continue;
257
258 // Non-type template parameters can be restricted by the value type, e.g.
259 // template <enum X> class A { ... };
260 // We have to be careful here, though, because we can be dealing with
261 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000262 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000263 // Handle the non-pack case first.
264 if (!NTTP->isExpandedParameterPack()) {
265 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000266 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000267 }
268 continue;
269 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000270
John McCalldf25c432013-02-16 00:17:33 +0000271 // Look at all the types in an expanded pack.
272 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
273 QualType type = NTTP->getExpansionType(i);
274 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000275 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000276 }
John McCalldf25c432013-02-16 00:17:33 +0000277 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000278 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000279
John McCalldf25c432013-02-16 00:17:33 +0000280 // Template template parameters can be restricted by their
281 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000282 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000283
284 // Handle the non-pack case first.
285 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000286 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
287 computation));
John McCalldf25c432013-02-16 00:17:33 +0000288 continue;
289 }
290
291 // Look at all expansions in an expanded pack.
292 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
293 i != n; ++i) {
294 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000295 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000296 }
297 }
298
John McCall457a04e2010-10-22 21:05:15 +0000299 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000300}
301
Eli Friedman7e346a82013-07-01 20:22:57 +0000302static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000303 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000304 const DeclContext *DC = D->getDeclContext();
305 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000306 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
307 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000308 DC = DC->getParent();
309 }
310 return Ret;
311}
312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000313/// Get the most restrictive linkage for the types and
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000314/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000315///
316/// Note that we don't take an LVComputationKind because we always
317/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000318LinkageInfo
319LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
320 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000321 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000322
David Majnemerc7b85c42014-04-23 05:16:48 +0000323 for (const TemplateArgument &Arg : Args) {
324 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000325 case TemplateArgument::Null:
326 case TemplateArgument::Integral:
327 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000328 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000329
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000330 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000331 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000332 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000333
George Burgess IV00f70bd2018-03-01 05:43:23 +0000334 case TemplateArgument::Declaration: {
335 const NamedDecl *ND = Arg.getAsDecl();
336 assert(!usesTypeVisibility(ND));
337 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000338 continue;
George Burgess IV00f70bd2018-03-01 05:43:23 +0000339 }
Eli Friedmanb826a002012-09-26 02:36:12 +0000340
341 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000342 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000343 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000344
345 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000346 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000347 if (TemplateDecl *Template =
348 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000349 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000350 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000351
352 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000353 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000354 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000355 }
John McCalldf25c432013-02-16 00:17:33 +0000356 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000357 }
358
John McCall457a04e2010-10-22 21:05:15 +0000359 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000360}
361
George Burgess IV99db3ea2017-08-09 04:02:49 +0000362LinkageInfo
363LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
364 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000365 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000366}
367
John McCall5f46c482013-02-21 23:42:58 +0000368static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
369 const FunctionTemplateSpecializationInfo *specInfo) {
370 // Include visibility from the template parameters and arguments
371 // only if this is not an explicit instantiation or specialization
372 // with direct explicit visibility. (Implicit instantiations won't
373 // have a direct attribute.)
374 if (!specInfo->isExplicitInstantiationOrSpecialization())
375 return true;
376
377 return !fn->hasAttr<VisibilityAttr>();
378}
379
John McCalldf25c432013-02-16 00:17:33 +0000380/// Merge in template-related linkage and visibility for the given
381/// function template specialization.
382///
383/// We don't need a computation kind here because we can assume
384/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000385///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000386/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000387void LinkageComputer::mergeTemplateLV(
388 LinkageInfo &LV, const FunctionDecl *fn,
389 const FunctionTemplateSpecializationInfo *specInfo,
390 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000391 bool considerVisibility =
392 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000393
394 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000395 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000396 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000397 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000398 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
399
400 // Merge information from the template arguments.
401 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000402 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000403 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000404}
405
John McCall5f46c482013-02-21 23:42:58 +0000406/// Does the given declaration have a direct visibility attribute
407/// that would match the given rules?
408static bool hasDirectVisibilityAttribute(const NamedDecl *D,
409 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000410 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000411 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000412
413 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
414 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000415}
416
John McCalld041a9b2013-02-20 01:54:26 +0000417/// Should we consider visibility associated with the template
418/// arguments and parameters of the given class template specialization?
419static bool shouldConsiderTemplateVisibility(
420 const ClassTemplateSpecializationDecl *spec,
421 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000422 // Include visibility from the template parameters and arguments
423 // only if this is not an explicit instantiation or specialization
424 // with direct explicit visibility (and note that implicit
425 // instantiations won't have a direct attribute).
426 //
427 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000428 // for an explicit specialization when computing the visibility of a
429 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000430 //
431 // This is a bit complex; let's unpack it.
432 //
433 // An explicit class specialization is an independent, top-level
434 // declaration. As such, if it or any of its members has an
435 // explicit visibility attribute, that must directly express the
436 // user's intent, and we should honor it. The same logic applies to
437 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000438
439 // Fast path: if this is not an explicit instantiation or
440 // specialization, we always want to consider template-related
441 // visibility restrictions.
442 if (!spec->isExplicitInstantiationOrSpecialization())
443 return true;
444
445 // This is the 'member thereof' check.
446 if (spec->isExplicitSpecialization() &&
447 hasExplicitVisibilityAlready(computation))
448 return false;
449
John McCall5f46c482013-02-21 23:42:58 +0000450 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000451}
452
453/// Merge in template-related linkage and visibility for the given
454/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000455void LinkageComputer::mergeTemplateLV(
456 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
457 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000458 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000459
460 // Merge information from the template parameters, but ignore
461 // visibility if we're only considering template arguments.
462
John McCalld041a9b2013-02-20 01:54:26 +0000463 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000464 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000465 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000466 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000467 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000468
469 // Merge information from the template arguments. We ignore
470 // template-argument visibility if we've got an explicit
471 // instantiation with a visibility attribute.
472 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000473 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000474 if (considerVisibility)
475 LV.mergeVisibility(argsLV);
476 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000477}
478
Larisse Voufo5899e192014-07-02 23:08:34 +0000479/// Should we consider visibility associated with the template
480/// arguments and parameters of the given variable template
481/// specialization? As usual, follow class template specialization
482/// logic up to initialization.
483static bool shouldConsiderTemplateVisibility(
484 const VarTemplateSpecializationDecl *spec,
485 LVComputationKind computation) {
486 // Include visibility from the template parameters and arguments
487 // only if this is not an explicit instantiation or specialization
488 // with direct explicit visibility (and note that implicit
489 // instantiations won't have a direct attribute).
490 if (!spec->isExplicitInstantiationOrSpecialization())
491 return true;
492
493 // An explicit variable specialization is an independent, top-level
494 // declaration. As such, if it has an explicit visibility attribute,
495 // that must directly express the user's intent, and we should honor
496 // it.
497 if (spec->isExplicitSpecialization() &&
498 hasExplicitVisibilityAlready(computation))
499 return false;
500
501 return !hasDirectVisibilityAttribute(spec, computation);
502}
503
504/// Merge in template-related linkage and visibility for the given
505/// variable template specialization. As usual, follow class template
506/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000507void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
508 const VarTemplateSpecializationDecl *spec,
509 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000510 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
511
512 // Merge information from the template parameters, but ignore
513 // visibility if we're only considering template arguments.
514
515 VarTemplateDecl *temp = spec->getSpecializedTemplate();
516 LinkageInfo tempLV =
517 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
518 LV.mergeMaybeWithVisibility(tempLV,
519 considerVisibility && !hasExplicitVisibilityAlready(computation));
520
521 // Merge information from the template arguments. We ignore
522 // template-argument visibility if we've got an explicit
523 // instantiation with a visibility attribute.
524 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
525 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
526 if (considerVisibility)
527 LV.mergeVisibility(argsLV);
528 LV.mergeExternalVisibility(argsLV);
529}
530
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000531static bool useInlineVisibilityHidden(const NamedDecl *D) {
532 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000533 const LangOptions &Opts = D->getASTContext().getLangOpts();
534 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000535 return false;
536
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000537 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000538 if (!FD)
539 return false;
540
541 TemplateSpecializationKind TSK = TSK_Undeclared;
542 if (FunctionTemplateSpecializationInfo *spec
543 = FD->getTemplateSpecializationInfo()) {
544 TSK = spec->getTemplateSpecializationKind();
545 } else if (MemberSpecializationInfo *MSI =
546 FD->getMemberSpecializationInfo()) {
547 TSK = MSI->getTemplateSpecializationKind();
548 }
549
Craig Topper36250ad2014-05-12 05:36:57 +0000550 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000551 // InlineVisibilityHidden only applies to definitions, and
552 // isInlined() only gives meaningful answers on definitions
553 // anyway.
554 return TSK != TSK_ExplicitInstantiationDeclaration &&
555 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000556 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000557}
558
Rafael Espindola593537a2013-05-05 20:15:21 +0000559template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000560 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000561 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000562}
563
Richard Smith03c05032014-02-17 23:34:47 +0000564static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000565 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000566 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000567 return true;
568 return false;
569}
570
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000571/// Determine whether D is declared in the purview of a named module.
572static bool isInModulePurview(const NamedDecl *D) {
573 if (auto *M = D->getOwningModule())
574 return M->isModulePurview();
575 return false;
576}
577
Ali Tamurb6a8a6c2019-04-19 02:15:57 +0000578static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
Richard Smithbecb92d2017-10-10 22:33:17 +0000579 // FIXME: Handle isModulePrivate.
Richard Smith1283e982017-07-07 20:04:28 +0000580 switch (D->getModuleOwnershipKind()) {
581 case Decl::ModuleOwnershipKind::Unowned:
582 case Decl::ModuleOwnershipKind::ModulePrivate:
583 return false;
584 case Decl::ModuleOwnershipKind::Visible:
585 case Decl::ModuleOwnershipKind::VisibleWhenImported:
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000586 return isInModulePurview(D);
Richard Smith1283e982017-07-07 20:04:28 +0000587 }
588 llvm_unreachable("unexpected module ownership kind");
589}
590
591static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
592 // Internal linkage declarations within a module interface unit are modeled
593 // as "module-internal linkage", which means that they have internal linkage
594 // formally but can be indirectly accessed from outside the module via inline
595 // functions and templates defined within the module.
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000596 if (isInModulePurview(D))
597 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
Richard Smith1283e982017-07-07 20:04:28 +0000598
599 return LinkageInfo::internal();
600}
601
602static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
603 // C++ Modules TS [basic.link]/6.8:
604 // - A name declared at namespace scope that does not have internal linkage
605 // by the previous rules and that is introduced by a non-exported
606 // declaration has module linkage.
Richard Smith96451e32019-04-19 02:46:50 +0000607 if (isInModulePurview(D) && !isExportedFromModuleInterfaceUnit(
608 cast<NamedDecl>(D->getCanonicalDecl())))
Richard Smitha5bbbfe2019-04-18 21:12:54 +0000609 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
Richard Smith1283e982017-07-07 20:04:28 +0000610
611 return LinkageInfo::external();
612}
613
Richard Smithbb750682019-04-26 01:51:08 +0000614static StorageClass getStorageClass(const Decl *D) {
615 if (auto *TD = dyn_cast<TemplateDecl>(D))
616 D = TD->getTemplatedDecl();
Hans Wennborgb0dbc9612019-05-14 10:11:33 +0000617 if (D) {
618 if (auto *VD = dyn_cast<VarDecl>(D))
619 return VD->getStorageClass();
620 if (auto *FD = dyn_cast<FunctionDecl>(D))
621 return FD->getStorageClass();
Richard Smithbb750682019-04-26 01:51:08 +0000622 }
623 return SC_None;
624}
625
George Burgess IV99db3ea2017-08-09 04:02:49 +0000626LinkageInfo
627LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000628 LVComputationKind computation,
629 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000630 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000631 "Not a name having namespace scope");
632 ASTContext &Context = D->getASTContext();
633
634 // C++ [basic.link]p3:
635 // A name having namespace scope (3.3.6) has internal linkage if it
636 // is the name of
Ilya Biryukovb8292c92019-04-24 08:50:24 +0000637
Hans Wennborgb0dbc9612019-05-14 10:11:33 +0000638 if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
Richard Smithbb750682019-04-26 01:51:08 +0000639 // - a variable, variable template, function, or function template
640 // that is explicitly declared static; or
641 // (This bullet corresponds to C99 6.2.2p3.)
642 return getInternalLinkageFor(D);
643 }
644
645 if (const auto *Var = dyn_cast<VarDecl>(D)) {
646 // - a non-template variable of non-volatile const-qualified type, unless
647 // - it is explicitly declared extern, or
648 // - it is inline or exported, or
649 // - it was previously declared and the prior declaration did not have
650 // internal linkage
651 // (There is no equivalent in C99.)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000652 if (Context.getLangOpts().CPlusPlus &&
Fangrui Song6907ce22018-07-30 19:24:48 +0000653 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000654 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000655 !Var->isInline() &&
Richard Smithbb750682019-04-26 01:51:08 +0000656 !isExportedFromModuleInterfaceUnit(Var) &&
657 !isa<VarTemplateSpecializationDecl>(Var) &&
658 !Var->getDescribedVarTemplate()) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000659 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000660 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000661 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000662
663 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000664 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000665 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000666 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000667 }
668
669 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
670 PrevVar = PrevVar->getPreviousDecl()) {
671 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
672 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000673 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000674 // Explicitly declared static.
675 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000676 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000677 }
David Majnemer18fac3b2014-12-10 22:58:14 +0000678 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
679 // - a data member of an anonymous union.
680 const VarDecl *VD = IFD->getVarDecl();
681 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000682 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000683 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000684 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000685
Richard Smithbb750682019-04-26 01:51:08 +0000686 // FIXME: This gives internal linkage to names that should have no linkage
687 // (those not covered by [basic.link]p6).
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000688 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000689 const auto *Var = dyn_cast<VarDecl>(D);
690 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000691 // FIXME: The check for extern "C" here is not justified by the standard
692 // wording, but we retain it from the pre-DR1113 model to avoid breaking
693 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000694 //
695 // C++11 [basic.link]p4:
696 // An unnamed namespace or a namespace declared directly or indirectly
697 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000698 if ((!Var || !isFirstInExternCContext(Var)) &&
699 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000700 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000701 }
John McCallb7139c42010-10-28 04:18:25 +0000702
John McCall457a04e2010-10-22 21:05:15 +0000703 // Set up the defaults.
704
705 // C99 6.2.2p5:
706 // If the declaration of an identifier for an object has file
707 // scope and no storage-class specifier, its linkage is
708 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000709 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000710
John McCalld041a9b2013-02-20 01:54:26 +0000711 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000712 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000713 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000714 } else {
715 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000716 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000717 for (const DeclContext *DC = D->getDeclContext();
718 !isa<TranslationUnitDecl>(DC);
719 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000720 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000721 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000722 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000723 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000724 break;
725 }
726 }
727 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000728
John McCalldf25c432013-02-16 00:17:33 +0000729 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000730 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000731 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000732 Visibility globalVisibility =
733 computation.isValueVisibility()
734 ? Context.getLangOpts().getValueVisibilityMode()
735 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000736 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000737
738 // If we're paying attention to global visibility, apply
739 // -finline-visibility-hidden if this is an inline method.
740 if (useInlineVisibilityHidden(D))
Reid Klecknera52d1512018-10-10 21:59:56 +0000741 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
John McCalldf25c432013-02-16 00:17:33 +0000742 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000743 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000744
Douglas Gregorf73b2822009-11-25 22:24:25 +0000745 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000746
Richard Smithbb750682019-04-26 01:51:08 +0000747 // A name having namespace scope that has not been given internal linkage
748 // above and that is the name of
749 // [...bullets...]
750 // has its linkage determined as follows:
751 // - if the enclosing namespace has internal linkage, the name has
752 // internal linkage; [handled above]
753 // - otherwise, if the declaration of the name is attached to a named
754 // module and is not exported, the name has module linkage;
755 // - otherwise, the name has external linkage.
756 // LV is currently set up to handle the last two bullets.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000757 //
Richard Smithbb750682019-04-26 01:51:08 +0000758 // The bullets are:
759
760 // - a variable; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000761 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000762 // GCC applies the following optimization to variables and static
763 // data members, but not to functions:
764 //
John McCall457a04e2010-10-22 21:05:15 +0000765 // Modify the variable's LV by the LV of its type unless this is
766 // C or extern "C". This follows from [basic.link]p9:
767 // A type without linkage shall not be used as the type of a
768 // variable or function with external linkage unless
769 // - the entity has C language linkage, or
770 // - the entity is declared within an unnamed namespace, or
771 // - the entity is not used or is defined in the same
772 // translation unit.
773 // and [basic.link]p10:
774 // ...the types specified by all declarations referring to a
775 // given variable or function shall be identical...
776 // C does not have an equivalent rule.
777 //
John McCall5fe84122010-10-26 04:59:26 +0000778 // Ignore this if we've got an explicit attribute; the user
779 // probably knows what they're doing.
780 //
John McCall457a04e2010-10-22 21:05:15 +0000781 // Note that we don't want to make the variable non-external
782 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000783 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
784 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000785 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000786 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000787 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000788 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000789 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000790 }
791
John McCall23032652010-11-02 18:38:13 +0000792 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000793 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000794
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000795 // Note that Sema::MergeVarDecl already takes care of implementing
796 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
797 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000798
Larisse Voufo5899e192014-07-02 23:08:34 +0000799 // As per function and class template specializations (below),
800 // consider LV for the template and template arguments. We're at file
801 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000802 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000803 mergeTemplateLV(LV, spec, computation);
804 }
805
Richard Smithbb750682019-04-26 01:51:08 +0000806 // - a function; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000807 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000808 // In theory, we can modify the function's LV by the LV of its
809 // type unless it has C linkage (see comment above about variables
810 // for justification). In practice, GCC doesn't do this, so it's
811 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000812
John McCall23032652010-11-02 18:38:13 +0000813 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000814 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000815
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000816 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
817 // merging storage classes and visibility attributes, so we don't have to
818 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000819
John McCallf768aa72011-02-10 06:50:24 +0000820 // In C++, then if the type of the function uses a type with
821 // unique-external linkage, it's not legally usable from outside
822 // this translation unit. However, we should use the C linkage
823 // rules instead for extern "C" declarations.
Richard Smith99f54792018-01-03 02:34:35 +0000824 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000825 // Only look at the type-as-written. Otherwise, deducing the return type
826 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000827 QualType TypeAsWritten = Function->getType();
828 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
829 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000830 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000831 return LinkageInfo::uniqueExternal();
832 }
John McCallf768aa72011-02-10 06:50:24 +0000833
John McCall5f46c482013-02-21 23:42:58 +0000834 // Consider LV from the template and the template arguments.
835 // We're at file scope, so we do not need to worry about nested
836 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000837 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000838 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000839 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000840 }
841
Douglas Gregorf73b2822009-11-25 22:24:25 +0000842 // - a named class (Clause 9), or an unnamed class defined in a
843 // typedef declaration in which the class has the typedef name
844 // for linkage purposes (7.1.3); or
845 // - a named enumeration (7.2), or an unnamed enumeration
846 // defined in a typedef declaration in which the enumeration
847 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000848 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000849 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000850 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000851 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000852
John McCall457a04e2010-10-22 21:05:15 +0000853 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000854 // linkage of the template and template arguments. We're at file
855 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000856 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000857 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000858 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000859
Richard Smithbb750682019-04-26 01:51:08 +0000860 // FIXME: This is not part of the C++ standard any more.
861 // - an enumerator belonging to an enumeration with external linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000862 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000863 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000864 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000865 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000866 return LinkageInfo::none();
867 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000868
Richard Smithbb750682019-04-26 01:51:08 +0000869 // - a template
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000870 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000871 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000872 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000873 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000874 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
875
Richard Smithbb750682019-04-26 01:51:08 +0000876 // An unnamed namespace or a namespace declared directly or indirectly
877 // within an unnamed namespace has internal linkage. All other namespaces
878 // have external linkage.
Richard Smith1283e982017-07-07 20:04:28 +0000879 //
880 // We handled names in anonymous namespaces above.
881 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000882 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000883
John McCall457a04e2010-10-22 21:05:15 +0000884 // By extension, we assign external linkage to Objective-C
885 // interfaces.
886 } else if (isa<ObjCInterfaceDecl>(D)) {
887 // fallout
888
Richard Smith97135cc2015-11-12 22:19:45 +0000889 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
890 // A typedef declaration has linkage if it gives a type a name for
891 // linkage purposes.
892 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
893 return LinkageInfo::none();
894
John McCall457a04e2010-10-22 21:05:15 +0000895 // Everything not covered here has no linkage.
896 } else {
John McCallc273f242010-10-30 11:50:40 +0000897 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000898 }
899
Richard Smithc445d5d2017-10-03 01:58:15 +0000900 // If we ended up with non-externally-visible linkage, visibility should
John McCall457a04e2010-10-22 21:05:15 +0000901 // always be default.
Richard Smithc445d5d2017-10-03 01:58:15 +0000902 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola4a5da442013-02-27 02:56:45 +0000903 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000904
Alexey Bataevbbc328c2019-11-21 11:30:43 -0500905 // Mark the symbols as hidden when compiling for the device.
906 if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice)
907 LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
908
John McCall457a04e2010-10-22 21:05:15 +0000909 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000910}
911
George Burgess IV99db3ea2017-08-09 04:02:49 +0000912LinkageInfo
913LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000914 LVComputationKind computation,
915 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000916 // Only certain class members have linkage. Note that fields don't
917 // really have linkage, but it's convenient to say they do for the
918 // purposes of calculating linkage of pointer-to-data-member
919 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000920 //
921 // Templates also don't officially have linkage, but since we ignore
922 // the C++ standard and look at template arguments when determining
923 // linkage and visibility of a template specialization, we might hit
924 // a template template argument that way. If we do, we need to
925 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000926 if (!(isa<CXXMethodDecl>(D) ||
927 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000928 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000929 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000930 isa<TagDecl>(D) ||
931 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000932 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000933
John McCall07072662010-11-02 01:45:15 +0000934 LinkageInfo LV;
935
John McCall07072662010-11-02 01:45:15 +0000936 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000937 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000938 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000939 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000940 // If we're paying attention to global visibility, apply
941 // -finline-visibility-hidden if this is an inline method.
942 //
943 // Note that we do this before merging information about
944 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000945 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Reid Klecknera52d1512018-10-10 21:59:56 +0000946 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
John McCall07072662010-11-02 01:45:15 +0000947 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000948
949 // If this class member has an explicit visibility attribute, the only
950 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000951 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000952 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000953 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000954 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000955
John McCall5f46c482013-02-21 23:42:58 +0000956 LinkageInfo classLV =
957 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Richard Smithcdb06f22017-09-23 04:02:17 +0000958 // The member has the same linkage as the class. If that's not externally
959 // visible, we don't need to compute anything about the linkage.
960 // FIXME: If we're only computing linkage, can we bail out here?
Rafael Espindolae6190db2013-05-28 02:22:10 +0000961 if (!isExternallyVisible(classLV.getLinkage()))
Richard Smithcdb06f22017-09-23 04:02:17 +0000962 return classLV;
Rafael Espindolae6190db2013-05-28 02:22:10 +0000963
964
John McCall5f46c482013-02-21 23:42:58 +0000965 // Otherwise, don't merge in classLV yet, because in certain cases
966 // we need to completely ignore the visibility from it.
967
968 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000969 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000970
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000971 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000972 // Only look at the type-as-written. Otherwise, deducing the return type
973 // of a function could change its linkage.
974 QualType TypeAsWritten = MD->getType();
975 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
976 TypeAsWritten = TSI->getType();
977 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
978 return LinkageInfo::uniqueExternal();
979
John McCall457a04e2010-10-22 21:05:15 +0000980 // If this is a method template specialization, use the linkage for
981 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000982 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000983 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000984 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000985 if (spec->isExplicitSpecialization()) {
986 explicitSpecSuppressor = MD;
987 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
988 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
989 }
990 } else if (isExplicitMemberSpecialization(MD)) {
991 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000992 }
John McCall457a04e2010-10-22 21:05:15 +0000993
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000994 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
995 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000996 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000997 if (spec->isExplicitSpecialization()) {
998 explicitSpecSuppressor = spec;
999 } else {
1000 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1001 if (isExplicitMemberSpecialization(temp)) {
1002 explicitSpecSuppressor = temp->getTemplatedDecl();
1003 }
1004 }
1005 } else if (isExplicitMemberSpecialization(RD)) {
1006 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +00001007 }
1008
John McCall37bb6c92010-10-29 22:22:43 +00001009 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001010 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1011 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +00001012 mergeTemplateLV(LV, spec, computation);
1013
John McCall36cd5cc2010-10-30 09:18:49 +00001014 // Modify the variable's linkage by its type, but ignore the
1015 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +00001016 if (!IgnoreVarTypeLinkage) {
1017 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1018 // FIXME: If the type's linkage is not externally visible, we can
1019 // give this static data member UniqueExternalLinkage.
1020 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1021 LV.mergeVisibility(typeLV);
1022 LV.mergeExternalVisibility(typeLV);
1023 }
John McCall5f46c482013-02-21 23:42:58 +00001024
1025 if (isExplicitMemberSpecialization(VD)) {
1026 explicitSpecSuppressor = VD;
1027 }
John McCalldf25c432013-02-16 00:17:33 +00001028
1029 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001030 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001031 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +00001032 (!LV.isVisibilityExplicit() &&
1033 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +00001034 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +00001035 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001036 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +00001037 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +00001038
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001039 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +00001040 if (isExplicitMemberSpecialization(redeclTemp)) {
1041 explicitSpecSuppressor = temp->getTemplatedDecl();
1042 }
1043 }
John McCall37bb6c92010-10-29 22:22:43 +00001044 }
1045
John McCall5f46c482013-02-21 23:42:58 +00001046 // We should never be looking for an attribute directly on a template.
1047 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1048
1049 // If this member is an explicit member specialization, and it has
1050 // an explicit attribute, ignore visibility from the parent.
1051 bool considerClassVisibility = true;
1052 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +00001053 // optimization: hasDVA() is true only with explicit visibility.
1054 LV.isVisibilityExplicit() &&
1055 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +00001056 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1057 considerClassVisibility = false;
1058 }
1059
1060 // Finally, merge in information from the class.
1061 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +00001062 return LV;
John McCall8823c652010-08-13 08:35:10 +00001063}
1064
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001065void NamedDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00001066
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001067bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001068 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001069 return true;
John McCalld396b972011-02-08 19:01:05 +00001070
Richard Smithfbe7b462017-09-22 02:22:32 +00001071 Linkage L = LinkageComputer{}
1072 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1073 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +00001074 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001075}
1076
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001077ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1078 StringRef name = getName();
1079 if (name.empty()) return SFF_None;
Fangrui Song6907ce22018-07-30 19:24:48 +00001080
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001081 if (name.front() == 'C')
1082 if (name == "CFStringCreateWithFormat" ||
1083 name == "CFStringCreateWithFormatAndArguments" ||
1084 name == "CFStringAppendFormat" ||
1085 name == "CFStringAppendFormatAndArguments")
1086 return SFF_CFString;
1087 return SFF_None;
1088}
1089
Rafael Espindola3ae00052013-05-13 00:12:11 +00001090Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001091 // We don't care about visibility here, so ask for the cheapest
1092 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001093 return LinkageComputer{}
1094 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1095 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001096}
1097
John McCallc273f242010-10-30 11:50:40 +00001098LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001099 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001100}
Ted Kremenek926d8602010-04-20 23:15:35 +00001101
Rafael Espindola9ad61122013-11-26 16:09:08 +00001102static Optional<Visibility>
1103getExplicitVisibilityAux(const NamedDecl *ND,
1104 NamedDecl::ExplicitVisibilityKind kind,
1105 bool IsMostRecent) {
1106 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1107
Rafael Espindola3a52c442013-02-26 19:33:14 +00001108 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001109 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001110 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001111
Rafael Espindola3a52c442013-02-26 19:33:14 +00001112 // If this is a member class of a specialization of a class template
1113 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001114 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001115 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1116 if (InstantiatedFrom)
1117 return getVisibilityOf(InstantiatedFrom, kind);
1118 }
1119
1120 // If there wasn't explicit visibility there, and this is a
1121 // specialization of a class template, check for visibility
1122 // on the pattern.
Steven Wu79cbd112018-04-19 15:46:43 +00001123 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1124 // Walk all the template decl till this point to see if there are
1125 // explicit visibility attributes.
1126 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1127 while (TD != nullptr) {
1128 auto Vis = getVisibilityOf(TD, kind);
1129 if (Vis != None)
1130 return Vis;
1131 TD = TD->getPreviousDecl();
1132 }
1133 return None;
1134 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001135
1136 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001137 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001138 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1139 if (MostRecent != ND)
1140 return getExplicitVisibilityAux(MostRecent, kind, true);
1141 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001142
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001143 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001144 if (Var->isStaticDataMember()) {
1145 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1146 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001147 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001148 }
1149
David Majnemer35b02bc2014-04-29 07:32:26 +00001150 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1151 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1152 kind);
1153
David Blaikie7a30dc52013-02-21 01:47:18 +00001154 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001155 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001156 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001157 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001158 // If the function is a specialization of a template with an
1159 // explicit visibility attribute, use that.
1160 if (FunctionTemplateSpecializationInfo *templateInfo
1161 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001162 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1163 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001164
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001165 // If the function is a member of a specialization of a class template
1166 // and the corresponding decl has explicit visibility, use that.
1167 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1168 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001169 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001170
David Blaikie7a30dc52013-02-21 01:47:18 +00001171 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001172 }
1173
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001174 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001175 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001176 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001177
David Blaikie7a30dc52013-02-21 01:47:18 +00001178 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001179}
1180
Rafael Espindola9ad61122013-11-26 16:09:08 +00001181Optional<Visibility>
1182NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1183 return getExplicitVisibilityAux(this, kind, false);
1184}
1185
George Burgess IV99db3ea2017-08-09 04:02:49 +00001186LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1187 Decl *ContextDecl,
1188 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001189 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001190 const NamedDecl *Owner;
1191 if (!ContextDecl)
1192 Owner = dyn_cast<NamedDecl>(DC);
1193 else if (isa<ParmVarDecl>(ContextDecl))
1194 Owner =
1195 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1196 else
1197 Owner = cast<NamedDecl>(ContextDecl);
1198
Richard Smithc95d2c52017-09-22 04:25:05 +00001199 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001200 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001201
1202 // If the owner has a deduced type, we need to skip querying the linkage and
1203 // visibility of that type, because it might involve this closure type. The
1204 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1205 // than NoLinkage when we don't strictly need to, which is benign.
1206 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001207 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001208 VD && VD->getType()->getContainedDeducedType()
1209 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1210 : getLVForDecl(Owner, computation);
1211
Richard Smith7ff83042017-09-22 04:33:20 +00001212 // A lambda never formally has linkage. But if the owner is externally
1213 // visible, then the lambda is too. We apply the same rules to blocks.
1214 if (!isExternallyVisible(OwnerLV.getLinkage()))
1215 return LinkageInfo::none();
1216 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1217 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001218}
1219
George Burgess IV99db3ea2017-08-09 04:02:49 +00001220LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1221 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001222 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001223 if (Function->isInAnonymousNamespace() &&
Richard Smith99f54792018-01-03 02:34:35 +00001224 !isFirstInExternCContext(Function))
Richard Smithdf963a32017-09-22 22:21:44 +00001225 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001226
1227 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001228 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001229 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001230
1231 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001232 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001233 if (Optional<Visibility> Vis =
1234 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001235 LV.mergeVisibility(*Vis, true);
1236 }
1237
1238 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1239 // merging storage classes and visibility attributes, so we don't have to
1240 // look at previous decls in here.
1241
1242 return LV;
1243 }
1244
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001245 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001246 if (Var->hasExternalStorage()) {
Richard Smith99f54792018-01-03 02:34:35 +00001247 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
Richard Smithdf963a32017-09-22 22:21:44 +00001248 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001249
John McCalldf25c432013-02-16 00:17:33 +00001250 LinkageInfo LV;
1251 if (Var->getStorageClass() == SC_PrivateExtern)
1252 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001253 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001254 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001255 LV.mergeVisibility(*Vis, true);
1256 }
1257
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001258 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1259 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1260 if (PrevLV.getLinkage())
1261 LV.setLinkage(PrevLV.getLinkage());
1262 LV.mergeVisibility(PrevLV);
1263 }
1264
John McCalldf25c432013-02-16 00:17:33 +00001265 return LV;
1266 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001267
1268 if (!Var->isStaticLocal())
1269 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001270 }
1271
Rafael Espindolaa4184182013-06-17 20:04:51 +00001272 ASTContext &Context = D->getASTContext();
1273 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001274 return LinkageInfo::none();
1275
Eli Friedman7e346a82013-07-01 20:22:57 +00001276 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001277 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001278 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001279
Eli Friedman7e346a82013-07-01 20:22:57 +00001280 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001281 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001282 if (!BD->getBlockManglingNumber())
1283 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001284
Eli Friedman7e346a82013-07-01 20:22:57 +00001285 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1286 BD->getBlockManglingContextDecl(), computation);
1287 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001288 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001289 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001290 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001291 return LinkageInfo::none();
1292
Hiroshi Inoue03ff37d2018-08-22 05:43:27 +00001293 // If a function is hidden by -fvisibility-inlines-hidden option and
1294 // is not explicitly attributed as a hidden function,
1295 // we should not make static local variables in the function hidden.
Eli Friedman7e346a82013-07-01 20:22:57 +00001296 LV = getLVForDecl(FD, computation);
Reid Klecknera52d1512018-10-10 21:59:56 +00001297 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1298 !LV.isVisibilityExplicit()) {
1299 assert(cast<VarDecl>(D)->isStaticLocal());
1300 // If this was an implicitly hidden inline method, check again for
1301 // explicit visibility on the parent class, and use that for static locals
1302 // if present.
1303 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1304 LV = getLVForDecl(MD->getParent(), computation);
1305 if (!LV.isVisibilityExplicit()) {
1306 Visibility globalVisibility =
1307 computation.isValueVisibility()
1308 ? Context.getLangOpts().getValueVisibilityMode()
1309 : Context.getLangOpts().getTypeVisibilityMode();
1310 return LinkageInfo(VisibleNoLinkage, globalVisibility,
1311 /*visibilityExplicit=*/false);
1312 }
1313 }
Eli Friedman7e346a82013-07-01 20:22:57 +00001314 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001315 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001316 return LinkageInfo::none();
1317 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1318 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001319}
1320
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001321static inline const CXXRecordDecl*
1322getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1323 const CXXRecordDecl *Ret = Record;
1324 while (Record && Record->isLambda()) {
1325 Ret = Record;
1326 if (!Record->getParent()) break;
1327 // Get the Containing Class of this Lambda Class
1328 Record = dyn_cast_or_null<CXXRecordDecl>(
1329 Record->getParent()->getParent());
1330 }
1331 return Ret;
1332}
1333
George Burgess IV99db3ea2017-08-09 04:02:49 +00001334LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001335 LVComputationKind computation,
1336 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001337 // Internal_linkage attribute overrides other considerations.
1338 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001339 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001340
Ted Kremenek926d8602010-04-20 23:15:35 +00001341 // Objective-C: treat all Objective-C declarations as having external
1342 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001343 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001344 default:
1345 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001346
1347 // Per C++ [basic.link]p2, only the names of objects, references,
1348 // functions, types, templates, namespaces, and values ever have linkage.
1349 //
1350 // Note that the name of a typedef, namespace alias, using declaration,
1351 // and so on are not the name of the corresponding type, namespace, or
1352 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001353 case Decl::ImplicitParam:
1354 case Decl::Label:
1355 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001356 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001357 case Decl::Using:
1358 case Decl::UsingShadow:
1359 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001360 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001361
Richard Smith26210db2015-11-13 03:52:13 +00001362 case Decl::EnumConstant:
1363 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001364 if (D->getASTContext().getLangOpts().CPlusPlus)
1365 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1366 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001367
Richard Smith97135cc2015-11-12 22:19:45 +00001368 case Decl::Typedef:
1369 case Decl::TypeAlias:
1370 // A typedef declaration has linkage if it gives a type a name for
1371 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001372 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001373 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1374 return LinkageInfo::none();
1375 break;
1376
John McCall457a04e2010-10-22 21:05:15 +00001377 case Decl::TemplateTemplateParm: // count these as external
1378 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001379 case Decl::ObjCAtDefsField:
1380 case Decl::ObjCCategory:
1381 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001382 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001383 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001384 case Decl::ObjCMethod:
1385 case Decl::ObjCProperty:
1386 case Decl::ObjCPropertyImpl:
1387 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001388 return getExternalLinkageFor(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00001389
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001390 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001391 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001392 if (Record->isLambda()) {
Michael Liao243ebfb2019-10-19 00:15:19 +00001393 if (Record->hasKnownLambdaInternalLinkage() ||
1394 !Record->getLambdaManglingNumber()) {
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001395 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001396 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001397 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001398
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001399 // This lambda has its linkage/visibility determined:
Fangrui Song6907ce22018-07-30 19:24:48 +00001400 // - either by the outermost lambda if that lambda has no mangling
1401 // number.
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001402 // - or by the parent of the outer most lambda
Fangrui Song6907ce22018-07-30 19:24:48 +00001403 // This prevents infinite recursion in settings such as nested lambdas
1404 // used in NSDMI's, for e.g.
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001405 // struct L {
1406 // int t{};
Fangrui Song6907ce22018-07-30 19:24:48 +00001407 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001408 // };
Fangrui Song6907ce22018-07-30 19:24:48 +00001409 const CXXRecordDecl *OuterMostLambda =
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001410 getOutermostEnclosingLambda(Record);
Michael Liao243ebfb2019-10-19 00:15:19 +00001411 if (OuterMostLambda->hasKnownLambdaInternalLinkage() ||
1412 !OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001413 return getInternalLinkageFor(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00001414
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001415 return getLVForClosure(
1416 OuterMostLambda->getDeclContext()->getRedeclContext(),
1417 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001418 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001419
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001420 break;
1421 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001422 }
1423
Douglas Gregorf73b2822009-11-25 22:24:25 +00001424 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001425 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001426 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Fangrui Song6907ce22018-07-30 19:24:48 +00001427
Douglas Gregorf73b2822009-11-25 22:24:25 +00001428 // C++ [basic.link]p5:
1429 // In addition, a member function, static data member, a named
1430 // class or enumeration of class scope, or an unnamed class or
1431 // enumeration defined in a class-scope typedef declaration such
1432 // that the class or enumeration has the typedef name for linkage
1433 // purposes (7.1.3), has external linkage if the name of the class
1434 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001435 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001436 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001437
1438 // C++ [basic.link]p6:
1439 // The name of a function declared in block scope and the name of
1440 // an object declared by a block scope extern declaration have
1441 // linkage. If there is a visible declaration of an entity with
1442 // linkage having the same name and type, ignoring entities
1443 // declared outside the innermost enclosing namespace scope, the
1444 // block scope declaration declares that same entity and receives
1445 // the linkage of the previous declaration. If there is more than
1446 // one such matching entity, the program is ill-formed. Otherwise,
1447 // if no matching entity is found, the block scope entity receives
1448 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001449 if (D->getDeclContext()->isFunctionOrMethod())
1450 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001451
1452 // C++ [basic.link]p6:
1453 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001454 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001455}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001456
George Burgess IV99db3ea2017-08-09 04:02:49 +00001457/// getLVForDecl - Get the linkage and visibility for the given declaration.
1458LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1459 LVComputationKind computation) {
1460 // Internal_linkage attribute overrides other considerations.
1461 if (D->hasAttr<InternalLinkageAttr>())
1462 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001463
Richard Smithfbe7b462017-09-22 02:22:32 +00001464 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001465 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001466
George Burgess IV35cb4f82017-08-09 04:12:17 +00001467 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1468 return *LI;
1469
George Burgess IV99db3ea2017-08-09 04:02:49 +00001470 LinkageInfo LV = computeLVForDecl(D, computation);
1471 if (D->hasCachedLinkage())
1472 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001473
George Burgess IV99db3ea2017-08-09 04:02:49 +00001474 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001475 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001476
1477#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001478 // In C (because of gnu inline) and in c++ with microsoft extensions an
1479 // static can follow an extern, so we can have two decls with different
1480 // linkages.
1481 const LangOptions &Opts = D->getASTContext().getLangOpts();
1482 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1483 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001484
George Burgess IV99db3ea2017-08-09 04:02:49 +00001485 // We have just computed the linkage for this decl. By induction we know
1486 // that all other computed linkages match, check that the one we just
1487 // computed also does.
1488 NamedDecl *Old = nullptr;
1489 for (auto I : D->redecls()) {
1490 auto *T = cast<NamedDecl>(I);
1491 if (T == D)
1492 continue;
1493 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1494 Old = T;
1495 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001496 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001497 }
1498 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001499#endif
1500
George Burgess IV99db3ea2017-08-09 04:02:49 +00001501 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001502}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001503
George Burgess IV99db3ea2017-08-09 04:02:49 +00001504LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001505 return getLVForDecl(D,
1506 LVComputationKind(usesTypeVisibility(D)
1507 ? NamedDecl::VisibilityForType
1508 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001509}
1510
Richard Smithbecb92d2017-10-10 22:33:17 +00001511Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
Richard Smithdd8b5332017-09-04 05:37:53 +00001512 Module *M = getOwningModule();
1513 if (!M)
1514 return nullptr;
1515
1516 switch (M->Kind) {
1517 case Module::ModuleMapModule:
1518 // Module map modules have no special linkage semantics.
1519 return nullptr;
1520
1521 case Module::ModuleInterfaceUnit:
1522 return M;
1523
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001524 case Module::GlobalModuleFragment: {
Richard Smithdd8b5332017-09-04 05:37:53 +00001525 // External linkage declarations in the global module have no owning module
1526 // for linkage purposes. But internal linkage declarations in the global
1527 // module fragment of a particular module are owned by that module for
1528 // linkage purposes.
Richard Smithbecb92d2017-10-10 22:33:17 +00001529 if (IgnoreLinkage)
1530 return nullptr;
1531 bool InternalLinkage;
1532 if (auto *ND = dyn_cast<NamedDecl>(this))
1533 InternalLinkage = !ND->hasExternalFormalLinkage();
1534 else {
1535 auto *NSD = dyn_cast<NamespaceDecl>(this);
1536 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1537 isInAnonymousNamespace();
1538 }
1539 return InternalLinkage ? M->Parent : nullptr;
Richard Smithdd8b5332017-09-04 05:37:53 +00001540 }
Richard Smitha5bbbfe2019-04-18 21:12:54 +00001541
1542 case Module::PrivateModuleFragment:
1543 // The private module fragment is part of its containing module for linkage
1544 // purposes.
1545 return M->Parent;
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001546 }
Richard Smithdd8b5332017-09-04 05:37:53 +00001547
1548 llvm_unreachable("unknown module kind");
1549}
1550
Richard Smith7873de02016-08-11 22:25:46 +00001551void NamedDecl::printName(raw_ostream &os) const {
1552 os << Name;
1553}
1554
Douglas Gregor2ada0482009-02-04 17:27:36 +00001555std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001556 std::string QualName;
1557 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001558 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001559 return OS.str();
1560}
1561
1562void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1563 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1564}
1565
1566void NamedDecl::printQualifiedName(raw_ostream &OS,
1567 const PrintingPolicy &P) const {
Ilya Biryukov66482232019-09-25 15:46:04 +00001568 if (getDeclContext()->isFunctionOrMethod()) {
1569 // We do not print '(anonymous)' for function parameters without name.
1570 printName(OS);
1571 return;
1572 }
1573 printNestedNameSpecifier(OS, P);
1574 if (getDeclName() || isa<DecompositionDecl>(this))
1575 OS << *this;
1576 else
1577 OS << "(anonymous)";
1578}
1579
1580void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1581 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1582}
1583
1584void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1585 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001586 const DeclContext *Ctx = getDeclContext();
1587
David Goldman19d21852019-04-04 20:13:22 +00001588 // For ObjC methods and properties, look through categories and use the
1589 // interface as context.
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001590 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1591 if (auto *ID = MD->getClassInterface())
1592 Ctx = ID;
David Goldman19d21852019-04-04 20:13:22 +00001593 if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1594 if (auto *MD = PD->getGetterMethodDecl())
1595 if (auto *ID = MD->getClassInterface())
1596 Ctx = ID;
1597 }
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001598
Ilya Biryukov66482232019-09-25 15:46:04 +00001599 if (Ctx->isFunctionOrMethod())
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001600 return;
Douglas Gregor2ada0482009-02-04 17:27:36 +00001601
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001602 using ContextsTy = SmallVector<const DeclContext *, 8>;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001603 ContextsTy Contexts;
1604
Sam McCall34f9d3f2018-02-02 13:34:47 +00001605 // Collect named contexts.
1606 while (Ctx) {
1607 if (isa<NamedDecl>(Ctx))
1608 Contexts.push_back(Ctx);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001609 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001610 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001611
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001612 for (const DeclContext *DC : llvm::reverse(Contexts)) {
David Majnemerf7e36092016-06-23 00:15:04 +00001613 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001614 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001615 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Serge Pavlov03e672c2017-11-28 16:14:14 +00001616 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001617 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001618 if (P.SuppressUnwrittenScope &&
1619 (ND->isAnonymousNamespace() || ND->isInline()))
1620 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001621 if (ND->isAnonymousNamespace()) {
1622 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1623 : "(anonymous namespace)");
1624 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001625 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001626 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001627 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001628 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001629 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001630 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001631 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001632 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001633 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001634 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001635 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001636
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001637 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001638 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001639 unsigned NumParams = FD->getNumParams();
1640 for (unsigned i = 0; i < NumParams; ++i) {
1641 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001642 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001643 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001644 }
1645
1646 if (FT->isVariadic()) {
1647 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001648 OS << ", ";
1649 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001650 }
1651 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001652 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001653 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001654 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1655 // enumerator is declared in the scope that immediately contains
1656 // the enum-specifier. Each scoped enumerator is declared in the
1657 // scope of the enumeration.
Paul Robinsonf1838482017-12-21 21:47:22 +00001658 // For the case of unscoped enumerator, do not include in the qualified
Paul Robinsond1c3dd82017-12-26 18:01:19 +00001659 // name any information about its enum enclosing scope, as its visibility
Paul Robinsonf1838482017-12-21 21:47:22 +00001660 // is global.
1661 if (ED->isScoped())
Alexander Kornienko4f355322015-11-09 16:45:17 +00001662 OS << *ED;
1663 else
1664 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001665 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001666 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001667 }
1668 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001669 }
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001670}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001671
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001672void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1673 const PrintingPolicy &Policy,
1674 bool Qualified) const {
1675 if (Qualified)
1676 printQualifiedName(OS, Policy);
1677 else
1678 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001679}
1680
Richard Smithe8292b12015-02-10 03:28:10 +00001681template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1682 return true;
1683}
1684static bool isRedeclarableImpl(...) { return false; }
1685static bool isRedeclarable(Decl::Kind K) {
1686 switch (K) {
1687#define DECL(Type, Base) \
1688 case Decl::Type: \
1689 return isRedeclarableImpl((Type##Decl *)nullptr);
1690#define ABSTRACT_DECL(DECL)
1691#include "clang/AST/DeclNodes.inc"
1692 }
1693 llvm_unreachable("unknown decl kind");
1694}
1695
1696bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001697 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1698
Richard Smithfe620d22015-03-05 23:24:12 +00001699 // Never replace one imported declaration with another; we need both results
1700 // when re-exporting.
1701 if (OldD->isFromASTFile() && isFromASTFile())
1702 return false;
1703
Richard Smith5cd86f82015-11-03 03:13:11 +00001704 // A kind mismatch implies that the declaration is not replaced.
1705 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001706 return false;
1707
Richard Smith5cd86f82015-11-03 03:13:11 +00001708 // For method declarations, we never replace. (Why?)
1709 if (isa<ObjCMethodDecl>(this))
1710 return false;
1711
1712 // For parameters, pick the newer one. This is either an error or (in
1713 // Objective-C) permitted as an extension.
1714 if (isa<ParmVarDecl>(this))
1715 return true;
1716
Richard Smithe8292b12015-02-10 03:28:10 +00001717 // Inline namespaces can give us two declarations with the same
1718 // name and kind in the same scope but different contexts; we should
1719 // keep both declarations in this case.
1720 if (!this->getDeclContext()->getRedeclContext()->Equals(
1721 OldD->getDeclContext()->getRedeclContext()))
1722 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001723
Richard Smith5cd86f82015-11-03 03:13:11 +00001724 // Using declarations can be replaced if they import the same name from the
1725 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001726 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001727 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001728 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001729 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001730 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001731 }
Richard Smithe8292b12015-02-10 03:28:10 +00001732 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001733 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001734 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001735 Context.getCanonicalNestedNameSpecifier(
1736 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1737 }
1738
Richard Smith5cd86f82015-11-03 03:13:11 +00001739 if (isRedeclarable(getKind())) {
1740 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1741 return false;
1742
1743 if (IsKnownNewer)
1744 return true;
1745
Richard Smithe8292b12015-02-10 03:28:10 +00001746 // Check whether this is actually newer than OldD. We want to keep the
1747 // newer declaration. This loop will usually only iterate once, because
1748 // OldD is usually the previous declaration.
1749 for (auto D : redecls()) {
1750 if (D == OldD)
1751 break;
1752
1753 // If we reach the canonical declaration, then OldD is not actually older
1754 // than this one.
1755 //
1756 // FIXME: In this case, we should not add this decl to the lookup table.
1757 if (D->isCanonicalDecl())
1758 return false;
1759 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001760
1761 // It's a newer declaration of the same kind of declaration in the same
1762 // scope: we want this decl instead of the existing one.
1763 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001764 }
1765
Richard Smith5cd86f82015-11-03 03:13:11 +00001766 // In all other cases, we need to keep both declarations in case they have
1767 // different visibility. Any attempt to use the name will result in an
1768 // ambiguity if more than one is visible.
1769 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001770}
1771
Douglas Gregoreddf4332009-02-24 20:03:32 +00001772bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001773 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001774}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001775
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001776NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001777 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001778 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001779 ND = UD->getTargetDecl();
1780
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001781 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001782 return AD->getClassInterface();
1783
Richard Smithf2005d32015-12-29 23:34:32 +00001784 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1785 return AD->getNamespace();
1786
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001787 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001788}
1789
John McCalla8ae2222010-04-06 21:38:20 +00001790bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001791 if (!isCXXClassMember())
1792 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001793
John McCalla8ae2222010-04-06 21:38:20 +00001794 const NamedDecl *D = this;
1795 if (isa<UsingShadowDecl>(D))
1796 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1797
John McCall5e77d762013-04-16 07:28:30 +00001798 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001799 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001800 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001801 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001802 return false;
1803}
1804
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001805//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001806// DeclaratorDecl Implementation
1807//===----------------------------------------------------------------------===//
1808
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001809template <typename DeclT>
1810static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1811 if (decl->getNumTemplateParameterLists() > 0)
1812 return decl->getTemplateParameterList(0)->getTemplateLoc();
1813 else
1814 return decl->getInnerLocStart();
1815}
1816
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001817SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001818 TypeSourceInfo *TSI = getTypeSourceInfo();
1819 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001820 return SourceLocation();
1821}
1822
Mark de Weverf022a5a2020-01-01 17:23:19 +01001823SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1824 TypeSourceInfo *TSI = getTypeSourceInfo();
1825 if (TSI) return TSI->getTypeLoc().getEndLoc();
1826 return SourceLocation();
1827}
1828
Douglas Gregor14454802011-02-25 02:25:35 +00001829void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1830 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001831 // Make sure the extended decl info is allocated.
1832 if (!hasExtInfo()) {
1833 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001834 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001835 // Allocate external info struct.
1836 DeclInfo = new (getASTContext()) ExtInfo;
1837 // Restore savedTInfo into (extended) decl info.
1838 getExtInfo()->TInfo = savedTInfo;
1839 }
1840 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001841 getExtInfo()->QualifierLoc = QualifierLoc;
Saar Razb65b1f32020-01-09 15:07:51 +02001842 } else if (hasExtInfo()) {
John McCall3e11ebe2010-03-15 10:12:16 +00001843 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
Saar Razb65b1f32020-01-09 15:07:51 +02001844 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001845 }
1846}
1847
Saar Razb65b1f32020-01-09 15:07:51 +02001848void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1849 assert(TrailingRequiresClause);
1850 // Make sure the extended decl info is allocated.
1851 if (!hasExtInfo()) {
1852 // Save (non-extended) type source info pointer.
1853 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1854 // Allocate external info struct.
1855 DeclInfo = new (getASTContext()) ExtInfo;
1856 // Restore savedTInfo into (extended) decl info.
1857 getExtInfo()->TInfo = savedTInfo;
1858 }
1859 // Set requires clause info.
1860 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1861}
1862
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001863void DeclaratorDecl::setTemplateParameterListsInfo(
1864 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1865 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001866 // Make sure the extended decl info is allocated.
1867 if (!hasExtInfo()) {
1868 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001869 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001870 // Allocate external info struct.
1871 DeclInfo = new (getASTContext()) ExtInfo;
1872 // Restore savedTInfo into (extended) decl info.
1873 getExtInfo()->TInfo = savedTInfo;
1874 }
1875 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001876 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001877}
1878
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001879SourceLocation DeclaratorDecl::getOuterLocStart() const {
1880 return getTemplateOrInnerLocStart(this);
1881}
1882
Abramo Bagnaraea947882011-03-08 16:41:52 +00001883// Helper function: returns true if QT is or contains a type
1884// having a postfix component.
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001885static bool typeIsPostfix(QualType QT) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00001886 while (true) {
1887 const Type* T = QT.getTypePtr();
1888 switch (T->getTypeClass()) {
1889 default:
1890 return false;
1891 case Type::Pointer:
1892 QT = cast<PointerType>(T)->getPointeeType();
1893 break;
1894 case Type::BlockPointer:
1895 QT = cast<BlockPointerType>(T)->getPointeeType();
1896 break;
1897 case Type::MemberPointer:
1898 QT = cast<MemberPointerType>(T)->getPointeeType();
1899 break;
1900 case Type::LValueReference:
1901 case Type::RValueReference:
1902 QT = cast<ReferenceType>(T)->getPointeeType();
1903 break;
1904 case Type::PackExpansion:
1905 QT = cast<PackExpansionType>(T)->getPattern();
1906 break;
1907 case Type::Paren:
1908 case Type::ConstantArray:
1909 case Type::DependentSizedArray:
1910 case Type::IncompleteArray:
1911 case Type::VariableArray:
1912 case Type::FunctionProto:
1913 case Type::FunctionNoProto:
1914 return true;
1915 }
1916 }
1917}
1918
Abramo Bagnaraea947882011-03-08 16:41:52 +00001919SourceRange DeclaratorDecl::getSourceRange() const {
1920 SourceLocation RangeEnd = getLocation();
1921 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001922 // If the declaration has no name or the type extends past the name take the
1923 // end location of the type.
1924 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001925 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1926 }
1927 return SourceRange(getOuterLocStart(), RangeEnd);
1928}
1929
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001930void QualifierInfo::setTemplateParameterListsInfo(
1931 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001932 // Free previous template parameters (if any).
1933 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001934 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001935 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001936 NumTemplParamLists = 0;
1937 }
1938 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001939 if (!TPLists.empty()) {
1940 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1941 NumTemplParamLists = TPLists.size();
1942 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001943 }
1944}
1945
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001946//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001947// VarDecl Implementation
1948//===----------------------------------------------------------------------===//
1949
Sebastian Redl833ef452010-01-26 22:01:41 +00001950const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1951 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001952 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001953 case SC_Auto: return "auto";
1954 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001955 case SC_PrivateExtern: return "__private_extern__";
1956 case SC_Register: return "register";
1957 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001958 }
1959
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001960 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001961}
1962
Richard Smith053f6c62014-05-16 23:01:30 +00001963VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1964 SourceLocation StartLoc, SourceLocation IdLoc,
1965 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1966 StorageClass SC)
1967 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001968 redeclarable_base(C) {
Benjamin Kramera939c232014-03-15 18:54:13 +00001969 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1970 "VarDeclBitfields too large!");
1971 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1972 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001973 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1974 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001975 AllBits = 0;
1976 VarDeclBits.SClass = SC;
1977 // Everything else is implicitly initialized to false.
1978}
1979
Abramo Bagnaradff19302011-03-08 08:55:46 +00001980VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1981 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001982 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001983 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001984 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001985}
1986
Douglas Gregor72172e92012-01-05 21:55:30 +00001987VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001988 return new (C, ID)
1989 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1990 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001991}
1992
Douglas Gregorbf62d642010-12-06 18:36:25 +00001993void VarDecl::setStorageClass(StorageClass SC) {
1994 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001995 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001996}
1997
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001998VarDecl::TLSKind VarDecl::getTLSKind() const {
1999 switch (VarDeclBits.TSCSpec) {
2000 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00002001 if (!hasAttr<ThreadAttr>() &&
2002 !(getASTContext().getLangOpts().OpenMPUseTLS &&
2003 getASTContext().getTargetInfo().isTLSSupported() &&
2004 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00002005 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00002006 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2007 LangOptions::MSVC2015)) ||
2008 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00002009 ? TLS_Dynamic
2010 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00002011 case TSCS___thread: // Fall through.
2012 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00002013 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00002014 case TSCS_thread_local:
2015 return TLS_Dynamic;
2016 }
2017 llvm_unreachable("Unknown thread storage class specifier!");
2018}
2019
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002020SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00002021 if (const Expr *Init = getInit()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002022 SourceLocation InitEnd = Init->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002023 // If Init is implicit, ignore its source range and fallback on
Nico Weberbbe13942013-01-22 17:00:09 +00002024 // DeclaratorDecl::getSourceRange() to handle postfix elements.
2025 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00002026 return SourceRange(getOuterLocStart(), InitEnd);
2027 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00002028 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002029}
2030
Rafael Espindola88510672013-01-04 21:18:45 +00002031template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00002032static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002033 // C++ [dcl.link]p1: All function types, function names with external linkage,
2034 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00002035 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002036 return NoLanguageLinkage;
2037
2038 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00002039 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00002040 ASTContext &Context = D.getASTContext();
2041 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00002042 return CLanguageLinkage;
2043
Rafael Espindola5bda63f2013-02-14 01:47:04 +00002044 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2045 // language linkage of the names of class members and the function type of
2046 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00002047 const DeclContext *DC = D.getDeclContext();
2048 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00002049 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00002050
2051 // If the first decl is in an extern "C" context, any other redeclaration
2052 // will have C language linkage. If the first one is not in an extern "C"
2053 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00002054 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00002055 return CLanguageLinkage;
2056 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00002057}
2058
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002059template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00002060static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002061 // Since the context is ignored for class members, they can only have C++
2062 // language linkage or no language linkage.
2063 const DeclContext *DC = D.getDeclContext();
2064 if (DC->isRecord()) {
2065 assert(D.getASTContext().getLangOpts().CPlusPlus);
2066 return false;
2067 }
2068
2069 return D.getLanguageLinkage() == CLanguageLinkage;
2070}
2071
Rafael Espindolaf4187652013-02-14 01:18:37 +00002072LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002073 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002074}
2075
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002076bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002077 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002078}
2079
Rafael Espindola593537a2013-05-05 20:15:21 +00002080bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002081 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002082}
2083
2084bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002085 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002086}
2087
Rafael Espindola8db352d2013-10-17 15:37:26 +00002088VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002089
Nico Weber7f5015a2015-04-15 21:53:00 +00002090VarDecl::DefinitionKind
2091VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Richard Smitha22d9a52017-12-02 00:55:48 +00002092 if (isThisDeclarationADemotedDefinition())
2093 return DeclarationOnly;
2094
Sebastian Redl35351a92010-01-31 22:27:38 +00002095 // C++ [basic.def]p2:
2096 // A declaration is a definition unless [...] it contains the 'extern'
2097 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00002098 // it declares a non-inline static data member in a class declaration [...],
2099 // it declares a static data member outside a class definition and the variable
2100 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00002101 // C++1y [temp.expl.spec]p15:
2102 // An explicit specialization of a static data member or an explicit
2103 // specialization of a static data member template is a definition if the
2104 // declaration includes an initializer; otherwise, it is a declaration.
2105 //
2106 // FIXME: How do you declare (but not define) a partial specialization of
2107 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00002108 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002109 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00002110 !(getCanonicalDecl()->isInline() &&
2111 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00002112 (hasInit() ||
2113 // If the first declaration is out-of-line, this may be an
2114 // instantiation of an out-of-line partial specialization of a variable
2115 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002116 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00002117 ? getTemplateSpecializationKind() == TSK_Undeclared
2118 : getTemplateSpecializationKind() !=
2119 TSK_ExplicitSpecialization) ||
2120 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00002121 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00002122 else if (!isOutOfLine() && isInline())
2123 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00002124 else
2125 return DeclarationOnly;
2126 }
2127 // C99 6.7p5:
2128 // A definition of an identifier is a declaration for that identifier that
2129 // [...] causes storage to be reserved for that object.
2130 // Note: that applies for all non-file-scope objects.
2131 // C99 6.9.2p1:
2132 // If the declaration of an identifier for an object has file scope and an
2133 // initializer, the declaration is an external definition for the identifier
2134 if (hasInit())
2135 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00002136
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002137 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002138 return Definition;
2139
David Majnemerdd0bed12015-05-14 05:19:20 +00002140 if (const auto *SAA = getAttr<SelectAnyAttr>())
2141 if (!SAA->isInherited())
2142 return Definition;
2143
Richard Smith8809a0c2013-09-27 20:14:12 +00002144 // A variable template specialization (other than a static data member
2145 // template or an explicit specialization) is a declaration until we
2146 // instantiate its initializer.
Richard Smith435e6472017-12-02 02:48:42 +00002147 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2148 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2149 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2150 !VTSD->IsCompleteDefinition)
2151 return DeclarationOnly;
2152 }
Richard Smith8809a0c2013-09-27 20:14:12 +00002153
Nico Weber608e7682015-04-15 23:04:24 +00002154 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002155 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002156
Rafael Espindolabff59562013-04-25 12:11:36 +00002157 // [dcl.link] p7:
2158 // A declaration directly contained in a linkage-specification is treated
2159 // as if it contains the extern specifier for the purpose of determining
2160 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002161 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002162 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002163
Sebastian Redl35351a92010-01-31 22:27:38 +00002164 // C99 6.9.2p2:
2165 // A declaration of an object that has file scope without an initializer,
2166 // and without a storage class specifier or the scs 'static', constitutes
2167 // a tentative definition.
2168 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002169 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002170 return TentativeDefinition;
2171
2172 // What's left is (in C, block-scope) declarations without initializers or
2173 // external storage. These are definitions.
2174 return Definition;
2175}
2176
Sebastian Redl35351a92010-01-31 22:27:38 +00002177VarDecl *VarDecl::getActingDefinition() {
2178 DefinitionKind Kind = isThisDeclarationADefinition();
2179 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002180 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002181
Craig Topper36250ad2014-05-12 05:36:57 +00002182 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002183 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002184 for (auto I : First->redecls()) {
2185 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002186 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002187 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002188 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002189 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002190 }
2191 return LastTentative;
2192}
2193
Daniel Dunbar9d355812012-03-09 01:51:51 +00002194VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002195 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002196 for (auto I : First->redecls()) {
2197 if (I->isThisDeclarationADefinition(C) == Definition)
2198 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002199 }
Craig Topper36250ad2014-05-12 05:36:57 +00002200 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002201}
2202
Daniel Dunbar9d355812012-03-09 01:51:51 +00002203VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002204 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002205
Rafael Espindola8db352d2013-10-17 15:37:26 +00002206 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002207 for (auto I : First->redecls()) {
2208 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002209 if (Kind == Definition)
2210 break;
2211 }
John McCall37bb6c92010-10-29 22:22:43 +00002212
2213 return Kind;
2214}
2215
Sebastian Redl5ca79842010-02-01 20:16:42 +00002216const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002217 for (auto I : redecls()) {
2218 if (auto Expr = I->getInit()) {
2219 D = I;
2220 return Expr;
2221 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002222 }
Craig Topper36250ad2014-05-12 05:36:57 +00002223 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002224}
2225
Chandler Carruth813faed2015-12-30 02:51:00 +00002226bool VarDecl::hasInit() const {
2227 if (auto *P = dyn_cast<ParmVarDecl>(this))
2228 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2229 return false;
2230
2231 return !Init.isNull();
2232}
2233
2234Expr *VarDecl::getInit() {
2235 if (!hasInit())
2236 return nullptr;
2237
2238 if (auto *S = Init.dyn_cast<Stmt *>())
2239 return cast<Expr>(S);
2240
2241 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2242}
2243
2244Stmt **VarDecl::getInitAddress() {
2245 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2246 return &ES->Value;
2247
2248 return Init.getAddrOfPtr1();
2249}
2250
Richard Smitha6e8b682019-09-04 20:30:37 +00002251VarDecl *VarDecl::getInitializingDeclaration() {
2252 VarDecl *Def = nullptr;
2253 for (auto I : redecls()) {
2254 if (I->hasInit())
2255 return I;
2256
2257 if (I->isThisDeclarationADefinition()) {
2258 if (isStaticDataMember())
2259 return I;
2260 else
2261 Def = I;
2262 }
2263 }
2264 return Def;
2265}
2266
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002267bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002268 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002269 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002270
2271 if (!isStaticDataMember())
2272 return false;
2273
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002274 // If this static data member was instantiated from a static data member of
Fangrui Song6907ce22018-07-30 19:24:48 +00002275 // a class template, check whether that static data member was defined
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002276 // out-of-line.
2277 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2278 return VD->isOutOfLine();
Fangrui Song6907ce22018-07-30 19:24:48 +00002279
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002280 return false;
2281}
2282
Douglas Gregord5058122010-02-11 01:19:42 +00002283void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002284 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002285 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002286 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002287 }
2288
2289 Init = I;
2290}
2291
Richard Smith715f7a12019-06-11 17:50:32 +00002292bool VarDecl::mightBeUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002293 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002294
Richard Smith35ecb362012-03-02 04:14:40 +00002295 if (!Lang.CPlusPlus)
2296 return false;
2297
Richard Smith715f7a12019-06-11 17:50:32 +00002298 // Function parameters are never usable in constant expressions.
2299 if (isa<ParmVarDecl>(this))
2300 return false;
2301
Richard Smith35ecb362012-03-02 04:14:40 +00002302 // In C++11, any variable of reference type can be used in a constant
2303 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002304 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002305 return true;
2306
2307 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002308 // not require the variable to be non-volatile, but we consider this to be a
2309 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002310 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002311 return false;
2312
2313 // In C++, const, non-volatile variables of integral or enumeration types
2314 // can be used in constant expressions.
2315 if (getType()->isIntegralOrEnumerationType())
2316 return true;
2317
Richard Smith35ecb362012-03-02 04:14:40 +00002318 // Additionally, in C++11, non-volatile constexpr variables can be used in
2319 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002320 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002321}
2322
Richard Smith715f7a12019-06-11 17:50:32 +00002323bool VarDecl::isUsableInConstantExpressions(ASTContext &Context) const {
2324 // C++2a [expr.const]p3:
2325 // A variable is usable in constant expressions after its initializing
2326 // declaration is encountered...
2327 const VarDecl *DefVD = nullptr;
2328 const Expr *Init = getAnyInitializer(DefVD);
Richard Smith94bc88e2019-06-17 21:46:17 +00002329 if (!Init || Init->isValueDependent() || getType()->isDependentType())
Richard Smith715f7a12019-06-11 17:50:32 +00002330 return false;
2331 // ... if it is a constexpr variable, or it is of reference type or of
2332 // const-qualified integral or enumeration type, ...
2333 if (!DefVD->mightBeUsableInConstantExpressions(Context))
2334 return false;
2335 // ... and its initializer is a constant initializer.
2336 return DefVD->checkInitIsICE();
2337}
2338
Richard Smithd0b4dd62011-12-19 06:19:21 +00002339/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2340/// form, which contains extra information on the evaluated value of the
2341/// initializer.
2342EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002343 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002344 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002345 // Note: EvaluatedStmt contains an APValue, which usually holds
2346 // resources not allocated from the ASTContext. We need to do some
2347 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2348 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002349 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002350 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002351 Init = Eval;
2352 }
2353 return Eval;
2354}
2355
Richard Smithdafff942012-01-14 04:30:29 +00002356APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002357 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002358 return evaluateValue(Notes);
2359}
2360
2361APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002362 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002363 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2364
2365 // We only produce notes indicating why an initializer is non-constant the
2366 // first time it is evaluated. FIXME: The notes won't always be emitted the
2367 // first time we try evaluation, so might not be produced at all.
2368 if (Eval->WasEvaluated)
Richard Smithe637cbe2019-05-21 23:15:18 +00002369 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002370
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002371 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002372 assert(!Init->isValueDependent());
2373
2374 if (Eval->IsEvaluating) {
2375 // FIXME: Produce a diagnostic for self-initialization.
2376 Eval->CheckedICE = true;
2377 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002378 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002379 }
2380
2381 Eval->IsEvaluating = true;
2382
2383 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2384 this, Notes);
2385
Manuel Klimeka7328992013-06-03 13:51:33 +00002386 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2387 // or that it's empty (so that there's nothing to clean up) if evaluation
2388 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002389 if (!Result)
2390 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002391 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002392 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002393
2394 Eval->IsEvaluating = false;
2395 Eval->WasEvaluated = true;
2396
2397 // In C++11, we have determined whether the initializer was a constant
2398 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002399 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002400 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002401 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002402 }
2403
Craig Topper36250ad2014-05-12 05:36:57 +00002404 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002405}
2406
Chandler Carruth813faed2015-12-30 02:51:00 +00002407APValue *VarDecl::getEvaluatedValue() const {
2408 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2409 if (Eval->WasEvaluated)
2410 return &Eval->Evaluated;
2411
2412 return nullptr;
2413}
2414
2415bool VarDecl::isInitKnownICE() const {
2416 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2417 return Eval->CheckedICE;
2418
2419 return false;
2420}
2421
2422bool VarDecl::isInitICE() const {
2423 assert(isInitKnownICE() &&
2424 "Check whether we already know that the initializer is an ICE");
2425 return Init.get<EvaluatedStmt *>()->IsICE;
2426}
2427
Richard Smithd0b4dd62011-12-19 06:19:21 +00002428bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002429 // Initializers of weak variables are never ICEs.
2430 if (isWeak())
2431 return false;
2432
Richard Smithd0b4dd62011-12-19 06:19:21 +00002433 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2434 if (Eval->CheckedICE)
2435 // We have already checked whether this subexpression is an
2436 // integral constant expression.
2437 return Eval->IsICE;
2438
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002439 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002440 assert(!Init->isValueDependent());
2441
2442 // In C++11, evaluate the initializer to check whether it's a constant
2443 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002444 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002445 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002446 evaluateValue(Notes);
2447 return Eval->IsICE;
2448 }
2449
2450 // It's an ICE whether or not the definition we found is
2451 // out-of-line. See DR 721 and the discussion in Clang PR
2452 // 6206 for details.
2453
2454 if (Eval->CheckingICE)
2455 return false;
2456 Eval->CheckingICE = true;
2457
2458 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2459 Eval->CheckingICE = false;
2460 Eval->CheckedICE = true;
2461 return Eval->IsICE;
2462}
2463
Richard Smithb2997f52019-05-21 20:10:50 +00002464bool VarDecl::isParameterPack() const {
2465 return isa<PackExpansionType>(getType());
2466}
2467
Richard Smith2195ec92017-04-21 01:15:13 +00002468template<typename DeclT>
2469static DeclT *getDefinitionOrSelf(DeclT *D) {
2470 assert(D);
2471 if (auto *Def = D->getDefinition())
2472 return Def;
2473 return D;
2474}
2475
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002476bool VarDecl::isEscapingByref() const {
2477 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2478}
2479
2480bool VarDecl::isNonEscapingByref() const {
2481 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2482}
2483
Richard Smithedbc6e92016-10-14 21:41:24 +00002484VarDecl *VarDecl::getTemplateInstantiationPattern() const {
Richard Smitha6b41d72019-05-03 23:51:38 +00002485 const VarDecl *VD = this;
Richard Smithedbc6e92016-10-14 21:41:24 +00002486
Richard Smitha6b41d72019-05-03 23:51:38 +00002487 // If this is an instantiated member, walk back to the template from which
2488 // it was instantiated.
2489 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002490 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
Richard Smitha6b41d72019-05-03 23:51:38 +00002491 VD = VD->getInstantiatedFromStaticDataMember();
Richard Smithedbc6e92016-10-14 21:41:24 +00002492 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2493 VD = NewVD;
Richard Smithedbc6e92016-10-14 21:41:24 +00002494 }
2495 }
2496
Richard Smitha6b41d72019-05-03 23:51:38 +00002497 // If it's an instantiated variable template specialization, find the
2498 // template or partial specialization from which it was instantiated.
2499 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2500 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2501 auto From = VDTemplSpec->getInstantiatedFrom();
2502 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2503 while (!VTD->isMemberSpecialization()) {
2504 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2505 if (!NewVTD)
2506 break;
2507 VTD = NewVTD;
2508 }
2509 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2510 }
2511 if (auto *VTPSD =
2512 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2513 while (!VTPSD->isMemberSpecialization()) {
2514 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2515 if (!NewVTPSD)
2516 break;
2517 VTPSD = NewVTPSD;
2518 }
2519 return getDefinitionOrSelf<VarDecl>(VTPSD);
2520 }
2521 }
2522 }
2523
2524 // If this is the pattern of a variable template, find where it was
2525 // instantiated from. FIXME: Is this necessary?
2526 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2527 while (!VarTemplate->isMemberSpecialization()) {
2528 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2529 if (!NewVT)
Richard Smithedbc6e92016-10-14 21:41:24 +00002530 break;
Richard Smitha6b41d72019-05-03 23:51:38 +00002531 VarTemplate = NewVT;
Richard Smithedbc6e92016-10-14 21:41:24 +00002532 }
2533
Richard Smith2195ec92017-04-21 01:15:13 +00002534 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002535 }
Richard Smitha6b41d72019-05-03 23:51:38 +00002536
2537 if (VD == this)
2538 return nullptr;
2539 return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
Richard Smithedbc6e92016-10-14 21:41:24 +00002540}
2541
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002542VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002543 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002544 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002545
2546 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002547}
2548
Douglas Gregor3c74d412009-10-14 20:14:33 +00002549TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002550 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002551 return Spec->getSpecializationKind();
2552
Sebastian Redl35351a92010-01-31 22:27:38 +00002553 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002554 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002555
Douglas Gregor86d142a2009-10-08 07:24:58 +00002556 return TSK_Undeclared;
2557}
2558
Richard Smitha6b41d72019-05-03 23:51:38 +00002559TemplateSpecializationKind
2560VarDecl::getTemplateSpecializationKindForInstantiation() const {
2561 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2562 return MSI->getTemplateSpecializationKind();
2563
2564 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2565 return Spec->getSpecializationKind();
2566
2567 return TSK_Undeclared;
2568}
2569
Richard Smith8809a0c2013-09-27 20:14:12 +00002570SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002571 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002572 return Spec->getPointOfInstantiation();
2573
2574 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2575 return MSI->getPointOfInstantiation();
2576
2577 return SourceLocation();
2578}
2579
Larisse Voufo39a1e502013-08-06 01:03:05 +00002580VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2581 return getASTContext().getTemplateOrSpecializationInfo(this)
2582 .dyn_cast<VarTemplateDecl *>();
2583}
2584
2585void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2586 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2587}
2588
Justin Lebar5489f852018-05-17 16:15:07 +00002589bool VarDecl::isKnownToBeDefined() const {
2590 const auto &LangOpts = getASTContext().getLangOpts();
2591 // In CUDA mode without relocatable device code, variables of form 'extern
2592 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2593 // memory pool. These are never undefined variables, even if they appear
2594 // inside of an anon namespace or static function.
2595 //
2596 // With CUDA relocatable device code enabled, these variables don't get
2597 // special handling; they're treated like regular extern variables.
Yaxun Liu97670892018-10-02 17:48:54 +00002598 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
Justin Lebar5489f852018-05-17 16:15:07 +00002599 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2600 isa<IncompleteArrayType>(getType()))
2601 return true;
2602
2603 return hasDefinition();
2604}
2605
Erik Pilkington5a559e62018-08-21 17:24:06 +00002606bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2607 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2608 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2609 !hasAttr<AlwaysDestroyAttr>()));
2610}
2611
Richard Smith2b4fa532019-09-29 05:08:46 +00002612QualType::DestructionKind
2613VarDecl::needsDestruction(const ASTContext &Ctx) const {
2614 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2615 if (Eval->HasConstantDestruction)
2616 return QualType::DK_none;
2617
2618 if (isNoDestroy(Ctx))
2619 return QualType::DK_none;
2620
2621 return getType().isDestructedType();
2622}
2623
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002624MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002625 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002626 // FIXME: Remove ?
2627 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2628 return getASTContext().getTemplateOrSpecializationInfo(this)
2629 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002630 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002631}
2632
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002633void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2634 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002635 assert((isa<VarTemplateSpecializationDecl>(this) ||
2636 getMemberSpecializationInfo()) &&
2637 "not a variable or static data member template specialization");
2638
Larisse Voufo39a1e502013-08-06 01:03:05 +00002639 if (VarTemplateSpecializationDecl *Spec =
2640 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2641 Spec->setSpecializationKind(TSK);
Richard Smitha6b41d72019-05-03 23:51:38 +00002642 if (TSK != TSK_ExplicitSpecialization &&
2643 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002644 Spec->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002645 Spec->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002646 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2647 L->InstantiationRequested(this);
2648 }
Richard Smitha6b41d72019-05-03 23:51:38 +00002649 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002650 MSI->setTemplateSpecializationKind(TSK);
2651 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002652 MSI->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002653 MSI->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002654 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2655 L->InstantiationRequested(this);
2656 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002657 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002658}
2659
2660void
2661VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2662 TemplateSpecializationKind TSK) {
2663 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2664 "Previous template or instantiation?");
2665 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002666}
2667
Sebastian Redl833ef452010-01-26 22:01:41 +00002668//===----------------------------------------------------------------------===//
2669// ParmVarDecl Implementation
2670//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002671
Sebastian Redl833ef452010-01-26 22:01:41 +00002672ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002673 SourceLocation StartLoc,
2674 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002675 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002676 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002677 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002678 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002679}
2680
Reid Kleckner8a365022013-06-24 17:51:48 +00002681QualType ParmVarDecl::getOriginalType() const {
2682 TypeSourceInfo *TSI = getTypeSourceInfo();
2683 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002684 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002685 return DT->getOriginalType();
2686 return T;
2687}
2688
Douglas Gregor72172e92012-01-05 21:55:30 +00002689ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002690 return new (C, ID)
2691 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2692 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002693}
2694
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002695SourceRange ParmVarDecl::getSourceRange() const {
2696 if (!hasInheritedDefaultArg()) {
2697 SourceRange ArgRange = getDefaultArgRange();
2698 if (ArgRange.isValid())
2699 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2700 }
2701
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002702 // DeclaratorDecl considers the range of postfix types as overlapping with the
2703 // declaration name, but this is not the case with parameters in ObjC methods.
2704 if (isa<ObjCMethodDecl>(getDeclContext()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002705 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002706
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002707 return DeclaratorDecl::getSourceRange();
2708}
2709
Sebastian Redl833ef452010-01-26 22:01:41 +00002710Expr *ParmVarDecl::getDefaultArg() {
2711 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2712 assert(!hasUninstantiatedDefaultArg() &&
2713 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002714
Sebastian Redl833ef452010-01-26 22:01:41 +00002715 Expr *Arg = getInit();
Bill Wendling7c44da22018-10-31 03:48:47 +00002716 if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002717 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002718
Sebastian Redl833ef452010-01-26 22:01:41 +00002719 return Arg;
2720}
2721
Chandler Carruth813faed2015-12-30 02:51:00 +00002722void ParmVarDecl::setDefaultArg(Expr *defarg) {
2723 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2724 Init = defarg;
2725}
Sebastian Redl833ef452010-01-26 22:01:41 +00002726
Chandler Carruth813faed2015-12-30 02:51:00 +00002727SourceRange ParmVarDecl::getDefaultArgRange() const {
2728 switch (ParmVarDeclBits.DefaultArgKind) {
2729 case DAK_None:
2730 case DAK_Unparsed:
2731 // Nothing we can do here.
2732 return SourceRange();
2733
2734 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002735 return getUninstantiatedDefaultArg()->getSourceRange();
2736
Chandler Carruth813faed2015-12-30 02:51:00 +00002737 case DAK_Normal:
2738 if (const Expr *E = getInit())
2739 return E->getSourceRange();
2740
2741 // Missing an actual expression, may be invalid.
2742 return SourceRange();
2743 }
2744 llvm_unreachable("Invalid default argument kind.");
2745}
2746
2747void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2748 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2749 Init = arg;
2750}
2751
2752Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2753 assert(hasUninstantiatedDefaultArg() &&
2754 "Wrong kind of initialization expression!");
2755 return cast_or_null<Expr>(Init.get<Stmt *>());
2756}
2757
2758bool ParmVarDecl::hasDefaultArg() const {
2759 // FIXME: We should just return false for DAK_None here once callers are
2760 // prepared for the case that we encountered an invalid default argument and
2761 // were unable to even build an invalid expression.
2762 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2763 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002764}
2765
Ted Kremenek540017e2011-10-06 05:00:56 +00002766void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2767 getASTContext().setParameterIndex(this, parameterIndex);
2768 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2769}
2770
2771unsigned ParmVarDecl::getParameterIndexLarge() const {
2772 return getASTContext().getParameterIndex(this);
2773}
2774
Nuno Lopes394ec982008-12-17 23:39:55 +00002775//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002776// FunctionDecl Implementation
2777//===----------------------------------------------------------------------===//
2778
Erich Keane9c665062018-08-01 21:02:40 +00002779FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2780 SourceLocation StartLoc,
2781 const DeclarationNameInfo &NameInfo, QualType T,
2782 TypeSourceInfo *TInfo, StorageClass S,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002783 bool isInlineSpecified,
Saar Razb65b1f32020-01-09 15:07:51 +02002784 ConstexprSpecKind ConstexprKind,
2785 Expr *TrailingRequiresClause)
Erich Keane9c665062018-08-01 21:02:40 +00002786 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2787 StartLoc),
Richard Smith848934c2019-12-05 13:37:35 -08002788 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
Erich Keane9c665062018-08-01 21:02:40 +00002789 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002790 assert(T.isNull() || T->isFunctionType());
Bruno Ricci0b639da2018-12-03 13:04:10 +00002791 FunctionDeclBits.SClass = S;
2792 FunctionDeclBits.IsInline = isInlineSpecified;
2793 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002794 FunctionDeclBits.IsVirtualAsWritten = false;
2795 FunctionDeclBits.IsPure = false;
2796 FunctionDeclBits.HasInheritedPrototype = false;
2797 FunctionDeclBits.HasWrittenPrototype = true;
2798 FunctionDeclBits.IsDeleted = false;
2799 FunctionDeclBits.IsTrivial = false;
2800 FunctionDeclBits.IsTrivialForCall = false;
2801 FunctionDeclBits.IsDefaulted = false;
2802 FunctionDeclBits.IsExplicitlyDefaulted = false;
Richard Smith848934c2019-12-05 13:37:35 -08002803 FunctionDeclBits.HasDefaultedFunctionInfo = false;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002804 FunctionDeclBits.HasImplicitReturnZero = false;
2805 FunctionDeclBits.IsLateTemplateParsed = false;
Gauthier Harnisch796ed032019-06-14 08:56:20 +00002806 FunctionDeclBits.ConstexprKind = ConstexprKind;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002807 FunctionDeclBits.InstantiationIsPending = false;
2808 FunctionDeclBits.UsesSEHTry = false;
Melanie Blower7f9b5132019-12-04 12:23:46 -08002809 FunctionDeclBits.UsesFPIntrin = false;
Bruno Ricci0b639da2018-12-03 13:04:10 +00002810 FunctionDeclBits.HasSkippedBody = false;
2811 FunctionDeclBits.WillHaveBody = false;
2812 FunctionDeclBits.IsMultiVersion = false;
2813 FunctionDeclBits.IsCopyDeductionCandidate = false;
2814 FunctionDeclBits.HasODRHash = false;
Saar Razb65b1f32020-01-09 15:07:51 +02002815 if (TrailingRequiresClause)
2816 setTrailingRequiresClause(TrailingRequiresClause);
Erich Keane9c665062018-08-01 21:02:40 +00002817}
2818
Benjamin Kramer9170e912013-02-22 15:46:01 +00002819void FunctionDecl::getNameForDiagnostic(
2820 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2821 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002822 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2823 if (TemplateArgs)
Serge Pavlov03e672c2017-11-28 16:14:14 +00002824 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002825}
2826
Ted Kremenek186a0742010-04-29 16:49:01 +00002827bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002828 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002829 return FT->isVariadic();
2830 return false;
2831}
2832
Richard Smith848934c2019-12-05 13:37:35 -08002833FunctionDecl::DefaultedFunctionInfo *
2834FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2835 ArrayRef<DeclAccessPair> Lookups) {
2836 DefaultedFunctionInfo *Info = new (Context.Allocate(
2837 totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2838 std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2839 DefaultedFunctionInfo;
2840 Info->NumLookups = Lookups.size();
2841 std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2842 Info->getTrailingObjects<DeclAccessPair>());
2843 return Info;
2844}
2845
2846void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2847 assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
2848 assert(!Body && "can't replace function body with defaulted function info");
2849
2850 FunctionDeclBits.HasDefaultedFunctionInfo = true;
2851 DefaultedInfo = Info;
2852}
2853
2854FunctionDecl::DefaultedFunctionInfo *
2855FunctionDecl::getDefaultedFunctionInfo() const {
2856 return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2857}
2858
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002859bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002860 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002861 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002862 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002863 return true;
2864 }
2865 }
2866
2867 return false;
2868}
2869
Richard Smith848934c2019-12-05 13:37:35 -08002870bool FunctionDecl::hasTrivialBody() const {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002871 Stmt *S = getBody();
2872 if (!S) {
2873 // Since we don't have a body for this function, we don't know if it's
2874 // trivial or not.
2875 return false;
2876 }
2877
2878 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2879 return true;
2880 return false;
2881}
2882
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002883bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002884 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002885 if (I->isThisDeclarationADefinition()) {
2886 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002887 return true;
2888 }
2889 }
2890
2891 return false;
2892}
2893
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002894Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002895 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002896 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002897
Richard Smith848934c2019-12-05 13:37:35 -08002898 assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
2899 "definition should not have a body");
Rafael Espindola44503012013-10-19 01:37:17 +00002900 if (Definition->Body)
2901 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002902
Craig Topper36250ad2014-05-12 05:36:57 +00002903 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002904}
2905
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002906void FunctionDecl::setBody(Stmt *B) {
Richard Smith848934c2019-12-05 13:37:35 -08002907 FunctionDeclBits.HasDefaultedFunctionInfo = false;
2908 Body = LazyDeclStmtPtr(B);
Douglas Gregor027ba502010-12-06 17:49:01 +00002909 if (B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002910 EndRangeLoc = B->getEndLoc();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002911}
2912
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002913void FunctionDecl::setPure(bool P) {
Erich Keane9c665062018-08-01 21:02:40 +00002914 FunctionDeclBits.IsPure = P;
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002915 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002916 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002917 Parent->markedVirtualFunctionPure();
2918}
2919
Richard Smith8d0dc312013-07-21 23:12:18 +00002920template<std::size_t Len>
2921static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2922 IdentifierInfo *II = ND->getIdentifier();
2923 return II && II->isStr(Str);
2924}
2925
Douglas Gregor16618f22009-09-12 00:17:51 +00002926bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002927 const TranslationUnitDecl *tunit =
2928 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2929 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002930 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002931 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002932}
2933
David Majnemerc729b0b2013-09-16 22:44:20 +00002934bool FunctionDecl::isMSVCRTEntryPoint() const {
2935 const TranslationUnitDecl *TUnit =
2936 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2937 if (!TUnit)
2938 return false;
2939
2940 // Even though we aren't really targeting MSVCRT if we are freestanding,
2941 // semantic analysis for these functions remains the same.
2942
2943 // MSVCRT entry points only exist on MSVCRT targets.
2944 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2945 return false;
2946
2947 // Nameless functions like constructors cannot be entry points.
2948 if (!getIdentifier())
2949 return false;
2950
2951 return llvm::StringSwitch<bool>(getName())
2952 .Cases("main", // an ANSI console app
2953 "wmain", // a Unicode console App
2954 "WinMain", // an ANSI GUI app
2955 "wWinMain", // a Unicode GUI app
2956 "DllMain", // a DLL
2957 true)
2958 .Default(false);
2959}
2960
John McCall53ffd372011-05-15 17:49:20 +00002961bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2962 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2963 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2964 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2965 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2966 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2967
Richard Smithf6004412014-01-19 23:25:37 +00002968 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2969 return false;
John McCall53ffd372011-05-15 17:49:20 +00002970
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002971 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002972 if (proto->getNumParams() != 2 || proto->isVariadic())
2973 return false;
John McCall53ffd372011-05-15 17:49:20 +00002974
2975 ASTContext &Context =
2976 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2977 ->getASTContext();
2978
2979 // The result type and first argument type are constant across all
2980 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002981 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002982}
2983
Akira Hatanakacae83f72017-06-29 18:48:40 +00002984bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002985 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2986 return false;
2987 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2988 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2989 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2990 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2991 return false;
2992
2993 if (isa<CXXRecordDecl>(getDeclContext()))
2994 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002995
2996 // This can only fail for an invalid 'operator new' declaration.
2997 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2998 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002999
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003000 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00003001 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00003002 return false;
3003
3004 // If this is a single-parameter function, it must be a replaceable global
3005 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00003006 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00003007 return true;
3008
Richard Smithb2f0f052016-10-10 18:54:32 +00003009 unsigned Params = 1;
3010 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00003011 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00003012
3013 auto Consume = [&] {
3014 ++Params;
3015 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3016 };
3017
3018 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3019 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00003020 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00003021 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3022 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3023 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3024 IsSizedDelete = true;
3025 Consume();
3026 }
3027
3028 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3029 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00003030 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3031 if (IsAligned)
3032 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00003033 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00003034 }
Richard Smithb2f0f052016-10-10 18:54:32 +00003035
3036 // Finally, if this is not a sized delete, the final parameter can
3037 // be a 'const std::nothrow_t&'.
3038 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3039 Ty = Ty->getPointeeType();
3040 if (Ty.getCVRQualifiers() != Qualifiers::Const)
3041 return false;
Richard Smith62a95562019-09-27 01:26:49 +00003042 if (Ty->isNothrowT())
Richard Smithb2f0f052016-10-10 18:54:32 +00003043 Consume();
3044 }
3045
3046 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00003047}
3048
serge-sans-pailled437fba2020-01-16 19:54:38 +01003049bool FunctionDecl::isInlineBuiltinDeclaration() const {
3050 if (!getBuiltinID())
3051 return false;
3052
3053 const FunctionDecl *Definition;
3054 return hasBody(Definition) && Definition->isInlineSpecified();
3055}
3056
Richard Smith5b349582017-10-13 01:55:36 +00003057bool FunctionDecl::isDestroyingOperatorDelete() const {
3058 // C++ P0722:
3059 // Within a class C, a single object deallocation function with signature
3060 // (T, std::destroying_delete_t, <more params>)
3061 // is a destroying operator delete.
3062 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3063 getNumParams() < 2)
3064 return false;
3065
3066 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3067 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3068 RD->getIdentifier()->isStr("destroying_delete_t");
3069}
3070
Rafael Espindolaf4187652013-02-14 01:18:37 +00003071LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00003072 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00003073}
3074
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003075bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00003076 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003077}
3078
Rafael Espindola593537a2013-05-05 20:15:21 +00003079bool FunctionDecl::isInExternCContext() const {
Anastasia Stulovad6865b72019-05-07 14:22:34 +00003080 if (hasAttr<OpenCLKernelAttr>())
3081 return true;
Serge Pavlov3cb80222013-11-14 02:13:03 +00003082 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00003083}
3084
3085bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00003086 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00003087}
3088
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003089bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003090 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003091 return Method->isStatic();
3092
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003093 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003094 return false;
3095
Mike Stump11289f42009-09-09 15:08:12 +00003096 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003097 DC->isNamespace();
3098 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003099 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00003100 if (!Namespace->getDeclName())
3101 return false;
3102 break;
3103 }
3104 }
3105
3106 return true;
3107}
3108
Richard Smith10876ef2013-01-17 01:30:42 +00003109bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00003110 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3111 hasAttr<C11NoReturnAttr>())
3112 return true;
3113
3114 if (auto *FnTy = getType()->getAs<FunctionType>())
3115 return FnTy->getNoReturnAttr();
3116
3117 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00003118}
3119
Erich Keane5c0d1922018-11-28 18:34:14 +00003120
3121MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3122 if (hasAttr<TargetAttr>())
3123 return MultiVersionKind::Target;
3124 if (hasAttr<CPUDispatchAttr>())
3125 return MultiVersionKind::CPUDispatch;
3126 if (hasAttr<CPUSpecificAttr>())
3127 return MultiVersionKind::CPUSpecific;
3128 return MultiVersionKind::None;
3129}
3130
Erich Keane3efe0022018-07-20 14:13:28 +00003131bool FunctionDecl::isCPUDispatchMultiVersion() const {
3132 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3133}
3134
3135bool FunctionDecl::isCPUSpecificMultiVersion() const {
3136 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3137}
3138
Erich Keane19a8adc2018-10-25 18:57:19 +00003139bool FunctionDecl::isTargetMultiVersion() const {
3140 return isMultiVersion() && hasAttr<TargetAttr>();
3141}
3142
Sebastian Redl833ef452010-01-26 22:01:41 +00003143void
3144FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00003145 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00003146
3147 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3148 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00003149 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00003150 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00003151 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00003152 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003153
Erich Keane9c665062018-08-01 21:02:40 +00003154 if (PrevDecl && PrevDecl->isInlined())
3155 setImplicitlyInline(true);
Sebastian Redl833ef452010-01-26 22:01:41 +00003156}
3157
Rafael Espindola8db352d2013-10-17 15:37:26 +00003158FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00003159
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003160/// Returns a value indicating whether this function corresponds to a builtin
3161/// function.
Douglas Gregorb9063fc2009-02-13 23:20:09 +00003162///
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003163/// The function corresponds to a built-in function if it is declared at
3164/// translation scope or within an extern "C" block and its name matches with
3165/// the name of a builtin. The returned value will be 0 for functions that do
3166/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3167/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3168/// value.
3169///
3170/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3171/// functions as their wrapped builtins. This shouldn't be done in general, but
3172/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3173unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
Simon Tatham7c11da02019-09-02 15:35:09 +01003174 unsigned BuiltinID;
Douglas Gregore711f702009-02-14 18:57:46 +00003175
Simon Tatham7c11da02019-09-02 15:35:09 +01003176 if (const auto *AMAA = getAttr<ArmMveAliasAttr>()) {
3177 BuiltinID = AMAA->getBuiltinName()->getBuiltinID();
3178 } else {
3179 if (!getIdentifier())
3180 return 0;
3181
3182 BuiltinID = getIdentifier()->getBuiltinID();
3183 }
3184
Daniel Dunbar304314d2012-03-06 23:52:37 +00003185 if (!BuiltinID)
3186 return 0;
3187
3188 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00003189 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003190 const auto *LinkageDecl =
3191 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00003192 // In C++, the first declaration of a builtin is always inside an implicit
3193 // extern "C".
3194 // FIXME: A recognised library function may not be directly in an extern "C"
3195 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00003196 if (!LinkageDecl) {
3197 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00003198 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00003199 return Builtin::BI__GetExceptionInfo;
3200 return 0;
3201 }
3202 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00003203 return 0;
3204 }
3205
3206 // If the function is marked "overloadable", it has a different mangled name
3207 // and is not the C library function.
Simon Tatham7c11da02019-09-02 15:35:09 +01003208 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3209 !hasAttr<ArmMveAliasAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00003210 return 0;
3211
Douglas Gregore711f702009-02-14 18:57:46 +00003212 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3213 return BuiltinID;
3214
3215 // This function has the name of a known C library
3216 // function. Determine whether it actually refers to the C library
3217 // function or whether it just has the same name.
3218
Douglas Gregora908e7f2009-02-17 03:23:10 +00003219 // If this is a static function, it's not a builtin.
Erik Pilkingtonb6e16ea2019-03-18 19:23:45 +00003220 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00003221 return 0;
3222
Anastasia Stulova1202de32016-02-12 12:07:04 +00003223 // OpenCL v1.2 s6.9.f - The library functions defined in
3224 // the C99 standard headers are not available.
3225 if (Context.getLangOpts().OpenCL &&
3226 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3227 return 0;
3228
Artem Belevich5ecdb942018-01-23 19:08:18 +00003229 // CUDA does not have device-side standard library. printf and malloc are the
3230 // only special cases that are supported by device-side runtime.
3231 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3232 !hasAttr<CUDAHostAttr>() &&
3233 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3234 return 0;
3235
Warren Hunt445d83e2013-11-01 23:46:51 +00003236 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00003237}
3238
Chris Lattner47c0d002009-04-25 06:03:53 +00003239/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00003240/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00003241/// after it has been created.
3242unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003243 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003244 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00003245}
3246
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003247void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003248 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003249 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00003250 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00003251
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00003252 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003253 if (!NewParamInfo.empty()) {
3254 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3255 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00003256 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00003257}
Chris Lattner41943152007-01-25 04:52:46 +00003258
Chris Lattner58258242008-04-10 02:22:51 +00003259/// getMinRequiredArguments - Returns the minimum number of arguments
3260/// needed to call this function. This may be fewer than the number of
3261/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00003262/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00003263unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003264 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003265 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00003266
Richard Smith91151782014-04-01 19:18:16 +00003267 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00003268 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00003269 if (!Param->isParameterPack() && !Param->hasDefaultArg())
3270 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00003271 return NumRequiredArgs;
3272}
3273
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003274/// The combination of the extern and inline keywords under MSVC forces
David Majnemer54e3ba52014-04-02 23:17:29 +00003275/// the function to be required.
3276///
3277/// Note: This function assumes that we will only get called when isInlined()
3278/// would return true for this FunctionDecl.
3279bool FunctionDecl::isMSExternInline() const {
3280 assert(isInlined() && "expected to get called on an inlined function!");
3281
3282 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00003283 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3284 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00003285 return false;
3286
David Majnemer73768702015-03-20 00:02:27 +00003287 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3288 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003289 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003290 return true;
3291
3292 return false;
3293}
3294
3295static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3296 if (Redecl->getStorageClass() != SC_Extern)
3297 return false;
3298
3299 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3300 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003301 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003302 return false;
3303
3304 return true;
3305}
3306
Eli Friedman1b125c32012-02-07 03:50:18 +00003307static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3308 // Only consider file-scope declarations in this test.
3309 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3310 return false;
3311
3312 // Only consider explicit declarations; the presence of a builtin for a
3313 // libcall shouldn't affect whether a definition is externally visible.
3314 if (Redecl->isImplicit())
3315 return false;
3316
Fangrui Song6907ce22018-07-30 19:24:48 +00003317 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003318 return true; // Not an inline definition
3319
3320 return false;
3321}
3322
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003323/// For a function declaration in C or C++, determine whether this
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003324/// declaration causes the definition to be externally visible.
3325///
David Majnemer54e3ba52014-04-02 23:17:29 +00003326/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00003327/// of redeclarations of the given functions causes
3328/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003329bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00003330 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003331 "Must have a declaration without a body.");
3332
3333 ASTContext &Context = getASTContext();
3334
David Majnemer54e3ba52014-04-02 23:17:29 +00003335 if (Context.getLangOpts().MSVCCompat) {
3336 const FunctionDecl *Definition;
3337 if (hasBody(Definition) && Definition->isInlined() &&
3338 redeclForcesDefMSVC(this))
3339 return true;
3340 }
3341
Martin Storsjo71decf82019-09-27 12:25:19 +00003342 if (Context.getLangOpts().CPlusPlus)
3343 return false;
3344
David Blaikiebbafb8a2012-03-11 07:00:24 +00003345 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003346 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3347 // an externally visible definition.
3348 //
3349 // FIXME: What happens if gnu_inline gets added on after the first
3350 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003351 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003352 return false;
3353
3354 const FunctionDecl *Prev = this;
3355 bool FoundBody = false;
3356 while ((Prev = Prev->getPreviousDecl())) {
Richard Smith848934c2019-12-05 13:37:35 -08003357 FoundBody |= Prev->doesThisDeclarationHaveABody();
Eli Friedman1b125c32012-02-07 03:50:18 +00003358
Richard Smith848934c2019-12-05 13:37:35 -08003359 if (Prev->doesThisDeclarationHaveABody()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003360 // If it's not the case that both 'inline' and 'extern' are
3361 // specified on the definition, then it is always externally visible.
3362 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003363 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003364 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003365 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003366 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003367 return false;
3368 }
3369 }
3370 return FoundBody;
3371 }
3372
Eli Friedman1b125c32012-02-07 03:50:18 +00003373 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003374 // [...] If all of the file scope declarations for a function in a
3375 // translation unit include the inline function specifier without extern,
Eli Friedman1b125c32012-02-07 03:50:18 +00003376 // then the definition in that translation unit is an inline definition.
3377 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003378 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003379 const FunctionDecl *Prev = this;
3380 bool FoundBody = false;
3381 while ((Prev = Prev->getPreviousDecl())) {
Richard Smith848934c2019-12-05 13:37:35 -08003382 FoundBody |= Prev->doesThisDeclarationHaveABody();
Eli Friedman1b125c32012-02-07 03:50:18 +00003383 if (RedeclForcesDefC99(Prev))
3384 return false;
3385 }
3386 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003387}
3388
Richard Smithd052a5782019-10-22 17:44:08 -07003389FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
Alp Tokerd0787eb2014-07-02 01:47:15 +00003390 const TypeSourceInfo *TSI = getTypeSourceInfo();
Richard Smithd052a5782019-10-22 17:44:08 -07003391 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3392 : FunctionTypeLoc();
3393}
3394
3395SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3396 FunctionTypeLoc FTL = getFunctionTypeLoc();
Alp Tokerf5b10792014-07-02 12:55:58 +00003397 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003398 return SourceRange();
3399
Alp Tokerf5b10792014-07-02 12:55:58 +00003400 // Skip self-referential return types.
3401 const SourceManager &SM = getASTContext().getSourceManager();
3402 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003403 SourceLocation Boundary = getNameInfo().getBeginLoc();
Alp Tokerf5b10792014-07-02 12:55:58 +00003404 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3405 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3406 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003407
Alp Tokerf5b10792014-07-02 12:55:58 +00003408 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003409}
3410
Nicolas Manichoncc3c9352019-12-03 08:21:55 -05003411SourceRange FunctionDecl::getParametersSourceRange() const {
3412 unsigned NP = getNumParams();
3413 SourceLocation EllipsisLoc = getEllipsisLoc();
3414
3415 if (NP == 0 && EllipsisLoc.isInvalid())
3416 return SourceRange();
3417
3418 SourceLocation Begin =
3419 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3420 SourceLocation End = EllipsisLoc.isValid()
3421 ? EllipsisLoc
3422 : ParamInfo[NP - 1]->getSourceRange().getEnd();
3423
3424 return SourceRange(Begin, End);
3425}
3426
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003427SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
Richard Smithd052a5782019-10-22 17:44:08 -07003428 FunctionTypeLoc FTL = getFunctionTypeLoc();
3429 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003430}
3431
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003432/// For an inline function definition in C, or for a gnu_inline function
Richard Smithf3814ad2013-01-25 00:08:28 +00003433/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003434///
3435/// Inline function definitions are always available for inlining optimizations.
3436/// However, depending on the language dialect, declaration specifiers, and
3437/// attributes, the definition of an inline function may or may not be
3438/// "externally" visible to other translation units in the program.
3439///
3440/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003441/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003442/// inline definition becomes externally visible (C99 6.7.4p6).
3443///
3444/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
Fangrui Song6907ce22018-07-30 19:24:48 +00003445/// definition, we use the GNU semantics for inline, which are nearly the
3446/// opposite of C99 semantics. In particular, "inline" by itself will create
3447/// an externally visible symbol, but "extern inline" will not create an
Douglas Gregor299d76e2009-09-13 07:46:26 +00003448/// externally visible symbol.
3449bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Nick Desaulniers58060222019-09-12 19:53:35 +00003450 assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3451 hasAttr<AliasAttr>()) &&
Manuel Klimekda7456a2016-11-01 10:30:50 +00003452 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003453 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003454 ASTContext &Context = getASTContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00003455
David Blaikiebbafb8a2012-03-11 07:00:24 +00003456 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003457 // Note: If you change the logic here, please change
3458 // doesDeclarationForceExternallyVisibleDefinition as well.
3459 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003460 // If it's not the case that both 'inline' and 'extern' are
3461 // specified on the definition, then this inline definition is
3462 // externally visible.
Martin Storsjo71decf82019-09-27 12:25:19 +00003463 if (Context.getLangOpts().CPlusPlus)
3464 return false;
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003465 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003466 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003467
Douglas Gregorff76cb92010-12-09 16:59:22 +00003468 // If any declaration is 'inline' but not 'extern', then this definition
3469 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003470 for (auto Redecl : redecls()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003471 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003472 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003473 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003474 }
3475
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003476 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003477 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003478
Richard Smithf3814ad2013-01-25 00:08:28 +00003479 // The rest of this function is C-only.
3480 assert(!Context.getLangOpts().CPlusPlus &&
3481 "should not use C inline rules in C++");
3482
Douglas Gregor299d76e2009-09-13 07:46:26 +00003483 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003484 // [...] If all of the file scope declarations for a function in a
3485 // translation unit include the inline function specifier without extern,
Douglas Gregor299d76e2009-09-13 07:46:26 +00003486 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003487 for (auto Redecl : redecls()) {
3488 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003489 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003490 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003491
Douglas Gregor299d76e2009-09-13 07:46:26 +00003492 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003493 // An inline definition does not provide an external definition for the
3494 // function, and does not forbid an external definition in another
Douglas Gregor299d76e2009-09-13 07:46:26 +00003495 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003496 return false;
3497}
3498
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003499/// getOverloadedOperator - Which C++ overloaded operator this
3500/// function represents, if any.
3501OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003502 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3503 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003504 else
3505 return OO_None;
3506}
3507
Alexis Huntc88db062010-01-13 09:01:02 +00003508/// getLiteralIdentifier - The literal suffix identifier this function
3509/// represents, if any.
3510const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3511 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3512 return getDeclName().getCXXLiteralIdentifier();
3513 else
Craig Topper36250ad2014-05-12 05:36:57 +00003514 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003515}
3516
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003517FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3518 if (TemplateOrSpecialization.isNull())
3519 return TK_NonTemplate;
3520 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3521 return TK_FunctionTemplate;
3522 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3523 return TK_MemberSpecialization;
3524 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3525 return TK_FunctionTemplateSpecialization;
3526 if (TemplateOrSpecialization.is
3527 <DependentFunctionTemplateSpecializationInfo*>())
3528 return TK_DependentFunctionTemplateSpecialization;
3529
David Blaikie83d382b2011-09-23 05:06:16 +00003530 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003531}
3532
Douglas Gregord801b062009-10-07 23:56:10 +00003533FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003534 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003535 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003536
3537 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003538}
3539
Chandler Carruth21c90602015-12-30 03:24:14 +00003540MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
Richard Smithf19a8b02019-05-02 00:49:14 +00003541 if (auto *MSI =
3542 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3543 return MSI;
3544 if (auto *FTSI = TemplateOrSpecialization
3545 .dyn_cast<FunctionTemplateSpecializationInfo *>())
3546 return FTSI->getMemberSpecializationInfo();
3547 return nullptr;
Chandler Carruth21c90602015-12-30 03:24:14 +00003548}
3549
Fangrui Song6907ce22018-07-30 19:24:48 +00003550void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003551FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3552 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003553 TemplateSpecializationKind TSK) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003554 assert(TemplateOrSpecialization.isNull() &&
Douglas Gregord801b062009-10-07 23:56:10 +00003555 "Member function is already a specialization");
Fangrui Song6907ce22018-07-30 19:24:48 +00003556 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003557 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003558 TemplateOrSpecialization = Info;
3559}
3560
Chandler Carruth21c90602015-12-30 03:24:14 +00003561FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3562 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3563}
3564
3565void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003566 assert(TemplateOrSpecialization.isNull() &&
3567 "Member function is already a specialization");
Chandler Carruth21c90602015-12-30 03:24:14 +00003568 TemplateOrSpecialization = Template;
3569}
3570
Douglas Gregorafca3b42009-10-27 20:53:28 +00003571bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003572 // If the function is invalid, it can't be implicitly instantiated.
3573 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003574 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003575
Richard Smithf19a8b02019-05-02 00:49:14 +00003576 switch (getTemplateSpecializationKindForInstantiation()) {
Douglas Gregorafca3b42009-10-27 20:53:28 +00003577 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003578 case TSK_ExplicitInstantiationDefinition:
Richard Smithf19a8b02019-05-02 00:49:14 +00003579 case TSK_ExplicitSpecialization:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003580 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003581
Douglas Gregorafca3b42009-10-27 20:53:28 +00003582 case TSK_ImplicitInstantiation:
3583 return true;
3584
3585 case TSK_ExplicitInstantiationDeclaration:
3586 // Handled below.
3587 break;
3588 }
3589
3590 // Find the actual template from which we will instantiate.
3591 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003592 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003593 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003594 HasPattern = PatternDecl->hasBody(PatternDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00003595
Douglas Gregorafca3b42009-10-27 20:53:28 +00003596 // C++0x [temp.explicit]p9:
3597 // Except for inline functions, other explicit instantiation declarations
3598 // have the effect of suppressing the implicit instantiation of the entity
Fangrui Song6907ce22018-07-30 19:24:48 +00003599 // to which they refer.
3600 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003601 return true;
3602
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003603 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003604}
3605
3606bool FunctionDecl::isTemplateInstantiation() const {
Richard Smithf19a8b02019-05-02 00:49:14 +00003607 // FIXME: Remove this, it's not clear what it means. (Which template
3608 // specialization kind?)
3609 return clang::isTemplateInstantiation(getTemplateSpecializationKind());
Ted Kremenek85825ae2011-12-01 00:59:17 +00003610}
Fangrui Song6907ce22018-07-30 19:24:48 +00003611
Douglas Gregorafca3b42009-10-27 20:53:28 +00003612FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003613 // If this is a generic lambda call operator specialization, its
Faisal Valib90b2112014-04-03 16:32:21 +00003614 // instantiation pattern is always its primary template's pattern
Fangrui Song6907ce22018-07-30 19:24:48 +00003615 // even if its primary template was instantiated from another
Faisal Valib90b2112014-04-03 16:32:21 +00003616 // member template (which happens with nested generic lambdas).
Fangrui Song6907ce22018-07-30 19:24:48 +00003617 // Since a lambda's call operator's body is transformed eagerly,
3618 // we don't have to go hunting for a prototype definition template
3619 // (i.e. instantiated-from-member-template) to use as an instantiation
Faisal Valib90b2112014-04-03 16:32:21 +00003620 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003621
Faisal Valib90b2112014-04-03 16:32:21 +00003622 if (isGenericLambdaCallOperatorSpecialization(
3623 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003624 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3625 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003626 }
Richard Smith2195ec92017-04-21 01:15:13 +00003627
Richard Smithf19a8b02019-05-02 00:49:14 +00003628 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) {
3629 if (!clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3630 return nullptr;
3631 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3632 }
3633
3634 if (!clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3635 return nullptr;
3636
Douglas Gregorafca3b42009-10-27 20:53:28 +00003637 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
Richard Smitha6b41d72019-05-03 23:51:38 +00003638 // If we hit a point where the user provided a specialization of this
3639 // template, we're done looking.
3640 while (!Primary->isMemberSpecialization()) {
3641 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3642 if (!NewPrimary)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003643 break;
Richard Smitha6b41d72019-05-03 23:51:38 +00003644 Primary = NewPrimary;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003645 }
Richard Smith2195ec92017-04-21 01:15:13 +00003646
3647 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00003648 }
Richard Smith2195ec92017-04-21 01:15:13 +00003649
Richard Smith2195ec92017-04-21 01:15:13 +00003650 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003651}
3652
Douglas Gregor70d83e22009-06-29 17:30:29 +00003653FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003654 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003655 = TemplateOrSpecialization
3656 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003657 return Info->getTemplate();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003658 }
Craig Topper36250ad2014-05-12 05:36:57 +00003659 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003660}
3661
Chandler Carruth21c90602015-12-30 03:24:14 +00003662FunctionTemplateSpecializationInfo *
3663FunctionDecl::getTemplateSpecializationInfo() const {
3664 return TemplateOrSpecialization
3665 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3666}
3667
Douglas Gregor70d83e22009-06-29 17:30:29 +00003668const TemplateArgumentList *
3669FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003670 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003671 = TemplateOrSpecialization
3672 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003673 return Info->TemplateArguments;
3674 }
Craig Topper36250ad2014-05-12 05:36:57 +00003675 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003676}
3677
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003678const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003679FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3680 if (FunctionTemplateSpecializationInfo *Info
3681 = TemplateOrSpecialization
3682 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3683 return Info->TemplateArgumentsAsWritten;
3684 }
Craig Topper36250ad2014-05-12 05:36:57 +00003685 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003686}
3687
Mike Stump11289f42009-09-09 15:08:12 +00003688void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003689FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3690 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003691 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003692 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003693 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003694 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3695 SourceLocation PointOfInstantiation) {
Richard Smithf19a8b02019-05-02 00:49:14 +00003696 assert((TemplateOrSpecialization.isNull() ||
3697 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3698 "Member function is already a specialization");
Fangrui Song6907ce22018-07-30 19:24:48 +00003699 assert(TSK != TSK_Undeclared &&
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003700 "Must specify the type of function template specialization");
Richard Smithf19a8b02019-05-02 00:49:14 +00003701 assert((TemplateOrSpecialization.isNull() ||
3702 TSK == TSK_ExplicitSpecialization) &&
3703 "Member specialization must be an explicit specialization");
3704 FunctionTemplateSpecializationInfo *Info =
3705 FunctionTemplateSpecializationInfo::Create(
3706 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3707 PointOfInstantiation,
3708 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003709 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003710 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003711}
3712
John McCallb9c78482010-04-08 09:05:18 +00003713void
3714FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3715 const UnresolvedSetImpl &Templates,
3716 const TemplateArgumentListInfo &TemplateArgs) {
3717 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003718 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003719 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3720 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003721 TemplateOrSpecialization = Info;
3722}
3723
James Y Knight7a22b242015-08-06 20:26:32 +00003724DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003725FunctionDecl::getDependentSpecializationInfo() const {
3726 return TemplateOrSpecialization
3727 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3728}
3729
3730DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003731DependentFunctionTemplateSpecializationInfo::Create(
3732 ASTContext &Context, const UnresolvedSetImpl &Ts,
3733 const TemplateArgumentListInfo &TArgs) {
3734 void *Buffer = Context.Allocate(
3735 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3736 TArgs.size(), Ts.size()));
3737 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3738}
3739
John McCallb9c78482010-04-08 09:05:18 +00003740DependentFunctionTemplateSpecializationInfo::
3741DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3742 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003743 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
James Y Knight53c76162015-07-17 18:21:37 +00003744 NumTemplates = Ts.size();
3745 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003746
James Y Knight7a22b242015-08-06 20:26:32 +00003747 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003748 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3749 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3750
James Y Knight7a22b242015-08-06 20:26:32 +00003751 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003752 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3753 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3754}
3755
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003756TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003757 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003758 // information object.
Richard Smithf19a8b02019-05-02 00:49:14 +00003759 if (FunctionTemplateSpecializationInfo *FTSInfo =
3760 TemplateOrSpecialization
3761 .dyn_cast<FunctionTemplateSpecializationInfo *>())
Douglas Gregord801b062009-10-07 23:56:10 +00003762 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003763
Richard Smithf19a8b02019-05-02 00:49:14 +00003764 if (MemberSpecializationInfo *MSInfo =
3765 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3766 return MSInfo->getTemplateSpecializationKind();
3767
3768 return TSK_Undeclared;
3769}
3770
3771TemplateSpecializationKind
3772FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3773 // This is the same as getTemplateSpecializationKind(), except that for a
3774 // function that is both a function template specialization and a member
3775 // specialization, we prefer the member specialization information. Eg:
3776 //
3777 // template<typename T> struct A {
3778 // template<typename U> void f() {}
3779 // template<> void f<int>() {}
3780 // };
3781 //
3782 // For A<int>::f<int>():
3783 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
3784 // * getTemplateSpecializationKindForInstantiation() will return
3785 // TSK_ImplicitInstantiation
3786 //
3787 // This reflects the facts that A<int>::f<int> is an explicit specialization
3788 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
3789 // from A::f<int> if a definition is needed.
3790 if (FunctionTemplateSpecializationInfo *FTSInfo =
3791 TemplateOrSpecialization
3792 .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
3793 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
3794 return MSInfo->getTemplateSpecializationKind();
3795 return FTSInfo->getTemplateSpecializationKind();
3796 }
3797
3798 if (MemberSpecializationInfo *MSInfo =
3799 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
Douglas Gregord801b062009-10-07 23:56:10 +00003800 return MSInfo->getTemplateSpecializationKind();
Fangrui Song6907ce22018-07-30 19:24:48 +00003801
Douglas Gregord801b062009-10-07 23:56:10 +00003802 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003803}
3804
Mike Stump11289f42009-09-09 15:08:12 +00003805void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003806FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3807 SourceLocation PointOfInstantiation) {
3808 if (FunctionTemplateSpecializationInfo *FTSInfo
3809 = TemplateOrSpecialization.dyn_cast<
3810 FunctionTemplateSpecializationInfo*>()) {
3811 FTSInfo->setTemplateSpecializationKind(TSK);
3812 if (TSK != TSK_ExplicitSpecialization &&
3813 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003814 FTSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003815 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003816 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3817 L->InstantiationRequested(this);
3818 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003819 } else if (MemberSpecializationInfo *MSInfo
3820 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3821 MSInfo->setTemplateSpecializationKind(TSK);
3822 if (TSK != TSK_ExplicitSpecialization &&
3823 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003824 MSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003825 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003826 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3827 L->InstantiationRequested(this);
3828 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003829 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003830 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003831}
3832
3833SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003834 if (FunctionTemplateSpecializationInfo *FTSInfo
3835 = TemplateOrSpecialization.dyn_cast<
3836 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003837 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003838 else if (MemberSpecializationInfo *MSInfo
3839 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003840 return MSInfo->getPointOfInstantiation();
Fangrui Song6907ce22018-07-30 19:24:48 +00003841
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003842 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003843}
3844
Douglas Gregor6411b922009-09-11 20:15:17 +00003845bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003846 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003847 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003848
3849 // If this function was instantiated from a member function of a
Douglas Gregor6411b922009-09-11 20:15:17 +00003850 // class template, check whether that member function was defined out-of-line.
3851 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3852 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003853 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003854 return Definition->isOutOfLine();
3855 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003856
Douglas Gregor6411b922009-09-11 20:15:17 +00003857 // If this function was instantiated from a function template,
3858 // check whether that function template was defined out-of-line.
3859 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3860 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003861 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003862 return Definition->isOutOfLine();
3863 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003864
Douglas Gregor6411b922009-09-11 20:15:17 +00003865 return false;
3866}
3867
Abramo Bagnaraea947882011-03-08 16:41:52 +00003868SourceRange FunctionDecl::getSourceRange() const {
3869 return SourceRange(getOuterLocStart(), EndRangeLoc);
3870}
3871
Anna Zaks28db7ce2012-01-18 02:45:01 +00003872unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003873 IdentifierInfo *FnInfo = getIdentifier();
3874
3875 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003876 return 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00003877
Anna Zaks201d4892012-01-13 21:52:01 +00003878 // Builtin handling.
3879 switch (getBuiltinID()) {
3880 case Builtin::BI__builtin_memset:
3881 case Builtin::BI__builtin___memset_chk:
3882 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003883 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003884
3885 case Builtin::BI__builtin_memcpy:
3886 case Builtin::BI__builtin___memcpy_chk:
3887 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003888 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003889
serge-sans-paillecee4a1c2019-12-11 21:30:10 +01003890 case Builtin::BI__builtin_mempcpy:
3891 case Builtin::BI__builtin___mempcpy_chk:
3892 case Builtin::BImempcpy:
3893 return Builtin::BImempcpy;
3894
Anna Zaks201d4892012-01-13 21:52:01 +00003895 case Builtin::BI__builtin_memmove:
3896 case Builtin::BI__builtin___memmove_chk:
3897 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003898 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003899
3900 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003901 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003902 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003903
Anna Zaks201d4892012-01-13 21:52:01 +00003904 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003905 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003906 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003907
3908 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003909 case Builtin::BImemcmp:
3910 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003911
Clement Courbet8c3343d2019-02-14 12:00:34 +00003912 case Builtin::BI__builtin_bcmp:
3913 case Builtin::BIbcmp:
3914 return Builtin::BIbcmp;
3915
Anna Zaks201d4892012-01-13 21:52:01 +00003916 case Builtin::BI__builtin_strncpy:
3917 case Builtin::BI__builtin___strncpy_chk:
3918 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003919 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003920
3921 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003922 case Builtin::BIstrncmp:
3923 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003924
3925 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003926 case Builtin::BIstrncasecmp:
3927 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003928
3929 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003930 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003931 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003932 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003933
3934 case Builtin::BI__builtin_strndup:
3935 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003936 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003937
Anna Zaks314cd092012-02-01 19:08:57 +00003938 case Builtin::BI__builtin_strlen:
3939 case Builtin::BIstrlen:
3940 return Builtin::BIstrlen;
3941
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003942 case Builtin::BI__builtin_bzero:
3943 case Builtin::BIbzero:
3944 return Builtin::BIbzero;
3945
Anna Zaks201d4892012-01-13 21:52:01 +00003946 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003947 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003948 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003949 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003950 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003951 return Builtin::BImemcpy;
serge-sans-paillecee4a1c2019-12-11 21:30:10 +01003952 else if (FnInfo->isStr("mempcpy"))
3953 return Builtin::BImempcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003954 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003955 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003956 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003957 return Builtin::BImemcmp;
Clement Courbet8c3343d2019-02-14 12:00:34 +00003958 else if (FnInfo->isStr("bcmp"))
3959 return Builtin::BIbcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003960 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003961 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003962 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003963 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003964 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003965 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003966 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003967 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003968 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003969 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003970 else if (FnInfo->isStr("strlen"))
3971 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003972 else if (FnInfo->isStr("bzero"))
3973 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003974 }
3975 break;
3976 }
Anna Zaks22122702012-01-17 00:37:07 +00003977 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003978}
3979
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003980unsigned FunctionDecl::getODRHash() const {
Erich Keane9c665062018-08-01 21:02:40 +00003981 assert(hasODRHash());
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003982 return ODRHash;
3983}
3984
Richard Trieue6caa262017-12-23 00:41:01 +00003985unsigned FunctionDecl::getODRHash() {
Erich Keane9c665062018-08-01 21:02:40 +00003986 if (hasODRHash())
Richard Trieue6caa262017-12-23 00:41:01 +00003987 return ODRHash;
3988
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003989 if (auto *FT = getInstantiatedFromMemberFunction()) {
Erich Keane9c665062018-08-01 21:02:40 +00003990 setHasODRHash(true);
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003991 ODRHash = FT->getODRHash();
3992 return ODRHash;
3993 }
3994
Richard Trieue6caa262017-12-23 00:41:01 +00003995 class ODRHash Hash;
3996 Hash.AddFunctionDecl(this);
Erich Keane9c665062018-08-01 21:02:40 +00003997 setHasODRHash(true);
Richard Trieue6caa262017-12-23 00:41:01 +00003998 ODRHash = Hash.CalculateHash();
3999 return ODRHash;
4000}
4001
Chris Lattner59a25942008-03-31 00:36:02 +00004002//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00004003// FieldDecl Implementation
4004//===----------------------------------------------------------------------===//
4005
Jay Foad39c79802011-01-12 09:06:06 +00004006FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004007 SourceLocation StartLoc, SourceLocation IdLoc,
4008 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00004009 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00004010 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00004011 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4012 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00004013}
4014
Douglas Gregor72172e92012-01-05 21:55:30 +00004015FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004016 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4017 SourceLocation(), nullptr, QualType(), nullptr,
4018 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00004019}
4020
Sebastian Redl833ef452010-01-26 22:01:41 +00004021bool FieldDecl::isAnonymousStructOrUnion() const {
4022 if (!isImplicit() || getDeclName())
4023 return false;
4024
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004025 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00004026 return Record->getDecl()->isAnonymousStructOrUnion();
4027
4028 return false;
4029}
4030
Richard Smithcaf33902011-10-10 18:28:20 +00004031unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4032 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00004033 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00004034}
4035
Richard Smith866dee42018-04-02 18:29:43 +00004036bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4037 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
4038 getBitWidthValue(Ctx) == 0;
4039}
4040
Richard Smith78b239e2019-06-20 20:44:45 +00004041bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4042 if (isZeroLengthBitField(Ctx))
4043 return true;
4044
4045 // C++2a [intro.object]p7:
4046 // An object has nonzero size if it
4047 // -- is not a potentially-overlapping subobject, or
4048 if (!hasAttr<NoUniqueAddressAttr>())
4049 return false;
4050
4051 // -- is not of class type, or
4052 const auto *RT = getType()->getAs<RecordType>();
4053 if (!RT)
4054 return false;
4055 const RecordDecl *RD = RT->getDecl()->getDefinition();
4056 if (!RD) {
4057 assert(isInvalidDecl() && "valid field has incomplete type");
4058 return false;
4059 }
4060
4061 // -- [has] virtual member functions or virtual base classes, or
4062 // -- has subobjects of nonzero size or bit-fields of nonzero length
4063 const auto *CXXRD = cast<CXXRecordDecl>(RD);
4064 if (!CXXRD->isEmpty())
4065 return false;
4066
4067 // Otherwise, [...] the circumstances under which the object has zero size
4068 // are implementation-defined.
4069 // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4070 // ABI will do.
4071 return true;
4072}
4073
John McCall4e819612011-01-20 07:57:12 +00004074unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00004075 const FieldDecl *Canonical = getCanonicalDecl();
4076 if (Canonical != this)
4077 return Canonical->getFieldIndex();
4078
John McCall4e819612011-01-20 07:57:12 +00004079 if (CachedFieldIndex) return CachedFieldIndex - 1;
4080
Richard Smithd62306a2011-11-10 06:34:14 +00004081 unsigned Index = 0;
Richard Smith85567dd2017-11-15 01:33:46 +00004082 const RecordDecl *RD = getParent()->getDefinition();
4083 assert(RD && "requested index for field of struct with no definition");
Richard Smithd62306a2011-11-10 06:34:14 +00004084
Hans Wennborga302cd92014-08-21 16:06:57 +00004085 for (auto *Field : RD->fields()) {
4086 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4087 ++Index;
4088 }
John McCall4e819612011-01-20 07:57:12 +00004089
Richard Smithd62306a2011-11-10 06:34:14 +00004090 assert(CachedFieldIndex && "failed to find field in parent");
4091 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00004092}
4093
Abramo Bagnara20c9e242011-03-08 11:07:11 +00004094SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00004095 const Expr *FinalExpr = getInClassInitializer();
4096 if (!FinalExpr)
4097 FinalExpr = getBitWidth();
4098 if (FinalExpr)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004099 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
Richard Smith6b8e3c02017-08-28 00:28:14 +00004100 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00004101}
4102
4103void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00004104 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00004105 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00004106 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00004107 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00004108 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00004109 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4110 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00004111}
4112
Sebastian Redl833ef452010-01-26 22:01:41 +00004113//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00004114// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00004115//===----------------------------------------------------------------------===//
4116
Erich Keanef92f31c2018-08-01 20:48:16 +00004117TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4118 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4119 SourceLocation StartL)
4120 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4121 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4122 assert((DK != Enum || TK == TTK_Enum) &&
4123 "EnumDecl not matched with TTK_Enum");
4124 setPreviousDecl(PrevDecl);
4125 setTagKind(TK);
4126 setCompleteDefinition(false);
4127 setBeingDefined(false);
4128 setEmbeddedInDeclarator(false);
4129 setFreeStanding(false);
4130 setCompleteDefinitionRequired(false);
4131}
4132
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00004133SourceLocation TagDecl::getOuterLocStart() const {
4134 return getTemplateOrInnerLocStart(this);
4135}
4136
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004137SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00004138 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004139 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00004140 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00004141}
4142
Rafael Espindola8db352d2013-10-17 15:37:26 +00004143TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00004144
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00004145void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00004146 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00004147 if (const Type *T = getTypeForDecl()) {
4148 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00004149 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00004150 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00004151 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00004152}
4153
Douglas Gregordee1be82009-01-17 00:42:38 +00004154void TagDecl::startDefinition() {
Erich Keanef92f31c2018-08-01 20:48:16 +00004155 setBeingDefined(true);
John McCall67da35c2010-02-04 22:26:26 +00004156
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004157 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00004158 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00004159 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00004160 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00004161 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00004162 }
Douglas Gregordee1be82009-01-17 00:42:38 +00004163}
4164
4165void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00004166 assert((!isa<CXXRecordDecl>(this) ||
4167 cast<CXXRecordDecl>(this)->hasDefinition()) &&
4168 "definition completed but not started");
4169
Erich Keanef92f31c2018-08-01 20:48:16 +00004170 setCompleteDefinition(true);
4171 setBeingDefined(false);
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00004172
4173 if (ASTMutationListener *L = getASTMutationListener())
4174 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00004175}
4176
John McCallf937c022011-10-07 06:10:15 +00004177TagDecl *TagDecl::getDefinition() const {
4178 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00004179 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004180
4181 // If it's possible for us to have an out-of-date definition, check now.
Erich Keanef92f31c2018-08-01 20:48:16 +00004182 if (mayHaveOutOfDateDef()) {
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004183 if (IdentifierInfo *II = getIdentifier()) {
4184 if (II->isOutOfDate()) {
4185 updateOutOfDate(*II);
4186 }
4187 }
4188 }
4189
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004190 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00004191 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00004192
Aaron Ballman86c93902014-03-06 23:45:36 +00004193 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00004194 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00004195 return R;
Mike Stump11289f42009-09-09 15:08:12 +00004196
Craig Topper36250ad2014-05-12 05:36:57 +00004197 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00004198}
4199
Douglas Gregor14454802011-02-25 02:25:35 +00004200void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4201 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00004202 // Make sure the extended qualifier info is allocated.
4203 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00004204 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00004205 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00004206 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004207 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00004208 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00004209 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00004210 if (getExtInfo()->NumTemplParamLists == 0) {
4211 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00004212 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004213 }
4214 else
4215 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00004216 }
4217 }
4218}
4219
Benjamin Kramer9cc210652015-08-05 09:40:49 +00004220void TagDecl::setTemplateParameterListsInfo(
4221 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4222 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00004223 // Make sure the extended decl info is allocated.
4224 if (!hasExtInfo())
4225 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00004226 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00004227 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00004228 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00004229}
4230
Ted Kremenek21475702008-09-05 17:16:31 +00004231//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00004232// EnumDecl Implementation
4233//===----------------------------------------------------------------------===//
4234
Erich Keanef92f31c2018-08-01 20:48:16 +00004235EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4236 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4237 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4238 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4239 assert(Scoped || !ScopedUsingClassTag);
4240 IntegerType = nullptr;
4241 setNumPositiveBits(0);
4242 setNumNegativeBits(0);
4243 setScoped(Scoped);
4244 setScopedUsingClassTag(ScopedUsingClassTag);
4245 setFixed(Fixed);
4246 setHasODRHash(false);
4247 ODRHash = 0;
4248}
4249
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004250void EnumDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004251
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004252EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4253 SourceLocation StartLoc, SourceLocation IdLoc,
4254 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00004255 EnumDecl *PrevDecl, bool IsScoped,
4256 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004257 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4258 IsScoped, IsScopedUsingClassTag, IsFixed);
Erich Keanef92f31c2018-08-01 20:48:16 +00004259 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Sebastian Redl833ef452010-01-26 22:01:41 +00004260 C.getTypeDeclType(Enum, PrevDecl);
4261 return Enum;
4262}
4263
Douglas Gregor72172e92012-01-05 21:55:30 +00004264EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004265 EnumDecl *Enum =
4266 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4267 nullptr, nullptr, false, false, false);
Erich Keanef92f31c2018-08-01 20:48:16 +00004268 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004269 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00004270}
4271
Alp Tokerb9fa5122014-01-06 11:31:18 +00004272SourceRange EnumDecl::getIntegerTypeRange() const {
4273 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4274 return TI->getTypeLoc().getSourceRange();
4275 return SourceRange();
4276}
4277
Douglas Gregord5058122010-02-11 01:19:42 +00004278void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00004279 QualType NewPromotionType,
4280 unsigned NumPositiveBits,
4281 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00004282 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00004283 if (!IntegerType)
4284 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00004285 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00004286 setNumPositiveBits(NumPositiveBits);
4287 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00004288 TagDecl::completeDefinition();
4289}
4290
Akira Hatanaka3c268af2017-03-21 02:23:00 +00004291bool EnumDecl::isClosed() const {
4292 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4293 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4294 return true;
4295}
4296
4297bool EnumDecl::isClosedFlag() const {
4298 return isClosed() && hasAttr<FlagEnumAttr>();
4299}
4300
4301bool EnumDecl::isClosedNonFlag() const {
4302 return isClosed() && !hasAttr<FlagEnumAttr>();
4303}
4304
Richard Smith7d137e32012-03-23 03:33:32 +00004305TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4306 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4307 return MSI->getTemplateSpecializationKind();
4308
4309 return TSK_Undeclared;
4310}
4311
4312void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4313 SourceLocation PointOfInstantiation) {
4314 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4315 assert(MSI && "Not an instantiated member enumeration?");
4316 MSI->setTemplateSpecializationKind(TSK);
4317 if (TSK != TSK_ExplicitSpecialization &&
4318 PointOfInstantiation.isValid() &&
4319 MSI->getPointOfInstantiation().isInvalid())
4320 MSI->setPointOfInstantiation(PointOfInstantiation);
4321}
4322
Richard Smith6739a102016-05-05 00:56:12 +00004323EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4324 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4325 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4326 EnumDecl *ED = getInstantiatedFromMemberEnum();
4327 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4328 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00004329 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00004330 }
4331 }
4332
4333 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4334 "couldn't find pattern for enum instantiation");
4335 return nullptr;
4336}
4337
Richard Smith4b38ded2012-03-14 23:13:10 +00004338EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4339 if (SpecializationInfo)
4340 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4341
Craig Topper36250ad2014-05-12 05:36:57 +00004342 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00004343}
4344
4345void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4346 TemplateSpecializationKind TSK) {
4347 assert(!SpecializationInfo && "Member enum is already a specialization");
4348 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4349}
4350
Richard Trieuab4d7302018-07-25 22:52:05 +00004351unsigned EnumDecl::getODRHash() {
Erich Keanef92f31c2018-08-01 20:48:16 +00004352 if (hasODRHash())
Richard Trieuab4d7302018-07-25 22:52:05 +00004353 return ODRHash;
4354
4355 class ODRHash Hash;
4356 Hash.AddEnumDecl(this);
Erich Keanef92f31c2018-08-01 20:48:16 +00004357 setHasODRHash(true);
Richard Trieuab4d7302018-07-25 22:52:05 +00004358 ODRHash = Hash.CalculateHash();
4359 return ODRHash;
4360}
4361
Sebastian Redl833ef452010-01-26 22:01:41 +00004362//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00004363// RecordDecl Implementation
4364//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00004365
Richard Smith053f6c62014-05-16 23:01:30 +00004366RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4367 DeclContext *DC, SourceLocation StartLoc,
4368 SourceLocation IdLoc, IdentifierInfo *Id,
4369 RecordDecl *PrevDecl)
Erich Keanef92f31c2018-08-01 20:48:16 +00004370 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4371 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4372 setHasFlexibleArrayMember(false);
4373 setAnonymousStructOrUnion(false);
4374 setHasObjectMember(false);
4375 setHasVolatileMember(false);
4376 setHasLoadedFieldsFromExternalStorage(false);
4377 setNonTrivialToPrimitiveDefaultInitialize(false);
4378 setNonTrivialToPrimitiveCopy(false);
4379 setNonTrivialToPrimitiveDestroy(false);
Akira Hatanaka09051062019-09-07 00:34:43 +00004380 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4381 setHasNonTrivialToPrimitiveDestructCUnion(false);
4382 setHasNonTrivialToPrimitiveCopyCUnion(false);
Erich Keanef92f31c2018-08-01 20:48:16 +00004383 setParamDestroyedInCallee(false);
4384 setArgPassingRestrictions(APK_CanPassInRegs);
Ted Kremenek52baf502008-09-02 21:12:32 +00004385}
4386
Jay Foad39c79802011-01-12 09:06:06 +00004387RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004388 SourceLocation StartLoc, SourceLocation IdLoc,
4389 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00004390 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4391 StartLoc, IdLoc, Id, PrevDecl);
Erich Keanef92f31c2018-08-01 20:48:16 +00004392 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004393
Ted Kremenek21475702008-09-05 17:16:31 +00004394 C.getTypeDeclType(R, PrevDecl);
4395 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00004396}
4397
Douglas Gregor72172e92012-01-05 21:55:30 +00004398RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004399 RecordDecl *R =
4400 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4401 SourceLocation(), nullptr, nullptr);
Erich Keanef92f31c2018-08-01 20:48:16 +00004402 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004403 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00004404}
4405
Douglas Gregordfcad112009-03-25 15:59:44 +00004406bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00004407 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00004408 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4409}
4410
Alexey Bataev39c81e22014-08-28 04:28:19 +00004411bool RecordDecl::isLambda() const {
4412 if (auto RD = dyn_cast<CXXRecordDecl>(this))
4413 return RD->isLambda();
4414 return false;
4415}
4416
Alexey Bataev330de032014-10-29 12:21:55 +00004417bool RecordDecl::isCapturedRecord() const {
4418 return hasAttr<CapturedRecordAttr>();
4419}
4420
4421void RecordDecl::setCapturedRecord() {
4422 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4423}
4424
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004425RecordDecl::field_iterator RecordDecl::field_begin() const {
Erich Keanef92f31c2018-08-01 20:48:16 +00004426 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004427 LoadFieldsFromExternalStorage();
4428
4429 return field_iterator(decl_iterator(FirstDecl));
4430}
4431
Douglas Gregorb11aad82011-02-19 18:51:44 +00004432/// completeDefinition - Notes that the definition of this type is now
4433/// complete.
4434void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00004435 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00004436 TagDecl::completeDefinition();
4437}
4438
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004439/// isMsStruct - Get whether or not this record uses ms_struct layout.
4440/// This which can be turned on with an attribute, pragma, or the
4441/// -mms-bitfields command-line option.
4442bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00004443 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004444}
4445
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004446void RecordDecl::LoadFieldsFromExternalStorage() const {
4447 ExternalASTSource *Source = getASTContext().getExternalSource();
4448 assert(hasExternalLexicalStorage() && Source && "No external storage?");
4449
4450 // Notify that we have a RecordDecl doing some initialization.
4451 ExternalASTSource::Deserializing TheFields(Source);
4452
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004453 SmallVector<Decl*, 64> Decls;
Erich Keanef92f31c2018-08-01 20:48:16 +00004454 setHasLoadedFieldsFromExternalStorage(true);
Richard Smith3cb15722015-08-05 22:41:45 +00004455 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4456 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4457 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004458
4459#ifndef NDEBUG
4460 // Check that all decls we got were FieldDecls.
4461 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00004462 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004463#endif
4464
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004465 if (Decls.empty())
4466 return;
4467
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004468 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00004469 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004470}
4471
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004472bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4473 ASTContext &Context = getASTContext();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004474 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4475 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4476 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004477 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00004478 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004479 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004480 // We may be able to relax some of these requirements.
4481 int ReasonToReject = -1;
4482 if (!CXXRD || CXXRD->isExternCContext())
4483 ReasonToReject = 0; // is not C++.
4484 else if (CXXRD->hasAttr<PackedAttr>())
4485 ReasonToReject = 1; // is packed.
4486 else if (CXXRD->isUnion())
4487 ReasonToReject = 2; // is a union.
4488 else if (CXXRD->isTriviallyCopyable())
4489 ReasonToReject = 3; // is trivially copyable.
4490 else if (CXXRD->hasTrivialDestructor())
4491 ReasonToReject = 4; // has trivial destructor.
4492 else if (CXXRD->isStandardLayout())
4493 ReasonToReject = 5; // is standard layout.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004494 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4495 "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004496 ReasonToReject = 6; // is in a blacklisted file.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004497 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4498 getQualifiedNameAsString(),
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004499 "field-padding"))
4500 ReasonToReject = 7; // is blacklisted.
4501
4502 if (EmitRemark) {
4503 if (ReasonToReject >= 0)
4504 Context.getDiagnostics().Report(
4505 getLocation(),
4506 diag::remark_sanitize_address_insert_extra_padding_rejected)
4507 << getQualifiedNameAsString() << ReasonToReject;
4508 else
4509 Context.getDiagnostics().Report(
4510 getLocation(),
4511 diag::remark_sanitize_address_insert_extra_padding_accepted)
4512 << getQualifiedNameAsString();
4513 }
4514 return ReasonToReject < 0;
4515}
4516
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004517const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4518 for (const auto *I : fields()) {
4519 if (I->getIdentifier())
4520 return I;
4521
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004522 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004523 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004524 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004525 return NamedDataMember;
4526 }
4527
4528 // We didn't find a named data member.
4529 return nullptr;
4530}
4531
Steve Naroff415d3d52008-10-08 17:01:13 +00004532//===----------------------------------------------------------------------===//
4533// BlockDecl Implementation
4534//===----------------------------------------------------------------------===//
4535
Erich Keanec9d29902018-08-01 21:16:54 +00004536BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4537 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4538 setIsVariadic(false);
4539 setCapturesCXXThis(false);
4540 setBlockMissingReturnType(true);
4541 setIsConversionFromLambda(false);
4542 setDoesNotEscape(false);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00004543 setCanAvoidCopyToHeap(false);
Erich Keanec9d29902018-08-01 21:16:54 +00004544}
4545
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004546void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00004547 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00004548
Steve Naroffc4b30e52009-03-13 16:56:44 +00004549 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00004550 if (!NewParamInfo.empty()) {
4551 NumParams = NewParamInfo.size();
4552 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4553 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00004554 }
4555}
4556
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004557void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4558 bool CapturesCXXThis) {
Erich Keanec9d29902018-08-01 21:16:54 +00004559 this->setCapturesCXXThis(CapturesCXXThis);
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004560 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004561
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004562 if (Captures.empty()) {
4563 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004564 return;
4565 }
4566
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004567 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004568}
Sebastian Redl833ef452010-01-26 22:01:41 +00004569
John McCallce45f882011-06-15 22:51:16 +00004570bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004571 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004572 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004573 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004574 return true;
4575
4576 return false;
4577}
4578
Douglas Gregor70226da2010-12-21 16:27:07 +00004579SourceRange BlockDecl::getSourceRange() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004580 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
Douglas Gregor70226da2010-12-21 16:27:07 +00004581}
Sebastian Redl833ef452010-01-26 22:01:41 +00004582
4583//===----------------------------------------------------------------------===//
4584// Other Decl Allocation/Deallocation Method Implementations
4585//===----------------------------------------------------------------------===//
4586
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004587void TranslationUnitDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004588
Sebastian Redl833ef452010-01-26 22:01:41 +00004589TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004590 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004591}
4592
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004593void PragmaCommentDecl::anchor() {}
Nico Weber66220292016-03-02 17:28:48 +00004594
4595PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4596 TranslationUnitDecl *DC,
4597 SourceLocation CommentLoc,
4598 PragmaMSCommentKind CommentKind,
4599 StringRef Arg) {
4600 PragmaCommentDecl *PCD =
4601 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4602 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4603 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4604 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4605 return PCD;
4606}
4607
4608PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4609 unsigned ID,
4610 unsigned ArgSize) {
4611 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4612 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4613}
4614
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004615void PragmaDetectMismatchDecl::anchor() {}
Nico Webercbbaeb12016-03-02 19:28:54 +00004616
4617PragmaDetectMismatchDecl *
4618PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4619 SourceLocation Loc, StringRef Name,
4620 StringRef Value) {
4621 size_t ValueStart = Name.size() + 1;
4622 PragmaDetectMismatchDecl *PDMD =
4623 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4624 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4625 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4626 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4627 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4628 Value.size());
4629 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4630 return PDMD;
4631}
4632
4633PragmaDetectMismatchDecl *
4634PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4635 unsigned NameValueSize) {
4636 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4637 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4638}
Nico Weber66220292016-03-02 17:28:48 +00004639
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004640void ExternCContextDecl::anchor() {}
Richard Smithf19e1272015-03-07 00:04:49 +00004641
4642ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4643 TranslationUnitDecl *DC) {
4644 return new (C, DC) ExternCContextDecl(DC);
4645}
4646
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004647void LabelDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004648
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004649LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004650 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004651 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004652}
4653
4654LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4655 SourceLocation IdentL, IdentifierInfo *II,
4656 SourceLocation GnuLabelL) {
4657 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004658 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004659}
4660
Douglas Gregor72172e92012-01-05 21:55:30 +00004661LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004662 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4663 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004664}
4665
Ehsan Akhgari31097582014-09-22 02:21:54 +00004666void LabelDecl::setMSAsmLabel(StringRef Name) {
Saar Razfdf80e82019-12-06 01:30:21 +02004667char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
Ehsan Akhgari31097582014-09-22 02:21:54 +00004668 memcpy(Buffer, Name.data(), Name.size());
4669 Buffer[Name.size()] = '\0';
4670 MSAsmName = Buffer;
4671}
4672
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004673void ValueDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004674
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004675bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004676 for (const auto *I : attrs())
4677 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004678 return true;
4679
4680 return isWeakImported();
4681}
4682
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004683void ImplicitParamDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004684
Sebastian Redl833ef452010-01-26 22:01:41 +00004685ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004686 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004687 IdentifierInfo *Id, QualType Type,
4688 ImplicitParamKind ParamKind) {
4689 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4690}
4691
4692ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4693 ImplicitParamKind ParamKind) {
4694 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004695}
4696
Richard Smithf7981722013-11-22 09:01:48 +00004697ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004698 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004699 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004700}
4701
Sebastian Redl833ef452010-01-26 22:01:41 +00004702FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004703 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004704 const DeclarationNameInfo &NameInfo,
4705 QualType T, TypeSourceInfo *TInfo,
Gauthier Harnisch796ed032019-06-14 08:56:20 +00004706 StorageClass SC, bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004707 bool hasWrittenPrototype,
Saar Razb65b1f32020-01-09 15:07:51 +02004708 ConstexprSpecKind ConstexprKind,
4709 Expr *TrailingRequiresClause) {
Richard Smithf7981722013-11-22 09:01:48 +00004710 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004711 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
Saar Razb65b1f32020-01-09 15:07:51 +02004712 SC, isInlineSpecified, ConstexprKind,
4713 TrailingRequiresClause);
Erich Keane9c665062018-08-01 21:02:40 +00004714 New->setHasWrittenPrototype(hasWrittenPrototype);
Sebastian Redl833ef452010-01-26 22:01:41 +00004715 return New;
4716}
4717
Douglas Gregor72172e92012-01-05 21:55:30 +00004718FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004719 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004720 DeclarationNameInfo(), QualType(), nullptr,
Saar Razb65b1f32020-01-09 15:07:51 +02004721 SC_None, false, CSK_unspecified, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004722}
4723
Sebastian Redl833ef452010-01-26 22:01:41 +00004724BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004725 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004726}
4727
Douglas Gregor72172e92012-01-05 21:55:30 +00004728BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004729 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004730}
4731
Chandler Carruth21c90602015-12-30 03:24:14 +00004732CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4733 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4734 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4735
Ben Langmuir37943a72013-05-03 19:00:33 +00004736CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4737 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004738 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004739 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004740}
4741
Ben Langmuirce914fc2013-05-03 19:20:19 +00004742CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004743 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004744 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004745 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004746}
4747
Chandler Carruth21c90602015-12-30 03:24:14 +00004748Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4749void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4750
4751bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4752void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4753
Sebastian Redl833ef452010-01-26 22:01:41 +00004754EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4755 SourceLocation L,
4756 IdentifierInfo *Id, QualType T,
4757 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004758 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004759}
4760
Douglas Gregor72172e92012-01-05 21:55:30 +00004761EnumConstantDecl *
4762EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004763 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4764 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004765}
4766
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004767void IndirectFieldDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004768
Richard Smith9f951822016-01-06 22:49:11 +00004769IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4770 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004771 QualType T,
4772 MutableArrayRef<NamedDecl *> CH)
4773 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4774 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004775 // In C++, indirect field declarations conflict with tag declarations in the
4776 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4777 if (C.getLangOpts().CPlusPlus)
4778 IdentifierNamespace |= IDNS_Tag;
4779}
4780
Benjamin Kramer39593702010-11-21 14:11:41 +00004781IndirectFieldDecl *
4782IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004783 IdentifierInfo *Id, QualType T,
4784 llvm::MutableArrayRef<NamedDecl *> CH) {
4785 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004786}
4787
Douglas Gregor72172e92012-01-05 21:55:30 +00004788IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4789 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004790 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004791 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004792}
4793
Douglas Gregorbe996932010-09-01 20:41:53 +00004794SourceRange EnumConstantDecl::getSourceRange() const {
4795 SourceLocation End = getLocation();
4796 if (Init)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004797 End = Init->getEndLoc();
Douglas Gregorbe996932010-09-01 20:41:53 +00004798 return SourceRange(getLocation(), End);
4799}
4800
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004801void TypeDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004802
Sebastian Redl833ef452010-01-26 22:01:41 +00004803TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004804 SourceLocation StartLoc, SourceLocation IdLoc,
4805 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004806 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004807}
4808
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004809void TypedefNameDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004810
Richard Smith42413142015-05-15 20:05:43 +00004811TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4812 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4813 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4814 auto *ThisTypedef = this;
4815 if (AnyRedecl && OwningTypedef) {
4816 OwningTypedef = OwningTypedef->getCanonicalDecl();
4817 ThisTypedef = ThisTypedef->getCanonicalDecl();
4818 }
4819 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004820 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004821 }
Richard Smitha5230222015-03-27 01:37:43 +00004822
4823 return nullptr;
4824}
4825
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004826bool TypedefNameDecl::isTransparentTagSlow() const {
4827 auto determineIsTransparent = [&]() {
4828 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4829 if (auto *TD = TT->getDecl()) {
4830 if (TD->getName() != getName())
4831 return false;
4832 SourceLocation TTLoc = getLocation();
4833 SourceLocation TDLoc = TD->getLocation();
4834 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4835 return false;
4836 SourceManager &SM = getASTContext().getSourceManager();
4837 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4838 }
4839 }
4840 return false;
4841 };
4842
4843 bool isTransparent = determineIsTransparent();
Benjamin Kramerdfb730a2018-01-26 14:14:11 +00004844 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004845 return isTransparent;
4846}
4847
Douglas Gregor72172e92012-01-05 21:55:30 +00004848TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004849 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004850 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004851}
4852
Richard Smithdda56e42011-04-15 14:24:37 +00004853TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4854 SourceLocation StartLoc,
4855 SourceLocation IdLoc, IdentifierInfo *Id,
4856 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004857 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004858}
4859
Douglas Gregor72172e92012-01-05 21:55:30 +00004860TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004861 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4862 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004863}
4864
Abramo Bagnaraea947882011-03-08 16:41:52 +00004865SourceRange TypedefDecl::getSourceRange() const {
4866 SourceLocation RangeEnd = getLocation();
4867 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4868 if (typeIsPostfix(TInfo->getType()))
4869 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4870 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004871 return SourceRange(getBeginLoc(), RangeEnd);
Abramo Bagnaraea947882011-03-08 16:41:52 +00004872}
4873
Richard Smithdda56e42011-04-15 14:24:37 +00004874SourceRange TypeAliasDecl::getSourceRange() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004875 SourceLocation RangeEnd = getBeginLoc();
Richard Smithdda56e42011-04-15 14:24:37 +00004876 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4877 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004878 return SourceRange(getBeginLoc(), RangeEnd);
Richard Smithdda56e42011-04-15 14:24:37 +00004879}
4880
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004881void FileScopeAsmDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004882
Sebastian Redl833ef452010-01-26 22:01:41 +00004883FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004884 StringLiteral *Str,
4885 SourceLocation AsmLoc,
4886 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004887 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004888}
Douglas Gregorba345522011-12-02 23:23:56 +00004889
Richard Smithf7981722013-11-22 09:01:48 +00004890FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004891 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004892 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4893 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004894}
4895
Michael Han84324352013-02-22 17:15:32 +00004896void EmptyDecl::anchor() {}
4897
4898EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004899 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004900}
4901
4902EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004903 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004904}
4905
Douglas Gregorba345522011-12-02 23:23:56 +00004906//===----------------------------------------------------------------------===//
4907// ImportDecl Implementation
4908//===----------------------------------------------------------------------===//
4909
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004910/// Retrieve the number of module identifiers needed to name the given
Douglas Gregorba345522011-12-02 23:23:56 +00004911/// module.
4912static unsigned getNumModuleIdentifiers(Module *Mod) {
4913 unsigned Result = 1;
4914 while (Mod->Parent) {
4915 Mod = Mod->Parent;
4916 ++Result;
4917 }
4918 return Result;
4919}
4920
Fangrui Song6907ce22018-07-30 19:24:48 +00004921ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004922 Module *Imported,
4923 ArrayRef<SourceLocation> IdentifierLocs)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004924 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
Douglas Gregorba345522011-12-02 23:23:56 +00004925 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004926 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004927 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4928 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004929}
4930
Fangrui Song6907ce22018-07-30 19:24:48 +00004931ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004932 Module *Imported, SourceLocation EndLoc)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004933 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
James Y Knight7a22b242015-08-06 20:26:32 +00004934 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004935}
4936
Richard Smithf7981722013-11-22 09:01:48 +00004937ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004938 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004939 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004940 return new (C, DC,
4941 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004942 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004943}
4944
Richard Smithf7981722013-11-22 09:01:48 +00004945ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004946 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004947 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004948 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004949 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4950 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004951 Import->setImplicit();
4952 return Import;
4953}
4954
Douglas Gregor72172e92012-01-05 21:55:30 +00004955ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4956 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004957 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004958 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004959}
4960
4961ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4962 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004963 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004964
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004965 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004966 return llvm::makeArrayRef(StoredLocs,
4967 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004968}
4969
4970SourceRange ImportDecl::getSourceRange() const {
4971 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004972 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4973
Douglas Gregorba345522011-12-02 23:23:56 +00004974 return SourceRange(getLocation(), getIdentifierLocs().back());
4975}
Richard Smith8df390f2016-09-08 23:14:54 +00004976
4977//===----------------------------------------------------------------------===//
4978// ExportDecl Implementation
4979//===----------------------------------------------------------------------===//
4980
4981void ExportDecl::anchor() {}
4982
4983ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4984 SourceLocation ExportLoc) {
4985 return new (C, DC) ExportDecl(DC, ExportLoc);
4986}
4987
4988ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4989 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4990}