blob: 98962461a7e1f85a1fc7afc92abff81f180bd3e4 [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"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000019#include "clang/AST/CanonicalType.h"
20#include "clang/AST/DeclBase.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000023#include "clang/AST/DeclOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/DeclTemplate.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000025#include "clang/AST/DeclarationName.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000026#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000027#include "clang/AST/ExprCXX.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000028#include "clang/AST/ExternalASTSource.h"
Richard Trieue6caa262017-12-23 00:41:01 +000029#include "clang/AST/ODRHash.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000030#include "clang/AST/PrettyDeclStackTrace.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000031#include "clang/AST/PrettyPrinter.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000032#include "clang/AST/Redeclarable.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000033#include "clang/AST/Stmt.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000034#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000036#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000037#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000038#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000039#include "clang/Basic/LLVM.h"
40#include "clang/Basic/LangOptions.h"
41#include "clang/Basic/Linkage.h"
Douglas Gregorba345522011-12-02 23:23:56 +000042#include "clang/Basic/Module.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000043#include "clang/Basic/PartialDiagnostic.h"
44#include "clang/Basic/SanitizerBlacklist.h"
45#include "clang/Basic/Sanitizers.h"
46#include "clang/Basic/SourceLocation.h"
47#include "clang/Basic/SourceManager.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000048#include "clang/Basic/Specifiers.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000049#include "clang/Basic/TargetCXXABI.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000050#include "clang/Basic/TargetInfo.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000051#include "clang/Basic/Visibility.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000052#include "llvm/ADT/APSInt.h"
53#include "llvm/ADT/ArrayRef.h"
54#include "llvm/ADT/None.h"
55#include "llvm/ADT/Optional.h"
56#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/SmallVector.h"
58#include "llvm/ADT/StringSwitch.h"
59#include "llvm/ADT/StringRef.h"
60#include "llvm/ADT/Triple.h"
61#include "llvm/Support/Casting.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000062#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkode0215c2017-11-13 23:01:27 +000063#include "llvm/Support/raw_ostream.h"
David Blaikie9c70e042011-09-21 18:16:56 +000064#include <algorithm>
Eugene Zelenkode0215c2017-11-13 23:01:27 +000065#include <cassert>
66#include <cstddef>
67#include <cstring>
68#include <memory>
69#include <string>
70#include <tuple>
71#include <type_traits>
David Blaikie9c70e042011-09-21 18:16:56 +000072
Chris Lattner6d9a6852006-10-25 05:11:20 +000073using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000074
Richard Smith0b87e072013-10-07 08:02:11 +000075Decl *clang::getPrimaryMergedDecl(Decl *D) {
76 return D->getASTContext().getPrimaryMergedDecl(D);
77}
78
Jordan Rose1e879d82018-03-23 00:07:18 +000079void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
80 SourceLocation Loc = this->Loc;
81 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
82 if (Loc.isValid()) {
83 Loc.print(OS, Context.getSourceManager());
84 OS << ": ";
85 }
86 OS << Message;
87
88 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
89 OS << " '";
90 ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
91 OS << "'";
92 }
93
94 OS << '\n';
95}
96
Richard Smith73b21d82014-09-03 02:33:22 +000097// Defined here so that it can be inlined into its direct callers.
98bool Decl::isOutOfLine() const {
99 return !getLexicalDeclContext()->Equals(getDeclContext());
100}
101
Richard Smith42413142015-05-15 20:05:43 +0000102TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
103 : Decl(TranslationUnit, nullptr, SourceLocation()),
Eugene Zelenkode0215c2017-11-13 23:01:27 +0000104 DeclContext(TranslationUnit), Ctx(ctx) {}
Richard Smith42413142015-05-15 20:05:43 +0000105
Chris Lattner88f70d62008-03-15 05:43:15 +0000106//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000107// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000108//===----------------------------------------------------------------------===//
109
John McCalldf25c432013-02-16 00:17:33 +0000110// Visibility rules aren't rigorously externally specified, but here
111// are the basic principles behind what we implement:
112//
113// 1. An explicit visibility attribute is generally a direct expression
114// of the user's intent and should be honored. Only the innermost
115// visibility attribute applies. If no visibility attribute applies,
116// global visibility settings are considered.
117//
118// 2. There is one caveat to the above: on or in a template pattern,
119// an explicit visibility attribute is just a default rule, and
120// visibility can be decreased by the visibility of template
121// arguments. But this, too, has an exception: an attribute on an
122// explicit specialization or instantiation causes all the visibility
123// restrictions of the template arguments to be ignored.
124//
125// 3. A variable that does not otherwise have explicit visibility can
126// be restricted by the visibility of its type.
127//
128// 4. A visibility restriction is explicit if it comes from an
129// attribute (or something like it), not a global visibility setting.
130// When emitting a reference to an external symbol, visibility
131// restrictions are ignored unless they are explicit.
John McCalld041a9b2013-02-20 01:54:26 +0000132//
133// 5. When computing the visibility of a non-type, including a
134// non-type member of a class, only non-type visibility restrictions
135// are considered: the 'visibility' attribute, global value-visibility
136// settings, and a few special cases like __private_extern.
137//
138// 6. When computing the visibility of a type, including a type member
139// of a class, only type visibility restrictions are considered:
140// the 'type_visibility' attribute and global type-visibility settings.
141// However, a 'visibility' attribute counts as a 'type_visibility'
142// attribute on any declaration that only has the former.
143//
144// The visibility of a "secondary" entity, like a template argument,
145// is computed using the kind of that entity, not the kind of the
146// primary entity for which we are computing visibility. For example,
147// the visibility of a specialization of either of these templates:
148// template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
149// template <class T, bool (&compare)(T, X)> class matcher;
150// is restricted according to the type visibility of the argument 'T',
151// the type visibility of 'bool(&)(T,X)', and the value visibility of
152// the argument function 'compare'. That 'has_match' is a value
153// and 'matcher' is a type only matters when looking for attributes
154// and settings from the immediate context.
John McCalldf25c432013-02-16 00:17:33 +0000155
John McCalld041a9b2013-02-20 01:54:26 +0000156/// Does this computation kind permit us to consider additional
157/// visibility settings from attributes and the like?
158static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000159 return computation.IgnoreExplicitVisibility;
John McCalld041a9b2013-02-20 01:54:26 +0000160}
161
162/// Given an LVComputationKind, return one of the same type/value sort
163/// that records that it already has explicit visibility.
164static LVComputationKind
Richard Smithfbe7b462017-09-22 02:22:32 +0000165withExplicitVisibilityAlready(LVComputationKind Kind) {
166 Kind.IgnoreExplicitVisibility = true;
167 return Kind;
John McCalld041a9b2013-02-20 01:54:26 +0000168}
169
David Blaikie05785d12013-02-20 22:23:23 +0000170static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
171 LVComputationKind kind) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000172 assert(!kind.IgnoreExplicitVisibility &&
John McCalld041a9b2013-02-20 01:54:26 +0000173 "asking for explicit visibility when we shouldn't be");
Richard Smithfbe7b462017-09-22 02:22:32 +0000174 return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
John McCalld041a9b2013-02-20 01:54:26 +0000175}
176
John McCalldf25c432013-02-16 00:17:33 +0000177/// Is the given declaration a "type" or a "value" for the purposes of
178/// visibility computation?
179static bool usesTypeVisibility(const NamedDecl *D) {
John McCallb4a99d32013-02-19 01:57:35 +0000180 return isa<TypeDecl>(D) ||
181 isa<ClassTemplateDecl>(D) ||
182 isa<ObjCInterfaceDecl>(D);
John McCalldf25c432013-02-16 00:17:33 +0000183}
184
John McCall5f46c482013-02-21 23:42:58 +0000185/// Does the given declaration have member specialization information,
186/// and if so, is it an explicit specialization?
187template <class T> static typename
Benjamin Kramered2f4762014-03-07 14:30:23 +0000188std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
John McCall5f46c482013-02-21 23:42:58 +0000189isExplicitMemberSpecialization(const T *D) {
190 if (const MemberSpecializationInfo *member =
191 D->getMemberSpecializationInfo()) {
192 return member->isExplicitSpecialization();
193 }
194 return false;
195}
196
197/// For templates, this question is easier: a member template can't be
198/// explicitly instantiated, so there's a single bit indicating whether
199/// or not this is an explicit member specialization.
200static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
201 return D->isMemberSpecialization();
202}
203
John McCalld041a9b2013-02-20 01:54:26 +0000204/// Given a visibility attribute, return the explicit visibility
205/// associated with it.
206template <class T>
207static Visibility getVisibilityFromAttr(const T *attr) {
208 switch (attr->getVisibility()) {
209 case T::Default:
210 return DefaultVisibility;
211 case T::Hidden:
212 return HiddenVisibility;
213 case T::Protected:
214 return ProtectedVisibility;
215 }
216 llvm_unreachable("bad visibility kind");
217}
218
John McCalldf25c432013-02-16 00:17:33 +0000219/// Return the explicit visibility of the given declaration.
David Blaikie05785d12013-02-20 22:23:23 +0000220static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
John McCalld041a9b2013-02-20 01:54:26 +0000221 NamedDecl::ExplicitVisibilityKind kind) {
222 // If we're ultimately computing the visibility of a type, look for
223 // a 'type_visibility' attribute before looking for 'visibility'.
224 if (kind == NamedDecl::VisibilityForType) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000225 if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000226 return getVisibilityFromAttr(A);
227 }
228 }
229
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000230 // If this declaration has an explicit visibility attribute, use it.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000231 if (const auto *A = D->getAttr<VisibilityAttr>()) {
John McCalld041a9b2013-02-20 01:54:26 +0000232 return getVisibilityFromAttr(A);
John McCall457a04e2010-10-22 21:05:15 +0000233 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000234
David Blaikie7a30dc52013-02-21 01:47:18 +0000235 return None;
John McCall457a04e2010-10-22 21:05:15 +0000236}
237
George Burgess IV99db3ea2017-08-09 04:02:49 +0000238LinkageInfo LinkageComputer::getLVForType(const Type &T,
239 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000240 if (computation.IgnoreAllVisibility)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000241 return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
George Burgess IV35cb4f82017-08-09 04:12:17 +0000242 return getTypeLinkageAndVisibility(&T);
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000243}
244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000245/// Get the most restrictive linkage for the types in the given
John McCalldf25c432013-02-16 00:17:33 +0000246/// template parameter list. For visibility purposes, template
247/// parameters are part of the signature of a template.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000248LinkageInfo LinkageComputer::getLVForTemplateParameterList(
249 const TemplateParameterList *Params, LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000250 LinkageInfo LV;
David Majnemerc7b85c42014-04-23 05:16:48 +0000251 for (const NamedDecl *P : *Params) {
John McCalldf25c432013-02-16 00:17:33 +0000252 // Template type parameters are the most common and never
253 // contribute to visibility, pack or not.
David Majnemerc7b85c42014-04-23 05:16:48 +0000254 if (isa<TemplateTypeParmDecl>(P))
John McCalldf25c432013-02-16 00:17:33 +0000255 continue;
256
257 // Non-type template parameters can be restricted by the value type, e.g.
258 // template <enum X> class A { ... };
259 // We have to be careful here, though, because we can be dealing with
260 // dependent types.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000261 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
John McCalldf25c432013-02-16 00:17:33 +0000262 // Handle the non-pack case first.
263 if (!NTTP->isExpandedParameterPack()) {
264 if (!NTTP->getType()->isDependentType()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000265 LV.merge(getLVForType(*NTTP->getType(), computation));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000266 }
267 continue;
268 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000269
John McCalldf25c432013-02-16 00:17:33 +0000270 // Look at all the types in an expanded pack.
271 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
272 QualType type = NTTP->getExpansionType(i);
273 if (!type->isDependentType())
George Burgess IV35cb4f82017-08-09 04:12:17 +0000274 LV.merge(getTypeLinkageAndVisibility(type));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000275 }
John McCalldf25c432013-02-16 00:17:33 +0000276 continue;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000277 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000278
John McCalldf25c432013-02-16 00:17:33 +0000279 // Template template parameters can be restricted by their
280 // template parameters, recursively.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000281 const auto *TTP = cast<TemplateTemplateParmDecl>(P);
John McCalldf25c432013-02-16 00:17:33 +0000282
283 // Handle the non-pack case first.
284 if (!TTP->isExpandedParameterPack()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000285 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
286 computation));
John McCalldf25c432013-02-16 00:17:33 +0000287 continue;
288 }
289
290 // Look at all expansions in an expanded pack.
291 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
292 i != n; ++i) {
293 LV.merge(getLVForTemplateParameterList(
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000294 TTP->getExpansionTemplateParameters(i), computation));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000295 }
296 }
297
John McCall457a04e2010-10-22 21:05:15 +0000298 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000299}
300
Eli Friedman7e346a82013-07-01 20:22:57 +0000301static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
Craig Topper36250ad2014-05-12 05:36:57 +0000302 const Decl *Ret = nullptr;
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000303 const DeclContext *DC = D->getDeclContext();
304 while (DC->getDeclKind() != Decl::TranslationUnit) {
Eli Friedman7e346a82013-07-01 20:22:57 +0000305 if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
306 Ret = cast<Decl>(DC);
Rafael Espindolac1b38a22013-05-16 04:30:21 +0000307 DC = DC->getParent();
308 }
309 return Ret;
310}
311
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000312/// Get the most restrictive linkage for the types and
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000313/// declarations in the given template argument list.
John McCalldf25c432013-02-16 00:17:33 +0000314///
315/// Note that we don't take an LVComputationKind because we always
316/// want to honor the visibility of template arguments in the same way.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000317LinkageInfo
318LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
319 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000320 LinkageInfo LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000321
David Majnemerc7b85c42014-04-23 05:16:48 +0000322 for (const TemplateArgument &Arg : Args) {
323 switch (Arg.getKind()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000324 case TemplateArgument::Null:
325 case TemplateArgument::Integral:
326 case TemplateArgument::Expression:
John McCalldf25c432013-02-16 00:17:33 +0000327 continue;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000328
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000329 case TemplateArgument::Type:
David Majnemerc7b85c42014-04-23 05:16:48 +0000330 LV.merge(getLVForType(*Arg.getAsType(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000331 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000332
George Burgess IV00f70bd2018-03-01 05:43:23 +0000333 case TemplateArgument::Declaration: {
334 const NamedDecl *ND = Arg.getAsDecl();
335 assert(!usesTypeVisibility(ND));
336 LV.merge(getLVForDecl(ND, computation));
John McCalldf25c432013-02-16 00:17:33 +0000337 continue;
George Burgess IV00f70bd2018-03-01 05:43:23 +0000338 }
Eli Friedmanb826a002012-09-26 02:36:12 +0000339
340 case TemplateArgument::NullPtr:
George Burgess IV35cb4f82017-08-09 04:12:17 +0000341 LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
John McCalldf25c432013-02-16 00:17:33 +0000342 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000343
344 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000345 case TemplateArgument::TemplateExpansion:
David Majnemerc7b85c42014-04-23 05:16:48 +0000346 if (TemplateDecl *Template =
347 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000348 LV.merge(getLVForDecl(Template, computation));
John McCalldf25c432013-02-16 00:17:33 +0000349 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000350
351 case TemplateArgument::Pack:
David Majnemerc7b85c42014-04-23 05:16:48 +0000352 LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
John McCalldf25c432013-02-16 00:17:33 +0000353 continue;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000354 }
John McCalldf25c432013-02-16 00:17:33 +0000355 llvm_unreachable("bad template argument kind");
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000356 }
357
John McCall457a04e2010-10-22 21:05:15 +0000358 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000359}
360
George Burgess IV99db3ea2017-08-09 04:02:49 +0000361LinkageInfo
362LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
363 LVComputationKind computation) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000364 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
John McCall8823c652010-08-13 08:35:10 +0000365}
366
John McCall5f46c482013-02-21 23:42:58 +0000367static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
368 const FunctionTemplateSpecializationInfo *specInfo) {
369 // Include visibility from the template parameters and arguments
370 // only if this is not an explicit instantiation or specialization
371 // with direct explicit visibility. (Implicit instantiations won't
372 // have a direct attribute.)
373 if (!specInfo->isExplicitInstantiationOrSpecialization())
374 return true;
375
376 return !fn->hasAttr<VisibilityAttr>();
377}
378
John McCalldf25c432013-02-16 00:17:33 +0000379/// Merge in template-related linkage and visibility for the given
380/// function template specialization.
381///
382/// We don't need a computation kind here because we can assume
383/// LVForValue.
John McCall5f46c482013-02-21 23:42:58 +0000384///
NAKAMURA Takumi62eae082013-02-22 04:06:28 +0000385/// \param[out] LV the computation to use for the parent
George Burgess IV99db3ea2017-08-09 04:02:49 +0000386void LinkageComputer::mergeTemplateLV(
387 LinkageInfo &LV, const FunctionDecl *fn,
388 const FunctionTemplateSpecializationInfo *specInfo,
389 LVComputationKind computation) {
John McCall5f46c482013-02-21 23:42:58 +0000390 bool considerVisibility =
391 shouldConsiderTemplateVisibility(fn, specInfo);
John McCalldf25c432013-02-16 00:17:33 +0000392
393 // Merge information from the template parameters.
John McCall5f46c482013-02-21 23:42:58 +0000394 FunctionTemplateDecl *temp = specInfo->getTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000395 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000396 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000397 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
398
399 // Merge information from the template arguments.
400 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000401 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
John McCalldf25c432013-02-16 00:17:33 +0000402 LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
John McCallb8c604a2011-06-27 23:06:04 +0000403}
404
John McCall5f46c482013-02-21 23:42:58 +0000405/// Does the given declaration have a direct visibility attribute
406/// that would match the given rules?
407static bool hasDirectVisibilityAttribute(const NamedDecl *D,
408 LVComputationKind computation) {
Richard Smithfbe7b462017-09-22 02:22:32 +0000409 if (computation.IgnoreAllVisibility)
John McCall5f46c482013-02-21 23:42:58 +0000410 return false;
Richard Smithfbe7b462017-09-22 02:22:32 +0000411
412 return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
413 D->hasAttr<VisibilityAttr>();
John McCall5f46c482013-02-21 23:42:58 +0000414}
415
John McCalld041a9b2013-02-20 01:54:26 +0000416/// Should we consider visibility associated with the template
417/// arguments and parameters of the given class template specialization?
418static bool shouldConsiderTemplateVisibility(
419 const ClassTemplateSpecializationDecl *spec,
420 LVComputationKind computation) {
John McCalldf25c432013-02-16 00:17:33 +0000421 // Include visibility from the template parameters and arguments
422 // only if this is not an explicit instantiation or specialization
423 // with direct explicit visibility (and note that implicit
424 // instantiations won't have a direct attribute).
425 //
426 // Furthermore, we want to ignore template parameters and arguments
John McCalld041a9b2013-02-20 01:54:26 +0000427 // for an explicit specialization when computing the visibility of a
428 // member thereof with explicit visibility.
John McCalldf25c432013-02-16 00:17:33 +0000429 //
430 // This is a bit complex; let's unpack it.
431 //
432 // An explicit class specialization is an independent, top-level
433 // declaration. As such, if it or any of its members has an
434 // explicit visibility attribute, that must directly express the
435 // user's intent, and we should honor it. The same logic applies to
436 // an explicit instantiation of a member of such a thing.
John McCalld041a9b2013-02-20 01:54:26 +0000437
438 // Fast path: if this is not an explicit instantiation or
439 // specialization, we always want to consider template-related
440 // visibility restrictions.
441 if (!spec->isExplicitInstantiationOrSpecialization())
442 return true;
443
444 // This is the 'member thereof' check.
445 if (spec->isExplicitSpecialization() &&
446 hasExplicitVisibilityAlready(computation))
447 return false;
448
John McCall5f46c482013-02-21 23:42:58 +0000449 return !hasDirectVisibilityAttribute(spec, computation);
John McCalld041a9b2013-02-20 01:54:26 +0000450}
451
452/// Merge in template-related linkage and visibility for the given
453/// class template specialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000454void LinkageComputer::mergeTemplateLV(
455 LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
456 LVComputationKind computation) {
John McCalld041a9b2013-02-20 01:54:26 +0000457 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
John McCalldf25c432013-02-16 00:17:33 +0000458
459 // Merge information from the template parameters, but ignore
460 // visibility if we're only considering template arguments.
461
John McCalld041a9b2013-02-20 01:54:26 +0000462 ClassTemplateDecl *temp = spec->getSpecializedTemplate();
John McCalldf25c432013-02-16 00:17:33 +0000463 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000464 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000465 LV.mergeMaybeWithVisibility(tempLV,
John McCalld041a9b2013-02-20 01:54:26 +0000466 considerVisibility && !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +0000467
468 // Merge information from the template arguments. We ignore
469 // template-argument visibility if we've got an explicit
470 // instantiation with a visibility attribute.
471 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000472 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
Rafael Espindola503276b2013-05-30 21:23:15 +0000473 if (considerVisibility)
474 LV.mergeVisibility(argsLV);
475 LV.mergeExternalVisibility(argsLV);
John McCallb8c604a2011-06-27 23:06:04 +0000476}
477
Larisse Voufo5899e192014-07-02 23:08:34 +0000478/// Should we consider visibility associated with the template
479/// arguments and parameters of the given variable template
480/// specialization? As usual, follow class template specialization
481/// logic up to initialization.
482static bool shouldConsiderTemplateVisibility(
483 const VarTemplateSpecializationDecl *spec,
484 LVComputationKind computation) {
485 // Include visibility from the template parameters and arguments
486 // only if this is not an explicit instantiation or specialization
487 // with direct explicit visibility (and note that implicit
488 // instantiations won't have a direct attribute).
489 if (!spec->isExplicitInstantiationOrSpecialization())
490 return true;
491
492 // An explicit variable specialization is an independent, top-level
493 // declaration. As such, if it has an explicit visibility attribute,
494 // that must directly express the user's intent, and we should honor
495 // it.
496 if (spec->isExplicitSpecialization() &&
497 hasExplicitVisibilityAlready(computation))
498 return false;
499
500 return !hasDirectVisibilityAttribute(spec, computation);
501}
502
503/// Merge in template-related linkage and visibility for the given
504/// variable template specialization. As usual, follow class template
505/// specialization logic up to initialization.
George Burgess IV99db3ea2017-08-09 04:02:49 +0000506void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
507 const VarTemplateSpecializationDecl *spec,
508 LVComputationKind computation) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000509 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
510
511 // Merge information from the template parameters, but ignore
512 // visibility if we're only considering template arguments.
513
514 VarTemplateDecl *temp = spec->getSpecializedTemplate();
515 LinkageInfo tempLV =
516 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
517 LV.mergeMaybeWithVisibility(tempLV,
518 considerVisibility && !hasExplicitVisibilityAlready(computation));
519
520 // Merge information from the template arguments. We ignore
521 // template-argument visibility if we've got an explicit
522 // instantiation with a visibility attribute.
523 const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
524 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
525 if (considerVisibility)
526 LV.mergeVisibility(argsLV);
527 LV.mergeExternalVisibility(argsLV);
528}
529
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000530static bool useInlineVisibilityHidden(const NamedDecl *D) {
531 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
Rafael Espindola5cc78902012-07-13 23:26:43 +0000532 const LangOptions &Opts = D->getASTContext().getLangOpts();
533 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000534 return false;
535
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000536 const auto *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000537 if (!FD)
538 return false;
539
540 TemplateSpecializationKind TSK = TSK_Undeclared;
541 if (FunctionTemplateSpecializationInfo *spec
542 = FD->getTemplateSpecializationInfo()) {
543 TSK = spec->getTemplateSpecializationKind();
544 } else if (MemberSpecializationInfo *MSI =
545 FD->getMemberSpecializationInfo()) {
546 TSK = MSI->getTemplateSpecializationKind();
547 }
548
Craig Topper36250ad2014-05-12 05:36:57 +0000549 const FunctionDecl *Def = nullptr;
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000550 // InlineVisibilityHidden only applies to definitions, and
551 // isInlined() only gives meaningful answers on definitions
552 // anyway.
553 return TSK != TSK_ExplicitInstantiationDeclaration &&
554 TSK != TSK_ExplicitInstantiationDefinition &&
Rafael Espindolafb9d4b42012-10-11 16:32:25 +0000555 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000556}
557
Rafael Espindola593537a2013-05-05 20:15:21 +0000558template <typename T> static bool isFirstInExternCContext(T *D) {
Rafael Espindola8db352d2013-10-17 15:37:26 +0000559 const T *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +0000560 return First->isInExternCContext();
Rafael Espindolaf4187652013-02-14 01:18:37 +0000561}
562
Richard Smith03c05032014-02-17 23:34:47 +0000563static bool isSingleLineLanguageLinkage(const Decl &D) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000564 if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
Richard Smith03c05032014-02-17 23:34:47 +0000565 if (!SD->hasBraces())
Rafael Espindola327be3c2013-04-26 01:30:23 +0000566 return true;
567 return false;
568}
569
Richard Smith1283e982017-07-07 20:04:28 +0000570static bool isExportedFromModuleIntefaceUnit(const NamedDecl *D) {
Richard Smithbecb92d2017-10-10 22:33:17 +0000571 // FIXME: Handle isModulePrivate.
Richard Smith1283e982017-07-07 20:04:28 +0000572 switch (D->getModuleOwnershipKind()) {
573 case Decl::ModuleOwnershipKind::Unowned:
574 case Decl::ModuleOwnershipKind::ModulePrivate:
575 return false;
576 case Decl::ModuleOwnershipKind::Visible:
577 case Decl::ModuleOwnershipKind::VisibleWhenImported:
578 if (auto *M = D->getOwningModule())
579 return M->Kind == Module::ModuleInterfaceUnit;
580 }
581 llvm_unreachable("unexpected module ownership kind");
582}
583
584static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
585 // Internal linkage declarations within a module interface unit are modeled
586 // as "module-internal linkage", which means that they have internal linkage
587 // formally but can be indirectly accessed from outside the module via inline
588 // functions and templates defined within the module.
589 if (auto *M = D->getOwningModule())
590 if (M->Kind == Module::ModuleInterfaceUnit)
591 return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
592
593 return LinkageInfo::internal();
594}
595
596static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
597 // C++ Modules TS [basic.link]/6.8:
598 // - A name declared at namespace scope that does not have internal linkage
599 // by the previous rules and that is introduced by a non-exported
600 // declaration has module linkage.
601 if (auto *M = D->getOwningModule())
602 if (M->Kind == Module::ModuleInterfaceUnit)
Richard Smithbecb92d2017-10-10 22:33:17 +0000603 if (!isExportedFromModuleIntefaceUnit(
604 cast<NamedDecl>(D->getCanonicalDecl())))
Richard Smith1283e982017-07-07 20:04:28 +0000605 return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
606
607 return LinkageInfo::external();
608}
609
George Burgess IV99db3ea2017-08-09 04:02:49 +0000610LinkageInfo
611LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000612 LVComputationKind computation,
613 bool IgnoreVarTypeLinkage) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000614 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000615 "Not a name having namespace scope");
616 ASTContext &Context = D->getASTContext();
617
618 // C++ [basic.link]p3:
619 // A name having namespace scope (3.3.6) has internal linkage if it
620 // is the name of
621 // - an object, reference, function or function template that is
622 // explicitly declared static; or,
623 // (This bullet corresponds to C99 6.2.2p3.)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000624 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000625 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000626 if (Var->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000627 return getInternalLinkageFor(Var);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000628
Richard Smith62f19e72016-06-25 00:15:56 +0000629 // - a non-inline, non-volatile object or reference that is explicitly
630 // declared const or constexpr and neither explicitly declared extern
631 // nor previously declared to have external linkage; or (there is no
632 // equivalent in C99)
Richard Smith1283e982017-07-07 20:04:28 +0000633 // The C++ modules TS adds "non-exported" to this list.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000634 if (Context.getLangOpts().CPlusPlus &&
Fangrui Song6907ce22018-07-30 19:24:48 +0000635 Var->getType().isConstQualified() &&
Richard Smith62f19e72016-06-25 00:15:56 +0000636 !Var->getType().isVolatileQualified() &&
Richard Smith1283e982017-07-07 20:04:28 +0000637 !Var->isInline() &&
638 !isExportedFromModuleIntefaceUnit(Var)) {
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000639 const VarDecl *PrevVar = Var->getPreviousDecl();
Rafael Espindola985a3ab2013-04-03 19:22:20 +0000640 if (PrevVar)
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000641 return getLVForDecl(PrevVar, computation);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000642
643 if (Var->getStorageClass() != SC_Extern &&
Rafael Espindola327be3c2013-04-26 01:30:23 +0000644 Var->getStorageClass() != SC_PrivateExtern &&
Richard Smith03c05032014-02-17 23:34:47 +0000645 !isSingleLineLanguageLinkage(*Var))
Richard Smith1283e982017-07-07 20:04:28 +0000646 return getInternalLinkageFor(Var);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000647 }
648
649 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
650 PrevVar = PrevVar->getPreviousDecl()) {
651 if (PrevVar->getStorageClass() == SC_PrivateExtern &&
652 Var->getStorageClass() == SC_None)
George Burgess IV35cb4f82017-08-09 04:12:17 +0000653 return getDeclLinkageAndVisibility(PrevVar);
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000654 // Explicitly declared static.
655 if (PrevVar->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000656 return getInternalLinkageFor(Var);
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000657 }
Alp Tokera2794f92014-01-22 07:29:52 +0000658 } else if (const FunctionDecl *Function = D->getAsFunction()) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000659 // C++ [temp]p4:
660 // A non-member function template can have internal linkage; any
661 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000662
663 // Explicitly declared static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000664 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +0000665 return getInternalLinkageFor(Function);
David Majnemer18fac3b2014-12-10 22:58:14 +0000666 } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
667 // - a data member of an anonymous union.
668 const VarDecl *VD = IFD->getVarDecl();
669 assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
Richard Smithc95d2c52017-09-22 04:25:05 +0000670 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000671 }
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000672 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
Douglas Gregorf73b2822009-11-25 22:24:25 +0000673
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000674 if (D->isInAnonymousNamespace()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000675 const auto *Var = dyn_cast<VarDecl>(D);
676 const auto *Func = dyn_cast<FunctionDecl>(D);
Richard Smithdf963a32017-09-22 22:21:44 +0000677 // FIXME: The check for extern "C" here is not justified by the standard
678 // wording, but we retain it from the pre-DR1113 model to avoid breaking
679 // code.
Richard Smith1283e982017-07-07 20:04:28 +0000680 //
681 // C++11 [basic.link]p4:
682 // An unnamed namespace or a namespace declared directly or indirectly
683 // within an unnamed namespace has internal linkage.
Rafael Espindola593537a2013-05-05 20:15:21 +0000684 if ((!Var || !isFirstInExternCContext(Var)) &&
685 (!Func || !isFirstInExternCContext(Func)))
Richard Smithdf963a32017-09-22 22:21:44 +0000686 return getInternalLinkageFor(D);
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000687 }
John McCallb7139c42010-10-28 04:18:25 +0000688
John McCall457a04e2010-10-22 21:05:15 +0000689 // Set up the defaults.
690
691 // C99 6.2.2p5:
692 // If the declaration of an identifier for an object has file
693 // scope and no storage-class specifier, its linkage is
694 // external.
Richard Smithdd8b5332017-09-04 05:37:53 +0000695 LinkageInfo LV = getExternalLinkageFor(D);
John McCallc273f242010-10-30 11:50:40 +0000696
John McCalld041a9b2013-02-20 01:54:26 +0000697 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000698 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000699 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000700 } else {
701 // If we're declared in a namespace with a visibility attribute,
John McCalldf25c432013-02-16 00:17:33 +0000702 // use that namespace's visibility, and it still counts as explicit.
Rafael Espindola78158af2012-04-16 18:46:26 +0000703 for (const DeclContext *DC = D->getDeclContext();
704 !isa<TranslationUnitDecl>(DC);
705 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000706 const auto *ND = dyn_cast<NamespaceDecl>(DC);
Rafael Espindola78158af2012-04-16 18:46:26 +0000707 if (!ND) continue;
David Blaikie05785d12013-02-20 22:23:23 +0000708 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000709 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000710 break;
711 }
712 }
713 }
Rafael Espindola78158af2012-04-16 18:46:26 +0000714
John McCalldf25c432013-02-16 00:17:33 +0000715 // Add in global settings if the above didn't give us direct visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000716 if (!LV.isVisibilityExplicit()) {
John McCallb4a99d32013-02-19 01:57:35 +0000717 // Use global type/value visibility as appropriate.
Richard Smithfbe7b462017-09-22 02:22:32 +0000718 Visibility globalVisibility =
719 computation.isValueVisibility()
720 ? Context.getLangOpts().getValueVisibilityMode()
721 : Context.getLangOpts().getTypeVisibilityMode();
John McCallb4a99d32013-02-19 01:57:35 +0000722 LV.mergeVisibility(globalVisibility, /*explicit*/ false);
John McCalldf25c432013-02-16 00:17:33 +0000723
724 // If we're paying attention to global visibility, apply
725 // -finline-visibility-hidden if this is an inline method.
726 if (useInlineVisibilityHidden(D))
Reid Klecknera52d1512018-10-10 21:59:56 +0000727 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
John McCalldf25c432013-02-16 00:17:33 +0000728 }
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000729 }
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000730
Douglas Gregorf73b2822009-11-25 22:24:25 +0000731 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000732
Douglas Gregorf73b2822009-11-25 22:24:25 +0000733 // A name having namespace scope has external linkage if it is the
734 // name of
735 //
736 // - an object or reference, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000737 if (const auto *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000738 // GCC applies the following optimization to variables and static
739 // data members, but not to functions:
740 //
John McCall457a04e2010-10-22 21:05:15 +0000741 // Modify the variable's LV by the LV of its type unless this is
742 // C or extern "C". This follows from [basic.link]p9:
743 // A type without linkage shall not be used as the type of a
744 // variable or function with external linkage unless
745 // - the entity has C language linkage, or
746 // - the entity is declared within an unnamed namespace, or
747 // - the entity is not used or is defined in the same
748 // translation unit.
749 // and [basic.link]p10:
750 // ...the types specified by all declarations referring to a
751 // given variable or function shall be identical...
752 // C does not have an equivalent rule.
753 //
John McCall5fe84122010-10-26 04:59:26 +0000754 // Ignore this if we've got an explicit attribute; the user
755 // probably knows what they're doing.
756 //
John McCall457a04e2010-10-22 21:05:15 +0000757 // Note that we don't want to make the variable non-external
758 // because of this, but unique-external linkage suits us.
Richard Smithc95d2c52017-09-22 04:25:05 +0000759 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
760 !IgnoreVarTypeLinkage) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000761 LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
Richard Smith405e2db2017-09-20 07:22:00 +0000762 if (!isExternallyVisible(TypeLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000763 return LinkageInfo::uniqueExternal();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000764 if (!LV.isVisibilityExplicit())
John McCalldf25c432013-02-16 00:17:33 +0000765 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000766 }
767
John McCall23032652010-11-02 18:38:13 +0000768 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000769 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000770
Rafael Espindolad5ed0332012-11-12 04:10:23 +0000771 // Note that Sema::MergeVarDecl already takes care of implementing
772 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
773 // to do it here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000774
Larisse Voufo5899e192014-07-02 23:08:34 +0000775 // As per function and class template specializations (below),
776 // consider LV for the template and template arguments. We're at file
777 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000778 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
Larisse Voufo5899e192014-07-02 23:08:34 +0000779 mergeTemplateLV(LV, spec, computation);
780 }
781
Douglas Gregorf73b2822009-11-25 22:24:25 +0000782 // - a function, unless it has internal linkage; or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000783 } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000784 // In theory, we can modify the function's LV by the LV of its
785 // type unless it has C linkage (see comment above about variables
786 // for justification). In practice, GCC doesn't do this, so it's
787 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000788
John McCall23032652010-11-02 18:38:13 +0000789 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000790 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000791
Rafael Espindolaa508c5d2012-11-21 02:47:19 +0000792 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
793 // merging storage classes and visibility attributes, so we don't have to
794 // look at previous decls in here.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000795
John McCallf768aa72011-02-10 06:50:24 +0000796 // In C++, then if the type of the function uses a type with
797 // unique-external linkage, it's not legally usable from outside
798 // this translation unit. However, we should use the C linkage
799 // rules instead for extern "C" declarations.
Richard Smith99f54792018-01-03 02:34:35 +0000800 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000801 // Only look at the type-as-written. Otherwise, deducing the return type
802 // of a function could change its linkage.
Richard Smith50f4afc2013-05-12 23:17:59 +0000803 QualType TypeAsWritten = Function->getType();
804 if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
805 TypeAsWritten = TSI->getType();
Richard Smith405e2db2017-09-20 07:22:00 +0000806 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
Richard Smith50f4afc2013-05-12 23:17:59 +0000807 return LinkageInfo::uniqueExternal();
808 }
John McCallf768aa72011-02-10 06:50:24 +0000809
John McCall5f46c482013-02-21 23:42:58 +0000810 // Consider LV from the template and the template arguments.
811 // We're at file scope, so we do not need to worry about nested
812 // specializations.
John McCallb8c604a2011-06-27 23:06:04 +0000813 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000814 = Function->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000815 mergeTemplateLV(LV, Function, specInfo, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000816 }
817
Douglas Gregorf73b2822009-11-25 22:24:25 +0000818 // - a named class (Clause 9), or an unnamed class defined in a
819 // typedef declaration in which the class has the typedef name
820 // for linkage purposes (7.1.3); or
821 // - a named enumeration (7.2), or an unnamed enumeration
822 // defined in a typedef declaration in which the enumeration
823 // has the typedef name for linkage purposes (7.1.3); or
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000824 } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000825 // Unnamed tags have no linkage.
John McCall5ea95772013-03-09 00:54:27 +0000826 if (!Tag->hasNameForLinkage())
John McCallc273f242010-10-30 11:50:40 +0000827 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000828
John McCall457a04e2010-10-22 21:05:15 +0000829 // If this is a class template specialization, consider the
John McCall5f46c482013-02-21 23:42:58 +0000830 // linkage of the template and template arguments. We're at file
831 // scope, so we do not need to worry about nested specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000832 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCalldf25c432013-02-16 00:17:33 +0000833 mergeTemplateLV(LV, spec, computation);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000834 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000835
836 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000837 } else if (isa<EnumConstantDecl>(D)) {
Rafael Espindola46cb6f12012-04-21 23:28:21 +0000838 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
John McCalldf25c432013-02-16 00:17:33 +0000839 computation);
Rafael Espindolab97e8962013-05-27 14:14:42 +0000840 if (!isExternalFormalLinkage(EnumLV.getLinkage()))
John McCallc273f242010-10-30 11:50:40 +0000841 return LinkageInfo::none();
842 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000843
844 // - a template, unless it is a function template that has
845 // internal linkage (Clause 14);
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000846 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalld041a9b2013-02-20 01:54:26 +0000847 bool considerVisibility = !hasExplicitVisibilityAlready(computation);
John McCalldf25c432013-02-16 00:17:33 +0000848 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000849 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +0000850 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
851
Douglas Gregorf73b2822009-11-25 22:24:25 +0000852 // - a namespace (7.3), unless it is declared within an unnamed
853 // namespace.
Richard Smith1283e982017-07-07 20:04:28 +0000854 //
855 // We handled names in anonymous namespaces above.
856 } else if (isa<NamespaceDecl>(D)) {
John McCall457a04e2010-10-22 21:05:15 +0000857 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000858
John McCall457a04e2010-10-22 21:05:15 +0000859 // By extension, we assign external linkage to Objective-C
860 // interfaces.
861 } else if (isa<ObjCInterfaceDecl>(D)) {
862 // fallout
863
Richard Smith97135cc2015-11-12 22:19:45 +0000864 } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
865 // A typedef declaration has linkage if it gives a type a name for
866 // linkage purposes.
867 if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
868 return LinkageInfo::none();
869
John McCall457a04e2010-10-22 21:05:15 +0000870 // Everything not covered here has no linkage.
871 } else {
John McCallc273f242010-10-30 11:50:40 +0000872 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000873 }
874
Richard Smithc445d5d2017-10-03 01:58:15 +0000875 // If we ended up with non-externally-visible linkage, visibility should
John McCall457a04e2010-10-22 21:05:15 +0000876 // always be default.
Richard Smithc445d5d2017-10-03 01:58:15 +0000877 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola4a5da442013-02-27 02:56:45 +0000878 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000879
John McCall457a04e2010-10-22 21:05:15 +0000880 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000881}
882
George Burgess IV99db3ea2017-08-09 04:02:49 +0000883LinkageInfo
884LinkageComputer::getLVForClassMember(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +0000885 LVComputationKind computation,
886 bool IgnoreVarTypeLinkage) {
John McCall457a04e2010-10-22 21:05:15 +0000887 // Only certain class members have linkage. Note that fields don't
888 // really have linkage, but it's convenient to say they do for the
889 // purposes of calculating linkage of pointer-to-data-member
890 // template arguments.
Richard Smith26d11be2014-01-08 01:51:59 +0000891 //
892 // Templates also don't officially have linkage, but since we ignore
893 // the C++ standard and look at template arguments when determining
894 // linkage and visibility of a template specialization, we might hit
895 // a template template argument that way. If we do, we need to
896 // consider its linkage.
John McCall8823c652010-08-13 08:35:10 +0000897 if (!(isa<CXXMethodDecl>(D) ||
898 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000899 isa<FieldDecl>(D) ||
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000900 isa<IndirectFieldDecl>(D) ||
Richard Smith26d11be2014-01-08 01:51:59 +0000901 isa<TagDecl>(D) ||
902 isa<TemplateDecl>(D)))
John McCallc273f242010-10-30 11:50:40 +0000903 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000904
John McCall07072662010-11-02 01:45:15 +0000905 LinkageInfo LV;
906
John McCall07072662010-11-02 01:45:15 +0000907 // If we have an explicit visibility attribute, merge that in.
John McCalld041a9b2013-02-20 01:54:26 +0000908 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +0000909 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000910 LV.mergeVisibility(*Vis, true);
Rafael Espindolac7c7ad52012-07-13 14:25:36 +0000911 // If we're paying attention to global visibility, apply
912 // -finline-visibility-hidden if this is an inline method.
913 //
914 // Note that we do this before merging information about
915 // the class visibility.
Rafael Espindola4a5da442013-02-27 02:56:45 +0000916 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
Reid Klecknera52d1512018-10-10 21:59:56 +0000917 LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
John McCall07072662010-11-02 01:45:15 +0000918 }
Rafael Espindola53cf2192012-04-19 05:50:08 +0000919
920 // If this class member has an explicit visibility attribute, the only
921 // thing that can change its visibility is the template arguments, so
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000922 // only look for them when processing the class.
John McCalld041a9b2013-02-20 01:54:26 +0000923 LVComputationKind classComputation = computation;
Rafael Espindola4a5da442013-02-27 02:56:45 +0000924 if (LV.isVisibilityExplicit())
John McCalld041a9b2013-02-20 01:54:26 +0000925 classComputation = withExplicitVisibilityAlready(computation);
Rafael Espindola505a7c82012-04-16 18:25:01 +0000926
John McCall5f46c482013-02-21 23:42:58 +0000927 LinkageInfo classLV =
928 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
Richard Smithcdb06f22017-09-23 04:02:17 +0000929 // The member has the same linkage as the class. If that's not externally
930 // visible, we don't need to compute anything about the linkage.
931 // FIXME: If we're only computing linkage, can we bail out here?
Rafael Espindolae6190db2013-05-28 02:22:10 +0000932 if (!isExternallyVisible(classLV.getLinkage()))
Richard Smithcdb06f22017-09-23 04:02:17 +0000933 return classLV;
Rafael Espindolae6190db2013-05-28 02:22:10 +0000934
935
John McCall5f46c482013-02-21 23:42:58 +0000936 // Otherwise, don't merge in classLV yet, because in certain cases
937 // we need to completely ignore the visibility from it.
938
939 // Specifically, if this decl exists and has an explicit attribute.
Craig Topper36250ad2014-05-12 05:36:57 +0000940 const NamedDecl *explicitSpecSuppressor = nullptr;
John McCall5f46c482013-02-21 23:42:58 +0000941
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000942 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc95d2c52017-09-22 04:25:05 +0000943 // Only look at the type-as-written. Otherwise, deducing the return type
944 // of a function could change its linkage.
945 QualType TypeAsWritten = MD->getType();
946 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
947 TypeAsWritten = TSI->getType();
948 if (!isExternallyVisible(TypeAsWritten->getLinkage()))
949 return LinkageInfo::uniqueExternal();
950
John McCall457a04e2010-10-22 21:05:15 +0000951 // If this is a method template specialization, use the linkage for
952 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000953 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000954 = MD->getTemplateSpecializationInfo()) {
Rafael Espindolaecf63c62013-05-29 04:55:30 +0000955 mergeTemplateLV(LV, MD, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000956 if (spec->isExplicitSpecialization()) {
957 explicitSpecSuppressor = MD;
958 } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
959 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
960 }
961 } else if (isExplicitMemberSpecialization(MD)) {
962 explicitSpecSuppressor = MD;
John McCalle6e622e2010-11-01 01:29:57 +0000963 }
John McCall457a04e2010-10-22 21:05:15 +0000964
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000965 } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
966 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCalldf25c432013-02-16 00:17:33 +0000967 mergeTemplateLV(LV, spec, computation);
John McCall5f46c482013-02-21 23:42:58 +0000968 if (spec->isExplicitSpecialization()) {
969 explicitSpecSuppressor = spec;
970 } else {
971 const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
972 if (isExplicitMemberSpecialization(temp)) {
973 explicitSpecSuppressor = temp->getTemplatedDecl();
974 }
975 }
976 } else if (isExplicitMemberSpecialization(RD)) {
977 explicitSpecSuppressor = RD;
John McCall37bb6c92010-10-29 22:22:43 +0000978 }
979
John McCall37bb6c92010-10-29 22:22:43 +0000980 // Static data members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +0000981 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
982 if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
Larisse Voufo5899e192014-07-02 23:08:34 +0000983 mergeTemplateLV(LV, spec, computation);
984
John McCall36cd5cc2010-10-30 09:18:49 +0000985 // Modify the variable's linkage by its type, but ignore the
986 // type's visibility unless it's a definition.
Richard Smithc95d2c52017-09-22 04:25:05 +0000987 if (!IgnoreVarTypeLinkage) {
988 LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
989 // FIXME: If the type's linkage is not externally visible, we can
990 // give this static data member UniqueExternalLinkage.
991 if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
992 LV.mergeVisibility(typeLV);
993 LV.mergeExternalVisibility(typeLV);
994 }
John McCall5f46c482013-02-21 23:42:58 +0000995
996 if (isExplicitMemberSpecialization(VD)) {
997 explicitSpecSuppressor = VD;
998 }
John McCalldf25c432013-02-16 00:17:33 +0000999
1000 // Template members.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001001 } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001002 bool considerVisibility =
Rafael Espindola4a5da442013-02-27 02:56:45 +00001003 (!LV.isVisibilityExplicit() &&
1004 !classLV.isVisibilityExplicit() &&
John McCalld041a9b2013-02-20 01:54:26 +00001005 !hasExplicitVisibilityAlready(computation));
John McCalldf25c432013-02-16 00:17:33 +00001006 LinkageInfo tempLV =
Rafael Espindolaecf63c62013-05-29 04:55:30 +00001007 getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
John McCalldf25c432013-02-16 00:17:33 +00001008 LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
John McCall5f46c482013-02-21 23:42:58 +00001009
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001010 if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
John McCall5f46c482013-02-21 23:42:58 +00001011 if (isExplicitMemberSpecialization(redeclTemp)) {
1012 explicitSpecSuppressor = temp->getTemplatedDecl();
1013 }
1014 }
John McCall37bb6c92010-10-29 22:22:43 +00001015 }
1016
John McCall5f46c482013-02-21 23:42:58 +00001017 // We should never be looking for an attribute directly on a template.
1018 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1019
1020 // If this member is an explicit member specialization, and it has
1021 // an explicit attribute, ignore visibility from the parent.
1022 bool considerClassVisibility = true;
1023 if (explicitSpecSuppressor &&
Rafael Espindola4a5da442013-02-27 02:56:45 +00001024 // optimization: hasDVA() is true only with explicit visibility.
1025 LV.isVisibilityExplicit() &&
1026 classLV.getVisibility() != DefaultVisibility &&
John McCall5f46c482013-02-21 23:42:58 +00001027 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1028 considerClassVisibility = false;
1029 }
1030
1031 // Finally, merge in information from the class.
1032 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
John McCall457a04e2010-10-22 21:05:15 +00001033 return LV;
John McCall8823c652010-08-13 08:35:10 +00001034}
1035
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001036void NamedDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00001037
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001038bool NamedDecl::isLinkageValid() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001039 if (!hasCachedLinkage())
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001040 return true;
John McCalld396b972011-02-08 19:01:05 +00001041
Richard Smithfbe7b462017-09-22 02:22:32 +00001042 Linkage L = LinkageComputer{}
1043 .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1044 .getLinkage();
George Burgess IV99db3ea2017-08-09 04:02:49 +00001045 return L == getCachedLinkage();
John McCalld396b972011-02-08 19:01:05 +00001046}
1047
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001048ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1049 StringRef name = getName();
1050 if (name.empty()) return SFF_None;
Fangrui Song6907ce22018-07-30 19:24:48 +00001051
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001052 if (name.front() == 'C')
1053 if (name == "CFStringCreateWithFormat" ||
1054 name == "CFStringCreateWithFormatAndArguments" ||
1055 name == "CFStringAppendFormat" ||
1056 name == "CFStringAppendFormatAndArguments")
1057 return SFF_CFString;
1058 return SFF_None;
1059}
1060
Rafael Espindola3ae00052013-05-13 00:12:11 +00001061Linkage NamedDecl::getLinkageInternal() const {
John McCalld041a9b2013-02-20 01:54:26 +00001062 // We don't care about visibility here, so ask for the cheapest
1063 // possible visibility analysis.
Richard Smithfbe7b462017-09-22 02:22:32 +00001064 return LinkageComputer{}
1065 .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1066 .getLinkage();
Douglas Gregorbf62d642010-12-06 18:36:25 +00001067}
1068
John McCallc273f242010-10-30 11:50:40 +00001069LinkageInfo NamedDecl::getLinkageAndVisibility() const {
George Burgess IV99db3ea2017-08-09 04:02:49 +00001070 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
John McCall033caa52010-10-29 00:29:13 +00001071}
Ted Kremenek926d8602010-04-20 23:15:35 +00001072
Rafael Espindola9ad61122013-11-26 16:09:08 +00001073static Optional<Visibility>
1074getExplicitVisibilityAux(const NamedDecl *ND,
1075 NamedDecl::ExplicitVisibilityKind kind,
1076 bool IsMostRecent) {
1077 assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1078
Rafael Espindola3a52c442013-02-26 19:33:14 +00001079 // Check the declaration itself first.
Rafael Espindola9ad61122013-11-26 16:09:08 +00001080 if (Optional<Visibility> V = getVisibilityOf(ND, kind))
Rafael Espindola3a52c442013-02-26 19:33:14 +00001081 return V;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001082
Rafael Espindola3a52c442013-02-26 19:33:14 +00001083 // If this is a member class of a specialization of a class template
1084 // and the corresponding decl has explicit visibility, use that.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001085 if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
Rafael Espindola3a52c442013-02-26 19:33:14 +00001086 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1087 if (InstantiatedFrom)
1088 return getVisibilityOf(InstantiatedFrom, kind);
1089 }
1090
1091 // If there wasn't explicit visibility there, and this is a
1092 // specialization of a class template, check for visibility
1093 // on the pattern.
Steven Wu79cbd112018-04-19 15:46:43 +00001094 if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1095 // Walk all the template decl till this point to see if there are
1096 // explicit visibility attributes.
1097 const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1098 while (TD != nullptr) {
1099 auto Vis = getVisibilityOf(TD, kind);
1100 if (Vis != None)
1101 return Vis;
1102 TD = TD->getPreviousDecl();
1103 }
1104 return None;
1105 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001106
1107 // Use the most recent declaration.
Rafael Espindola7ab1ce02013-12-08 01:13:22 +00001108 if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
Rafael Espindola9ad61122013-11-26 16:09:08 +00001109 const NamedDecl *MostRecent = ND->getMostRecentDecl();
1110 if (MostRecent != ND)
1111 return getExplicitVisibilityAux(MostRecent, kind, true);
1112 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001113
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001114 if (const auto *Var = dyn_cast<VarDecl>(ND)) {
Rafael Espindola96e68242012-05-16 02:10:38 +00001115 if (Var->isStaticDataMember()) {
1116 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1117 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001118 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola96e68242012-05-16 02:10:38 +00001119 }
1120
David Majnemer35b02bc2014-04-29 07:32:26 +00001121 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1122 return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1123 kind);
1124
David Blaikie7a30dc52013-02-21 01:47:18 +00001125 return None;
Rafael Espindola96e68242012-05-16 02:10:38 +00001126 }
Rafael Espindola3a52c442013-02-26 19:33:14 +00001127 // Also handle function template specializations.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001128 if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001129 // If the function is a specialization of a template with an
1130 // explicit visibility attribute, use that.
1131 if (FunctionTemplateSpecializationInfo *templateInfo
1132 = fn->getTemplateSpecializationInfo())
John McCalld041a9b2013-02-20 01:54:26 +00001133 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1134 kind);
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001135
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001136 // If the function is a member of a specialization of a class template
1137 // and the corresponding decl has explicit visibility, use that.
1138 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1139 if (InstantiatedFrom)
John McCalld041a9b2013-02-20 01:54:26 +00001140 return getVisibilityOf(InstantiatedFrom, kind);
Rafael Espindola8093fdf2012-02-23 04:17:32 +00001141
David Blaikie7a30dc52013-02-21 01:47:18 +00001142 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001143 }
1144
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001145 // The visibility of a template is stored in the templated decl.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001146 if (const auto *TD = dyn_cast<TemplateDecl>(ND))
John McCalld041a9b2013-02-20 01:54:26 +00001147 return getVisibilityOf(TD->getTemplatedDecl(), kind);
Rafael Espindolafb4263f2012-07-31 19:02:02 +00001148
David Blaikie7a30dc52013-02-21 01:47:18 +00001149 return None;
Douglas Gregor1baf38f2011-03-26 12:10:19 +00001150}
1151
Rafael Espindola9ad61122013-11-26 16:09:08 +00001152Optional<Visibility>
1153NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1154 return getExplicitVisibilityAux(this, kind, false);
1155}
1156
George Burgess IV99db3ea2017-08-09 04:02:49 +00001157LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1158 Decl *ContextDecl,
1159 LVComputationKind computation) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001160 // This lambda has its linkage/visibility determined by its owner.
Richard Smithc95d2c52017-09-22 04:25:05 +00001161 const NamedDecl *Owner;
1162 if (!ContextDecl)
1163 Owner = dyn_cast<NamedDecl>(DC);
1164 else if (isa<ParmVarDecl>(ContextDecl))
1165 Owner =
1166 dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1167 else
1168 Owner = cast<NamedDecl>(ContextDecl);
1169
Richard Smithc95d2c52017-09-22 04:25:05 +00001170 if (!Owner)
Richard Smith7ff83042017-09-22 04:33:20 +00001171 return LinkageInfo::none();
Richard Smithc95d2c52017-09-22 04:25:05 +00001172
1173 // If the owner has a deduced type, we need to skip querying the linkage and
1174 // visibility of that type, because it might involve this closure type. The
1175 // only effect of this is that we might give a lambda VisibleNoLinkage rather
1176 // than NoLinkage when we don't strictly need to, which is benign.
1177 auto *VD = dyn_cast<VarDecl>(Owner);
Richard Smith7ff83042017-09-22 04:33:20 +00001178 LinkageInfo OwnerLV =
Richard Smithc95d2c52017-09-22 04:25:05 +00001179 VD && VD->getType()->getContainedDeducedType()
1180 ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1181 : getLVForDecl(Owner, computation);
1182
Richard Smith7ff83042017-09-22 04:33:20 +00001183 // A lambda never formally has linkage. But if the owner is externally
1184 // visible, then the lambda is too. We apply the same rules to blocks.
1185 if (!isExternallyVisible(OwnerLV.getLinkage()))
1186 return LinkageInfo::none();
1187 return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1188 OwnerLV.isVisibilityExplicit());
Eli Friedman7e346a82013-07-01 20:22:57 +00001189}
1190
George Burgess IV99db3ea2017-08-09 04:02:49 +00001191LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1192 LVComputationKind computation) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001193 if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
John McCalldf25c432013-02-16 00:17:33 +00001194 if (Function->isInAnonymousNamespace() &&
Richard Smith99f54792018-01-03 02:34:35 +00001195 !isFirstInExternCContext(Function))
Richard Smithdf963a32017-09-22 22:21:44 +00001196 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001197
1198 // This is a "void f();" which got merged with a file static.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001199 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
Richard Smith1283e982017-07-07 20:04:28 +00001200 return getInternalLinkageFor(Function);
John McCalldf25c432013-02-16 00:17:33 +00001201
1202 LinkageInfo LV;
John McCalld041a9b2013-02-20 01:54:26 +00001203 if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001204 if (Optional<Visibility> Vis =
1205 getExplicitVisibility(Function, computation))
John McCalldf25c432013-02-16 00:17:33 +00001206 LV.mergeVisibility(*Vis, true);
1207 }
1208
1209 // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1210 // merging storage classes and visibility attributes, so we don't have to
1211 // look at previous decls in here.
1212
1213 return LV;
1214 }
1215
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001216 if (const auto *Var = dyn_cast<VarDecl>(D)) {
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001217 if (Var->hasExternalStorage()) {
Richard Smith99f54792018-01-03 02:34:35 +00001218 if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
Richard Smithdf963a32017-09-22 22:21:44 +00001219 return getInternalLinkageFor(Var);
John McCalldf25c432013-02-16 00:17:33 +00001220
John McCalldf25c432013-02-16 00:17:33 +00001221 LinkageInfo LV;
1222 if (Var->getStorageClass() == SC_PrivateExtern)
1223 LV.mergeVisibility(HiddenVisibility, true);
John McCalld041a9b2013-02-20 01:54:26 +00001224 else if (!hasExplicitVisibilityAlready(computation)) {
David Blaikie05785d12013-02-20 22:23:23 +00001225 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
John McCalldf25c432013-02-16 00:17:33 +00001226 LV.mergeVisibility(*Vis, true);
1227 }
1228
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001229 if (const VarDecl *Prev = Var->getPreviousDecl()) {
1230 LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1231 if (PrevLV.getLinkage())
1232 LV.setLinkage(PrevLV.getLinkage());
1233 LV.mergeVisibility(PrevLV);
1234 }
1235
John McCalldf25c432013-02-16 00:17:33 +00001236 return LV;
1237 }
Rafael Espindolaa4184182013-06-17 20:04:51 +00001238
1239 if (!Var->isStaticLocal())
1240 return LinkageInfo::none();
John McCalldf25c432013-02-16 00:17:33 +00001241 }
1242
Rafael Espindolaa4184182013-06-17 20:04:51 +00001243 ASTContext &Context = D->getASTContext();
1244 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindola50df3a02013-05-25 17:16:20 +00001245 return LinkageInfo::none();
1246
Eli Friedman7e346a82013-07-01 20:22:57 +00001247 const Decl *OuterD = getOutermostFuncOrBlockContext(D);
Alexey Bataev0a47e652016-01-12 09:01:25 +00001248 if (!OuterD || OuterD->isInvalidDecl())
Rafael Espindola50df3a02013-05-25 17:16:20 +00001249 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001250
Eli Friedman7e346a82013-07-01 20:22:57 +00001251 LinkageInfo LV;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001252 if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001253 if (!BD->getBlockManglingNumber())
1254 return LinkageInfo::none();
Rafael Espindola52189362013-06-04 13:43:35 +00001255
Eli Friedman7e346a82013-07-01 20:22:57 +00001256 LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1257 BD->getBlockManglingContextDecl(), computation);
1258 } else {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001259 const auto *FD = cast<FunctionDecl>(OuterD);
Eli Friedman7e346a82013-07-01 20:22:57 +00001260 if (!FD->isInlined() &&
David Majnemer9963ade2014-12-16 04:52:14 +00001261 !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
Eli Friedman7e346a82013-07-01 20:22:57 +00001262 return LinkageInfo::none();
1263
Hiroshi Inoue03ff37d2018-08-22 05:43:27 +00001264 // If a function is hidden by -fvisibility-inlines-hidden option and
1265 // is not explicitly attributed as a hidden function,
1266 // we should not make static local variables in the function hidden.
Eli Friedman7e346a82013-07-01 20:22:57 +00001267 LV = getLVForDecl(FD, computation);
Reid Klecknera52d1512018-10-10 21:59:56 +00001268 if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1269 !LV.isVisibilityExplicit()) {
1270 assert(cast<VarDecl>(D)->isStaticLocal());
1271 // If this was an implicitly hidden inline method, check again for
1272 // explicit visibility on the parent class, and use that for static locals
1273 // if present.
1274 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1275 LV = getLVForDecl(MD->getParent(), computation);
1276 if (!LV.isVisibilityExplicit()) {
1277 Visibility globalVisibility =
1278 computation.isValueVisibility()
1279 ? Context.getLangOpts().getValueVisibilityMode()
1280 : Context.getLangOpts().getTypeVisibilityMode();
1281 return LinkageInfo(VisibleNoLinkage, globalVisibility,
1282 /*visibilityExplicit=*/false);
1283 }
1284 }
Eli Friedman7e346a82013-07-01 20:22:57 +00001285 }
Rafael Espindola111bb2e2013-05-27 14:50:21 +00001286 if (!isExternallyVisible(LV.getLinkage()))
Rafael Espindola50df3a02013-05-25 17:16:20 +00001287 return LinkageInfo::none();
1288 return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1289 LV.isVisibilityExplicit());
John McCalldf25c432013-02-16 00:17:33 +00001290}
1291
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001292static inline const CXXRecordDecl*
1293getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1294 const CXXRecordDecl *Ret = Record;
1295 while (Record && Record->isLambda()) {
1296 Ret = Record;
1297 if (!Record->getParent()) break;
1298 // Get the Containing Class of this Lambda Class
1299 Record = dyn_cast_or_null<CXXRecordDecl>(
1300 Record->getParent()->getParent());
1301 }
1302 return Ret;
1303}
1304
George Burgess IV99db3ea2017-08-09 04:02:49 +00001305LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
Richard Smithc95d2c52017-09-22 04:25:05 +00001306 LVComputationKind computation,
1307 bool IgnoreVarTypeLinkage) {
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001308 // Internal_linkage attribute overrides other considerations.
1309 if (D->hasAttr<InternalLinkageAttr>())
Richard Smith1283e982017-07-07 20:04:28 +00001310 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001311
Ted Kremenek926d8602010-04-20 23:15:35 +00001312 // Objective-C: treat all Objective-C declarations as having external
1313 // linkage.
John McCall033caa52010-10-29 00:29:13 +00001314 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +00001315 default:
1316 break;
Richard Smith97135cc2015-11-12 22:19:45 +00001317
1318 // Per C++ [basic.link]p2, only the names of objects, references,
1319 // functions, types, templates, namespaces, and values ever have linkage.
1320 //
1321 // Note that the name of a typedef, namespace alias, using declaration,
1322 // and so on are not the name of the corresponding type, namespace, or
1323 // declaration, so they do *not* have linkage.
Richard Smith97135cc2015-11-12 22:19:45 +00001324 case Decl::ImplicitParam:
1325 case Decl::Label:
1326 case Decl::NamespaceAlias:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001327 case Decl::ParmVar:
Richard Smith97135cc2015-11-12 22:19:45 +00001328 case Decl::Using:
1329 case Decl::UsingShadow:
1330 case Decl::UsingDirective:
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +00001331 return LinkageInfo::none();
Richard Smith97135cc2015-11-12 22:19:45 +00001332
Richard Smith26210db2015-11-13 03:52:13 +00001333 case Decl::EnumConstant:
1334 // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
Bruno Cardoso Lopes057c82c2017-07-01 00:06:27 +00001335 if (D->getASTContext().getLangOpts().CPlusPlus)
1336 return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1337 return LinkageInfo::visible_none();
Richard Smith26210db2015-11-13 03:52:13 +00001338
Richard Smith97135cc2015-11-12 22:19:45 +00001339 case Decl::Typedef:
1340 case Decl::TypeAlias:
1341 // A typedef declaration has linkage if it gives a type a name for
1342 // linkage purposes.
Vassil Vassilevb00ea082017-07-01 20:44:49 +00001343 if (!cast<TypedefNameDecl>(D)
Richard Smith97135cc2015-11-12 22:19:45 +00001344 ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1345 return LinkageInfo::none();
1346 break;
1347
John McCall457a04e2010-10-22 21:05:15 +00001348 case Decl::TemplateTemplateParm: // count these as external
1349 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +00001350 case Decl::ObjCAtDefsField:
1351 case Decl::ObjCCategory:
1352 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +00001353 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +00001354 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +00001355 case Decl::ObjCMethod:
1356 case Decl::ObjCProperty:
1357 case Decl::ObjCPropertyImpl:
1358 case Decl::ObjCProtocol:
Richard Smith1283e982017-07-07 20:04:28 +00001359 return getExternalLinkageFor(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00001360
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001361 case Decl::CXXRecord: {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001362 const auto *Record = cast<CXXRecordDecl>(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001363 if (Record->isLambda()) {
1364 if (!Record->getLambdaManglingNumber()) {
1365 // This lambda has no mangling number, so it's internal.
Richard Smith1283e982017-07-07 20:04:28 +00001366 return getInternalLinkageFor(D);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001367 }
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001368
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001369 // This lambda has its linkage/visibility determined:
Fangrui Song6907ce22018-07-30 19:24:48 +00001370 // - either by the outermost lambda if that lambda has no mangling
1371 // number.
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001372 // - or by the parent of the outer most lambda
Fangrui Song6907ce22018-07-30 19:24:48 +00001373 // This prevents infinite recursion in settings such as nested lambdas
1374 // used in NSDMI's, for e.g.
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001375 // struct L {
1376 // int t{};
Fangrui Song6907ce22018-07-30 19:24:48 +00001377 // int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001378 // };
Fangrui Song6907ce22018-07-30 19:24:48 +00001379 const CXXRecordDecl *OuterMostLambda =
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001380 getOutermostEnclosingLambda(Record);
1381 if (!OuterMostLambda->getLambdaManglingNumber())
Richard Smith1283e982017-07-07 20:04:28 +00001382 return getInternalLinkageFor(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00001383
Faisal Vali49b4c1f2013-10-01 02:51:53 +00001384 return getLVForClosure(
1385 OuterMostLambda->getDeclContext()->getRedeclContext(),
1386 OuterMostLambda->getLambdaContextDecl(), computation);
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001387 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001388
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001389 break;
1390 }
Ted Kremenek926d8602010-04-20 23:15:35 +00001391 }
1392
Douglas Gregorf73b2822009-11-25 22:24:25 +00001393 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +00001394 if (D->getDeclContext()->getRedeclContext()->isFileContext())
Richard Smithc95d2c52017-09-22 04:25:05 +00001395 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
Fangrui Song6907ce22018-07-30 19:24:48 +00001396
Douglas Gregorf73b2822009-11-25 22:24:25 +00001397 // C++ [basic.link]p5:
1398 // In addition, a member function, static data member, a named
1399 // class or enumeration of class scope, or an unnamed class or
1400 // enumeration defined in a class-scope typedef declaration such
1401 // that the class or enumeration has the typedef name for linkage
1402 // purposes (7.1.3), has external linkage if the name of the class
1403 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +00001404 if (D->getDeclContext()->isRecord())
Richard Smithc95d2c52017-09-22 04:25:05 +00001405 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001406
1407 // C++ [basic.link]p6:
1408 // The name of a function declared in block scope and the name of
1409 // an object declared by a block scope extern declaration have
1410 // linkage. If there is a visible declaration of an entity with
1411 // linkage having the same name and type, ignoring entities
1412 // declared outside the innermost enclosing namespace scope, the
1413 // block scope declaration declares that same entity and receives
1414 // the linkage of the previous declaration. If there is more than
1415 // one such matching entity, the program is ill-formed. Otherwise,
1416 // if no matching entity is found, the block scope entity receives
1417 // external linkage.
John McCalldf25c432013-02-16 00:17:33 +00001418 if (D->getDeclContext()->isFunctionOrMethod())
1419 return getLVForLocalDecl(D, computation);
Douglas Gregorf73b2822009-11-25 22:24:25 +00001420
1421 // C++ [basic.link]p6:
1422 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +00001423 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +00001424}
Douglas Gregorf73b2822009-11-25 22:24:25 +00001425
George Burgess IV99db3ea2017-08-09 04:02:49 +00001426/// getLVForDecl - Get the linkage and visibility for the given declaration.
1427LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1428 LVComputationKind computation) {
1429 // Internal_linkage attribute overrides other considerations.
1430 if (D->hasAttr<InternalLinkageAttr>())
1431 return getInternalLinkageFor(D);
Evgeniy Stepanovae6ebd32015-11-10 21:28:44 +00001432
Richard Smithfbe7b462017-09-22 02:22:32 +00001433 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
George Burgess IV99db3ea2017-08-09 04:02:49 +00001434 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001435
George Burgess IV35cb4f82017-08-09 04:12:17 +00001436 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1437 return *LI;
1438
George Burgess IV99db3ea2017-08-09 04:02:49 +00001439 LinkageInfo LV = computeLVForDecl(D, computation);
1440 if (D->hasCachedLinkage())
1441 assert(D->getCachedLinkage() == LV.getLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001442
George Burgess IV99db3ea2017-08-09 04:02:49 +00001443 D->setCachedLinkage(LV.getLinkage());
George Burgess IV35cb4f82017-08-09 04:12:17 +00001444 cache(D, computation, LV);
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001445
1446#ifndef NDEBUG
George Burgess IV99db3ea2017-08-09 04:02:49 +00001447 // In C (because of gnu inline) and in c++ with microsoft extensions an
1448 // static can follow an extern, so we can have two decls with different
1449 // linkages.
1450 const LangOptions &Opts = D->getASTContext().getLangOpts();
1451 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1452 return LV;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001453
George Burgess IV99db3ea2017-08-09 04:02:49 +00001454 // We have just computed the linkage for this decl. By induction we know
1455 // that all other computed linkages match, check that the one we just
1456 // computed also does.
1457 NamedDecl *Old = nullptr;
1458 for (auto I : D->redecls()) {
1459 auto *T = cast<NamedDecl>(I);
1460 if (T == D)
1461 continue;
1462 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1463 Old = T;
1464 break;
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001465 }
George Burgess IV99db3ea2017-08-09 04:02:49 +00001466 }
1467 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001468#endif
1469
George Burgess IV99db3ea2017-08-09 04:02:49 +00001470 return LV;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001471}
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001472
George Burgess IV99db3ea2017-08-09 04:02:49 +00001473LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
Richard Smithfbe7b462017-09-22 02:22:32 +00001474 return getLVForDecl(D,
1475 LVComputationKind(usesTypeVisibility(D)
1476 ? NamedDecl::VisibilityForType
1477 : NamedDecl::VisibilityForValue));
Rafael Espindola9551d3b2013-05-28 19:43:11 +00001478}
1479
Richard Smithbecb92d2017-10-10 22:33:17 +00001480Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
Richard Smithdd8b5332017-09-04 05:37:53 +00001481 Module *M = getOwningModule();
1482 if (!M)
1483 return nullptr;
1484
1485 switch (M->Kind) {
1486 case Module::ModuleMapModule:
1487 // Module map modules have no special linkage semantics.
1488 return nullptr;
1489
1490 case Module::ModuleInterfaceUnit:
1491 return M;
1492
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001493 case Module::GlobalModuleFragment: {
Richard Smithdd8b5332017-09-04 05:37:53 +00001494 // External linkage declarations in the global module have no owning module
1495 // for linkage purposes. But internal linkage declarations in the global
1496 // module fragment of a particular module are owned by that module for
1497 // linkage purposes.
Richard Smithbecb92d2017-10-10 22:33:17 +00001498 if (IgnoreLinkage)
1499 return nullptr;
1500 bool InternalLinkage;
1501 if (auto *ND = dyn_cast<NamedDecl>(this))
1502 InternalLinkage = !ND->hasExternalFormalLinkage();
1503 else {
1504 auto *NSD = dyn_cast<NamespaceDecl>(this);
1505 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1506 isInAnonymousNamespace();
1507 }
1508 return InternalLinkage ? M->Parent : nullptr;
Richard Smithdd8b5332017-09-04 05:37:53 +00001509 }
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001510 }
Richard Smithdd8b5332017-09-04 05:37:53 +00001511
1512 llvm_unreachable("unknown module kind");
1513}
1514
Richard Smith7873de02016-08-11 22:25:46 +00001515void NamedDecl::printName(raw_ostream &os) const {
1516 os << Name;
1517}
1518
Douglas Gregor2ada0482009-02-04 17:27:36 +00001519std::string NamedDecl::getQualifiedNameAsString() const {
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001520 std::string QualName;
1521 llvm::raw_string_ostream OS(QualName);
Aaron Ballman75ee4cc2014-01-03 18:42:48 +00001522 printQualifiedName(OS, getASTContext().getPrintingPolicy());
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001523 return OS.str();
1524}
1525
1526void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1527 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1528}
1529
1530void NamedDecl::printQualifiedName(raw_ostream &OS,
1531 const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +00001532 const DeclContext *Ctx = getDeclContext();
1533
Argyrios Kyrtzidisa166a2b2017-03-07 09:26:07 +00001534 // For ObjC methods, look through categories and use the interface as context.
1535 if (auto *MD = dyn_cast<ObjCMethodDecl>(this))
1536 if (auto *ID = MD->getClassInterface())
1537 Ctx = ID;
1538
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001539 if (Ctx->isFunctionOrMethod()) {
1540 printName(OS);
1541 return;
1542 }
Douglas Gregor2ada0482009-02-04 17:27:36 +00001543
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001544 using ContextsTy = SmallVector<const DeclContext *, 8>;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001545 ContextsTy Contexts;
1546
Sam McCall34f9d3f2018-02-02 13:34:47 +00001547 // Collect named contexts.
1548 while (Ctx) {
1549 if (isa<NamedDecl>(Ctx))
1550 Contexts.push_back(Ctx);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001551 Ctx = Ctx->getParent();
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001552 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001553
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001554 for (const DeclContext *DC : llvm::reverse(Contexts)) {
David Majnemerf7e36092016-06-23 00:15:04 +00001555 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
Benjamin Kramer9170e912013-02-22 15:46:01 +00001556 OS << Spec->getName();
Douglas Gregor85673582009-05-18 17:01:57 +00001557 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Serge Pavlov03e672c2017-11-28 16:14:14 +00001558 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
David Majnemerf7e36092016-06-23 00:15:04 +00001559 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
Richard Smith46dd5bb2014-05-30 22:16:51 +00001560 if (P.SuppressUnwrittenScope &&
1561 (ND->isAnonymousNamespace() || ND->isInline()))
1562 continue;
Reid Kleckner60103382015-12-16 02:04:40 +00001563 if (ND->isAnonymousNamespace()) {
1564 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1565 : "(anonymous namespace)");
1566 }
Sam Weinig07d211e2009-12-24 23:15:03 +00001567 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001568 OS << *ND;
David Majnemerf7e36092016-06-23 00:15:04 +00001569 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001570 if (!RD->getIdentifier())
David Blaikieabe1a392014-04-02 05:58:29 +00001571 OS << "(anonymous " << RD->getKindName() << ')';
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001572 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001573 OS << *RD;
David Majnemerf7e36092016-06-23 00:15:04 +00001574 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
Craig Topper36250ad2014-05-12 05:36:57 +00001575 const FunctionProtoType *FT = nullptr;
Sam Weinigb999f682009-12-28 03:19:38 +00001576 if (FD->hasWrittenPrototype())
Eli Friedman5c27c4c2012-08-30 22:22:09 +00001577 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
Sam Weinigb999f682009-12-28 03:19:38 +00001578
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001579 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +00001580 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +00001581 unsigned NumParams = FD->getNumParams();
1582 for (unsigned i = 0; i < NumParams; ++i) {
1583 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001584 OS << ", ";
Argyrios Kyrtzidisa18347e2012-05-05 04:20:37 +00001585 OS << FD->getParamDecl(i)->getType().stream(P);
Sam Weinigb999f682009-12-28 03:19:38 +00001586 }
1587
1588 if (FT->isVariadic()) {
1589 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001590 OS << ", ";
1591 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +00001592 }
1593 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001594 OS << ')';
David Majnemerf7e36092016-06-23 00:15:04 +00001595 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
Alexander Kornienko4f355322015-11-09 16:45:17 +00001596 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1597 // enumerator is declared in the scope that immediately contains
1598 // the enum-specifier. Each scoped enumerator is declared in the
1599 // scope of the enumeration.
Paul Robinsonf1838482017-12-21 21:47:22 +00001600 // For the case of unscoped enumerator, do not include in the qualified
Paul Robinsond1c3dd82017-12-26 18:01:19 +00001601 // name any information about its enum enclosing scope, as its visibility
Paul Robinsonf1838482017-12-21 21:47:22 +00001602 // is global.
1603 if (ED->isScoped())
Alexander Kornienko4f355322015-11-09 16:45:17 +00001604 OS << *ED;
1605 else
1606 continue;
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001607 } else {
David Majnemerf7e36092016-06-23 00:15:04 +00001608 OS << *cast<NamedDecl>(DC);
Benjamin Kramerd76b6982010-04-28 14:33:51 +00001609 }
1610 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +00001611 }
1612
Richard Smith7873de02016-08-11 22:25:46 +00001613 if (getDeclName() || isa<DecompositionDecl>(this))
Benjamin Kramerb89514a2011-10-14 18:45:37 +00001614 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +00001615 else
David Blaikieabe1a392014-04-02 05:58:29 +00001616 OS << "(anonymous)";
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001617}
Douglas Gregor2ada0482009-02-04 17:27:36 +00001618
Benjamin Kramer24ebf7c2013-02-23 13:53:57 +00001619void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1620 const PrintingPolicy &Policy,
1621 bool Qualified) const {
1622 if (Qualified)
1623 printQualifiedName(OS, Policy);
1624 else
1625 printName(OS);
Douglas Gregor2ada0482009-02-04 17:27:36 +00001626}
1627
Richard Smithe8292b12015-02-10 03:28:10 +00001628template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1629 return true;
1630}
1631static bool isRedeclarableImpl(...) { return false; }
1632static bool isRedeclarable(Decl::Kind K) {
1633 switch (K) {
1634#define DECL(Type, Base) \
1635 case Decl::Type: \
1636 return isRedeclarableImpl((Type##Decl *)nullptr);
1637#define ABSTRACT_DECL(DECL)
1638#include "clang/AST/DeclNodes.inc"
1639 }
1640 llvm_unreachable("unknown decl kind");
1641}
1642
1643bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001644 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1645
Richard Smithfe620d22015-03-05 23:24:12 +00001646 // Never replace one imported declaration with another; we need both results
1647 // when re-exporting.
1648 if (OldD->isFromASTFile() && isFromASTFile())
1649 return false;
1650
Richard Smith5cd86f82015-11-03 03:13:11 +00001651 // A kind mismatch implies that the declaration is not replaced.
1652 if (OldD->getKind() != getKind())
Richard Smithe8292b12015-02-10 03:28:10 +00001653 return false;
1654
Richard Smith5cd86f82015-11-03 03:13:11 +00001655 // For method declarations, we never replace. (Why?)
1656 if (isa<ObjCMethodDecl>(this))
1657 return false;
1658
1659 // For parameters, pick the newer one. This is either an error or (in
1660 // Objective-C) permitted as an extension.
1661 if (isa<ParmVarDecl>(this))
1662 return true;
1663
Richard Smithe8292b12015-02-10 03:28:10 +00001664 // Inline namespaces can give us two declarations with the same
1665 // name and kind in the same scope but different contexts; we should
1666 // keep both declarations in this case.
1667 if (!this->getDeclContext()->getRedeclContext()->Equals(
1668 OldD->getDeclContext()->getRedeclContext()))
1669 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001670
Richard Smith5cd86f82015-11-03 03:13:11 +00001671 // Using declarations can be replaced if they import the same name from the
1672 // same context.
Richard Smithe8292b12015-02-10 03:28:10 +00001673 if (auto *UD = dyn_cast<UsingDecl>(this)) {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001674 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001675 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001676 Context.getCanonicalNestedNameSpecifier(
Richard Smithe8292b12015-02-10 03:28:10 +00001677 cast<UsingDecl>(OldD)->getQualifier());
Douglas Gregora9d87bc2011-02-25 00:36:19 +00001678 }
Richard Smithe8292b12015-02-10 03:28:10 +00001679 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001680 ASTContext &Context = getASTContext();
Richard Smithe8292b12015-02-10 03:28:10 +00001681 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
Eli Friedman0eaf10b2013-08-20 00:39:40 +00001682 Context.getCanonicalNestedNameSpecifier(
1683 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1684 }
1685
Richard Smith5cd86f82015-11-03 03:13:11 +00001686 if (isRedeclarable(getKind())) {
1687 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1688 return false;
1689
1690 if (IsKnownNewer)
1691 return true;
1692
Richard Smithe8292b12015-02-10 03:28:10 +00001693 // Check whether this is actually newer than OldD. We want to keep the
1694 // newer declaration. This loop will usually only iterate once, because
1695 // OldD is usually the previous declaration.
1696 for (auto D : redecls()) {
1697 if (D == OldD)
1698 break;
1699
1700 // If we reach the canonical declaration, then OldD is not actually older
1701 // than this one.
1702 //
1703 // FIXME: In this case, we should not add this decl to the lookup table.
1704 if (D->isCanonicalDecl())
1705 return false;
1706 }
Richard Smith5cd86f82015-11-03 03:13:11 +00001707
1708 // It's a newer declaration of the same kind of declaration in the same
1709 // scope: we want this decl instead of the existing one.
1710 return true;
Richard Smithe8292b12015-02-10 03:28:10 +00001711 }
1712
Richard Smith5cd86f82015-11-03 03:13:11 +00001713 // In all other cases, we need to keep both declarations in case they have
1714 // different visibility. Any attempt to use the name will result in an
1715 // ambiguity if more than one is visible.
1716 return false;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001717}
1718
Douglas Gregoreddf4332009-02-24 20:03:32 +00001719bool NamedDecl::hasLinkage() const {
Rafael Espindola50df3a02013-05-25 17:16:20 +00001720 return getFormalLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +00001721}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001722
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +00001723NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +00001724 NamedDecl *ND = this;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001725 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001726 ND = UD->getTargetDecl();
1727
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001728 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001729 return AD->getClassInterface();
1730
Richard Smithf2005d32015-12-29 23:34:32 +00001731 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1732 return AD->getNamespace();
1733
Benjamin Kramerba0495a2012-03-08 21:00:45 +00001734 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +00001735}
1736
John McCalla8ae2222010-04-06 21:38:20 +00001737bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +00001738 if (!isCXXClassMember())
1739 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001740
John McCalla8ae2222010-04-06 21:38:20 +00001741 const NamedDecl *D = this;
1742 if (isa<UsingShadowDecl>(D))
1743 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1744
John McCall5e77d762013-04-16 07:28:30 +00001745 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +00001746 return true;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001747 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
Alp Tokera2794f92014-01-22 07:29:52 +00001748 return MD->isInstance();
John McCalla8ae2222010-04-06 21:38:20 +00001749 return false;
1750}
1751
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001752//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001753// DeclaratorDecl Implementation
1754//===----------------------------------------------------------------------===//
1755
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001756template <typename DeclT>
1757static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1758 if (decl->getNumTemplateParameterLists() > 0)
1759 return decl->getTemplateParameterList(0)->getTemplateLoc();
1760 else
1761 return decl->getInnerLocStart();
1762}
1763
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001764SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001765 TypeSourceInfo *TSI = getTypeSourceInfo();
1766 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001767 return SourceLocation();
1768}
1769
Douglas Gregor14454802011-02-25 02:25:35 +00001770void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1771 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001772 // Make sure the extended decl info is allocated.
1773 if (!hasExtInfo()) {
1774 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001775 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
John McCall3e11ebe2010-03-15 10:12:16 +00001776 // Allocate external info struct.
1777 DeclInfo = new (getASTContext()) ExtInfo;
1778 // Restore savedTInfo into (extended) decl info.
1779 getExtInfo()->TInfo = savedTInfo;
1780 }
1781 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001782 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001783 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001784 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001785 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001786 if (getExtInfo()->NumTemplParamLists == 0) {
1787 // Save type source info pointer.
1788 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1789 // Deallocate the extended decl info.
1790 getASTContext().Deallocate(getExtInfo());
1791 // Restore savedTInfo into (non-extended) decl info.
1792 DeclInfo = savedTInfo;
1793 }
1794 else
1795 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001796 }
1797 }
1798}
1799
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001800void DeclaratorDecl::setTemplateParameterListsInfo(
1801 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1802 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00001803 // Make sure the extended decl info is allocated.
1804 if (!hasExtInfo()) {
1805 // Save (non-extended) type source info pointer.
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00001806 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
Abramo Bagnara60804e12011-03-18 15:16:37 +00001807 // Allocate external info struct.
1808 DeclInfo = new (getASTContext()) ExtInfo;
1809 // Restore savedTInfo into (extended) decl info.
1810 getExtInfo()->TInfo = savedTInfo;
1811 }
1812 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001813 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00001814}
1815
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001816SourceLocation DeclaratorDecl::getOuterLocStart() const {
1817 return getTemplateOrInnerLocStart(this);
1818}
1819
Abramo Bagnaraea947882011-03-08 16:41:52 +00001820// Helper function: returns true if QT is or contains a type
1821// having a postfix component.
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001822static bool typeIsPostfix(QualType QT) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00001823 while (true) {
1824 const Type* T = QT.getTypePtr();
1825 switch (T->getTypeClass()) {
1826 default:
1827 return false;
1828 case Type::Pointer:
1829 QT = cast<PointerType>(T)->getPointeeType();
1830 break;
1831 case Type::BlockPointer:
1832 QT = cast<BlockPointerType>(T)->getPointeeType();
1833 break;
1834 case Type::MemberPointer:
1835 QT = cast<MemberPointerType>(T)->getPointeeType();
1836 break;
1837 case Type::LValueReference:
1838 case Type::RValueReference:
1839 QT = cast<ReferenceType>(T)->getPointeeType();
1840 break;
1841 case Type::PackExpansion:
1842 QT = cast<PackExpansionType>(T)->getPattern();
1843 break;
1844 case Type::Paren:
1845 case Type::ConstantArray:
1846 case Type::DependentSizedArray:
1847 case Type::IncompleteArray:
1848 case Type::VariableArray:
1849 case Type::FunctionProto:
1850 case Type::FunctionNoProto:
1851 return true;
1852 }
1853 }
1854}
1855
Abramo Bagnaraea947882011-03-08 16:41:52 +00001856SourceRange DeclaratorDecl::getSourceRange() const {
1857 SourceLocation RangeEnd = getLocation();
1858 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
Benjamin Kramer3a7cc812014-02-02 15:28:46 +00001859 // If the declaration has no name or the type extends past the name take the
1860 // end location of the type.
1861 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
Abramo Bagnaraea947882011-03-08 16:41:52 +00001862 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1863 }
1864 return SourceRange(getOuterLocStart(), RangeEnd);
1865}
1866
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001867void QualifierInfo::setTemplateParameterListsInfo(
1868 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001869 // Free previous template parameters (if any).
1870 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001871 Context.Deallocate(TemplParamLists);
Craig Topper36250ad2014-05-12 05:36:57 +00001872 TemplParamLists = nullptr;
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001873 NumTemplParamLists = 0;
1874 }
1875 // Set info on matched template parameter lists (if any).
Benjamin Kramer9cc210652015-08-05 09:40:49 +00001876 if (!TPLists.empty()) {
1877 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1878 NumTemplParamLists = TPLists.size();
1879 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001880 }
1881}
1882
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001883//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001884// VarDecl Implementation
1885//===----------------------------------------------------------------------===//
1886
Sebastian Redl833ef452010-01-26 22:01:41 +00001887const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1888 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001889 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001890 case SC_Auto: return "auto";
1891 case SC_Extern: return "extern";
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001892 case SC_PrivateExtern: return "__private_extern__";
1893 case SC_Register: return "register";
1894 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001895 }
1896
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001897 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001898}
1899
Richard Smith053f6c62014-05-16 23:01:30 +00001900VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1901 SourceLocation StartLoc, SourceLocation IdLoc,
1902 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1903 StorageClass SC)
1904 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
Eugene Zelenkode0215c2017-11-13 23:01:27 +00001905 redeclarable_base(C) {
Benjamin Kramera939c232014-03-15 18:54:13 +00001906 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1907 "VarDeclBitfields too large!");
1908 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1909 "ParmVarDeclBitfields too large!");
David Majnemerfa7bc782015-05-19 00:57:16 +00001910 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1911 "NonParmVarDeclBitfields too large!");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001912 AllBits = 0;
1913 VarDeclBits.SClass = SC;
1914 // Everything else is implicitly initialized to false.
1915}
1916
Abramo Bagnaradff19302011-03-08 08:55:46 +00001917VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1918 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001919 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001920 StorageClass S) {
Richard Smith053f6c62014-05-16 23:01:30 +00001921 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
Nuno Lopes394ec982008-12-17 23:39:55 +00001922}
1923
Douglas Gregor72172e92012-01-05 21:55:30 +00001924VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00001925 return new (C, ID)
1926 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1927 QualType(), nullptr, SC_None);
Douglas Gregor72172e92012-01-05 21:55:30 +00001928}
1929
Douglas Gregorbf62d642010-12-06 18:36:25 +00001930void VarDecl::setStorageClass(StorageClass SC) {
1931 assert(isLegalForVariable(SC));
John McCallbeaa11c2011-05-01 02:13:58 +00001932 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001933}
1934
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001935VarDecl::TLSKind VarDecl::getTLSKind() const {
1936 switch (VarDeclBits.TSCSpec) {
1937 case TSCS_unspecified:
Samuel Antaof8b50122015-07-13 22:54:53 +00001938 if (!hasAttr<ThreadAttr>() &&
1939 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1940 getASTContext().getTargetInfo().isTLSSupported() &&
1941 hasAttr<OMPThreadPrivateDeclAttr>()))
David Majnemer1b5baff2015-05-14 05:19:23 +00001942 return TLS_None;
Samuel Antaof8b50122015-07-13 22:54:53 +00001943 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1944 LangOptions::MSVC2015)) ||
1945 hasAttr<OMPThreadPrivateDeclAttr>())
David Majnemer1b5baff2015-05-14 05:19:23 +00001946 ? TLS_Dynamic
1947 : TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001948 case TSCS___thread: // Fall through.
1949 case TSCS__Thread_local:
Samuel Antaof8b50122015-07-13 22:54:53 +00001950 return TLS_Static;
Reid Kleckner7d6d2702014-05-01 03:16:47 +00001951 case TSCS_thread_local:
1952 return TLS_Dynamic;
1953 }
1954 llvm_unreachable("Unknown thread storage class specifier!");
1955}
1956
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001957SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001958 if (const Expr *Init = getInit()) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001959 SourceLocation InitEnd = Init->getEndLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00001960 // If Init is implicit, ignore its source range and fallback on
Nico Weberbbe13942013-01-22 17:00:09 +00001961 // DeclaratorDecl::getSourceRange() to handle postfix elements.
1962 if (InitEnd.isValid() && InitEnd != getLocation())
Argyrios Kyrtzidise0d64972012-10-08 23:08:41 +00001963 return SourceRange(getOuterLocStart(), InitEnd);
1964 }
Abramo Bagnaraea947882011-03-08 16:41:52 +00001965 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001966}
1967
Rafael Espindola88510672013-01-04 21:18:45 +00001968template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001969static LanguageLinkage getDeclLanguageLinkage(const T &D) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001970 // C++ [dcl.link]p1: All function types, function names with external linkage,
1971 // and variable names with external linkage have a language linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001972 if (!D.hasExternalFormalLinkage())
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001973 return NoLanguageLinkage;
1974
1975 // Language linkage is a C++ concept, but saying that everything else in C has
Rafael Espindola66748e92013-01-04 20:41:40 +00001976 // C language linkage fits the implementation nicely.
Rafael Espindola576127d2012-12-28 14:21:58 +00001977 ASTContext &Context = D.getASTContext();
1978 if (!Context.getLangOpts().CPlusPlus)
Rafael Espindolaf4187652013-02-14 01:18:37 +00001979 return CLanguageLinkage;
1980
Rafael Espindola5bda63f2013-02-14 01:47:04 +00001981 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1982 // language linkage of the names of class members and the function type of
1983 // class member functions.
Rafael Espindola576127d2012-12-28 14:21:58 +00001984 const DeclContext *DC = D.getDeclContext();
1985 if (DC->isRecord())
Rafael Espindolaf4187652013-02-14 01:18:37 +00001986 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001987
1988 // If the first decl is in an extern "C" context, any other redeclaration
1989 // will have C language linkage. If the first one is not in an extern "C"
1990 // context, we would have reported an error for any other decl being in one.
Rafael Espindola593537a2013-05-05 20:15:21 +00001991 if (isFirstInExternCContext(&D))
Rafael Espindolaf4187652013-02-14 01:18:37 +00001992 return CLanguageLinkage;
1993 return CXXLanguageLinkage;
Rafael Espindola576127d2012-12-28 14:21:58 +00001994}
1995
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001996template<typename T>
Alp Toker84212df2014-05-31 06:11:02 +00001997static bool isDeclExternC(const T &D) {
Rafael Espindola0e0d0092013-03-14 03:07:35 +00001998 // Since the context is ignored for class members, they can only have C++
1999 // language linkage or no language linkage.
2000 const DeclContext *DC = D.getDeclContext();
2001 if (DC->isRecord()) {
2002 assert(D.getASTContext().getLangOpts().CPlusPlus);
2003 return false;
2004 }
2005
2006 return D.getLanguageLinkage() == CLanguageLinkage;
2007}
2008
Rafael Espindolaf4187652013-02-14 01:18:37 +00002009LanguageLinkage VarDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002010 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002011}
2012
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002013bool VarDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002014 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002015}
2016
Rafael Espindola593537a2013-05-05 20:15:21 +00002017bool VarDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002018 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002019}
2020
2021bool VarDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002022 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002023}
2024
Rafael Espindola8db352d2013-10-17 15:37:26 +00002025VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002026
Nico Weber7f5015a2015-04-15 21:53:00 +00002027VarDecl::DefinitionKind
2028VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
Richard Smitha22d9a52017-12-02 00:55:48 +00002029 if (isThisDeclarationADemotedDefinition())
2030 return DeclarationOnly;
2031
Sebastian Redl35351a92010-01-31 22:27:38 +00002032 // C++ [basic.def]p2:
2033 // A declaration is a definition unless [...] it contains the 'extern'
2034 // specifier or a linkage-specification and neither an initializer [...],
Richard Smith62f19e72016-06-25 00:15:56 +00002035 // it declares a non-inline static data member in a class declaration [...],
2036 // it declares a static data member outside a class definition and the variable
2037 // was defined within the class with the constexpr specifier [...],
Richard Smith8809a0c2013-09-27 20:14:12 +00002038 // C++1y [temp.expl.spec]p15:
2039 // An explicit specialization of a static data member or an explicit
2040 // specialization of a static data member template is a definition if the
2041 // declaration includes an initializer; otherwise, it is a declaration.
2042 //
2043 // FIXME: How do you declare (but not define) a partial specialization of
2044 // a static data member template outside the containing class?
Sebastian Redl35351a92010-01-31 22:27:38 +00002045 if (isStaticDataMember()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002046 if (isOutOfLine() &&
Richard Smith62f19e72016-06-25 00:15:56 +00002047 !(getCanonicalDecl()->isInline() &&
2048 getCanonicalDecl()->isConstexpr()) &&
Richard Smith8809a0c2013-09-27 20:14:12 +00002049 (hasInit() ||
2050 // If the first declaration is out-of-line, this may be an
2051 // instantiation of an out-of-line partial specialization of a variable
2052 // template for which we have not yet instantiated the initializer.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002053 (getFirstDecl()->isOutOfLine()
Richard Smith8809a0c2013-09-27 20:14:12 +00002054 ? getTemplateSpecializationKind() == TSK_Undeclared
2055 : getTemplateSpecializationKind() !=
2056 TSK_ExplicitSpecialization) ||
2057 isa<VarTemplatePartialSpecializationDecl>(this)))
Sebastian Redl35351a92010-01-31 22:27:38 +00002058 return Definition;
Richard Smith62f19e72016-06-25 00:15:56 +00002059 else if (!isOutOfLine() && isInline())
2060 return Definition;
Sebastian Redl35351a92010-01-31 22:27:38 +00002061 else
2062 return DeclarationOnly;
2063 }
2064 // C99 6.7p5:
2065 // A definition of an identifier is a declaration for that identifier that
2066 // [...] causes storage to be reserved for that object.
2067 // Note: that applies for all non-file-scope objects.
2068 // C99 6.9.2p1:
2069 // If the declaration of an identifier for an object has file scope and an
2070 // initializer, the declaration is an external definition for the identifier
2071 if (hasInit())
2072 return Definition;
Rafael Espindolabff59562013-04-25 12:11:36 +00002073
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002074 if (hasDefiningAttr())
Rafael Espindolad53ffa02013-10-22 21:39:03 +00002075 return Definition;
2076
David Majnemerdd0bed12015-05-14 05:19:20 +00002077 if (const auto *SAA = getAttr<SelectAnyAttr>())
2078 if (!SAA->isInherited())
2079 return Definition;
2080
Richard Smith8809a0c2013-09-27 20:14:12 +00002081 // A variable template specialization (other than a static data member
2082 // template or an explicit specialization) is a declaration until we
2083 // instantiate its initializer.
Richard Smith435e6472017-12-02 02:48:42 +00002084 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2085 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2086 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2087 !VTSD->IsCompleteDefinition)
2088 return DeclarationOnly;
2089 }
Richard Smith8809a0c2013-09-27 20:14:12 +00002090
Nico Weber608e7682015-04-15 23:04:24 +00002091 if (hasExternalStorage())
Sebastian Redl35351a92010-01-31 22:27:38 +00002092 return DeclarationOnly;
Rafael Espindola8f326a52013-03-07 01:42:44 +00002093
Rafael Espindolabff59562013-04-25 12:11:36 +00002094 // [dcl.link] p7:
2095 // A declaration directly contained in a linkage-specification is treated
2096 // as if it contains the extern specifier for the purpose of determining
2097 // the linkage of the declared name and whether it is a definition.
Nico Weber608e7682015-04-15 23:04:24 +00002098 if (isSingleLineLanguageLinkage(*this))
Rafael Espindola327be3c2013-04-26 01:30:23 +00002099 return DeclarationOnly;
Rafael Espindolabff59562013-04-25 12:11:36 +00002100
Sebastian Redl35351a92010-01-31 22:27:38 +00002101 // C99 6.9.2p2:
2102 // A declaration of an object that has file scope without an initializer,
2103 // and without a storage class specifier or the scs 'static', constitutes
2104 // a tentative definition.
2105 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002106 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00002107 return TentativeDefinition;
2108
2109 // What's left is (in C, block-scope) declarations without initializers or
2110 // external storage. These are definitions.
2111 return Definition;
2112}
2113
Sebastian Redl35351a92010-01-31 22:27:38 +00002114VarDecl *VarDecl::getActingDefinition() {
2115 DefinitionKind Kind = isThisDeclarationADefinition();
2116 if (Kind != TentativeDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002117 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002118
Craig Topper36250ad2014-05-12 05:36:57 +00002119 VarDecl *LastTentative = nullptr;
Rafael Espindola8db352d2013-10-17 15:37:26 +00002120 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002121 for (auto I : First->redecls()) {
2122 Kind = I->isThisDeclarationADefinition();
Sebastian Redl35351a92010-01-31 22:27:38 +00002123 if (Kind == Definition)
Craig Topper36250ad2014-05-12 05:36:57 +00002124 return nullptr;
Sebastian Redl35351a92010-01-31 22:27:38 +00002125 else if (Kind == TentativeDefinition)
Aaron Ballman86c93902014-03-06 23:45:36 +00002126 LastTentative = I;
Sebastian Redl35351a92010-01-31 22:27:38 +00002127 }
2128 return LastTentative;
2129}
2130
Daniel Dunbar9d355812012-03-09 01:51:51 +00002131VarDecl *VarDecl::getDefinition(ASTContext &C) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002132 VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002133 for (auto I : First->redecls()) {
2134 if (I->isThisDeclarationADefinition(C) == Definition)
2135 return I;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002136 }
Craig Topper36250ad2014-05-12 05:36:57 +00002137 return nullptr;
Sebastian Redl5ca79842010-02-01 20:16:42 +00002138}
2139
Daniel Dunbar9d355812012-03-09 01:51:51 +00002140VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00002141 DefinitionKind Kind = DeclarationOnly;
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002142
Rafael Espindola8db352d2013-10-17 15:37:26 +00002143 const VarDecl *First = getFirstDecl();
Aaron Ballman86c93902014-03-06 23:45:36 +00002144 for (auto I : First->redecls()) {
2145 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00002146 if (Kind == Definition)
2147 break;
2148 }
John McCall37bb6c92010-10-29 22:22:43 +00002149
2150 return Kind;
2151}
2152
Sebastian Redl5ca79842010-02-01 20:16:42 +00002153const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002154 for (auto I : redecls()) {
2155 if (auto Expr = I->getInit()) {
2156 D = I;
2157 return Expr;
2158 }
Sebastian Redl833ef452010-01-26 22:01:41 +00002159 }
Craig Topper36250ad2014-05-12 05:36:57 +00002160 return nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002161}
2162
Chandler Carruth813faed2015-12-30 02:51:00 +00002163bool VarDecl::hasInit() const {
2164 if (auto *P = dyn_cast<ParmVarDecl>(this))
2165 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2166 return false;
2167
2168 return !Init.isNull();
2169}
2170
2171Expr *VarDecl::getInit() {
2172 if (!hasInit())
2173 return nullptr;
2174
2175 if (auto *S = Init.dyn_cast<Stmt *>())
2176 return cast<Expr>(S);
2177
2178 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2179}
2180
2181Stmt **VarDecl::getInitAddress() {
2182 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2183 return &ES->Value;
2184
2185 return Init.getAddrOfPtr1();
2186}
2187
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002188bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002189 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002190 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00002191
2192 if (!isStaticDataMember())
2193 return false;
2194
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002195 // If this static data member was instantiated from a static data member of
Fangrui Song6907ce22018-07-30 19:24:48 +00002196 // a class template, check whether that static data member was defined
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002197 // out-of-line.
2198 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2199 return VD->isOutOfLine();
Fangrui Song6907ce22018-07-30 19:24:48 +00002200
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002201 return false;
2202}
2203
Douglas Gregord5058122010-02-11 01:19:42 +00002204void VarDecl::setInit(Expr *I) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002205 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
Sebastian Redl833ef452010-01-26 22:01:41 +00002206 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00002207 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00002208 }
2209
2210 Init = I;
2211}
2212
Daniel Dunbar9d355812012-03-09 01:51:51 +00002213bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002214 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00002215
Richard Smith35ecb362012-03-02 04:14:40 +00002216 if (!Lang.CPlusPlus)
2217 return false;
2218
2219 // In C++11, any variable of reference type can be used in a constant
2220 // expression if it is initialized by a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002221 if (Lang.CPlusPlus11 && getType()->isReferenceType())
Richard Smith35ecb362012-03-02 04:14:40 +00002222 return true;
2223
2224 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00002225 // not require the variable to be non-volatile, but we consider this to be a
2226 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00002227 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00002228 return false;
2229
2230 // In C++, const, non-volatile variables of integral or enumeration types
2231 // can be used in constant expressions.
2232 if (getType()->isIntegralOrEnumerationType())
2233 return true;
2234
Richard Smith35ecb362012-03-02 04:14:40 +00002235 // Additionally, in C++11, non-volatile constexpr variables can be used in
2236 // constant expressions.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002237 return Lang.CPlusPlus11 && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00002238}
2239
Richard Smithd0b4dd62011-12-19 06:19:21 +00002240/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2241/// form, which contains extra information on the evaluated value of the
2242/// initializer.
2243EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002244 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002245 if (!Eval) {
Manuel Klimeka7328992013-06-03 13:51:33 +00002246 // Note: EvaluatedStmt contains an APValue, which usually holds
2247 // resources not allocated from the ASTContext. We need to do some
2248 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2249 // where we can detect whether there's anything to clean up or not.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002250 Eval = new (getASTContext()) EvaluatedStmt;
Chandler Carruth813faed2015-12-30 02:51:00 +00002251 Eval->Value = Init.get<Stmt *>();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002252 Init = Eval;
2253 }
2254 return Eval;
2255}
2256
Richard Smithdafff942012-01-14 04:30:29 +00002257APValue *VarDecl::evaluateValue() const {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002258 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithdafff942012-01-14 04:30:29 +00002259 return evaluateValue(Notes);
2260}
2261
2262APValue *VarDecl::evaluateValue(
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002263 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002264 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2265
2266 // We only produce notes indicating why an initializer is non-constant the
2267 // first time it is evaluated. FIXME: The notes won't always be emitted the
2268 // first time we try evaluation, so might not be produced at all.
2269 if (Eval->WasEvaluated)
Craig Topper36250ad2014-05-12 05:36:57 +00002270 return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002271
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002272 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002273 assert(!Init->isValueDependent());
2274
2275 if (Eval->IsEvaluating) {
2276 // FIXME: Produce a diagnostic for self-initialization.
2277 Eval->CheckedICE = true;
2278 Eval->IsICE = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002279 return nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002280 }
2281
2282 Eval->IsEvaluating = true;
2283
2284 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2285 this, Notes);
2286
Manuel Klimeka7328992013-06-03 13:51:33 +00002287 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2288 // or that it's empty (so that there's nothing to clean up) if evaluation
2289 // failed.
Richard Smithd0b4dd62011-12-19 06:19:21 +00002290 if (!Result)
2291 Eval->Evaluated = APValue();
Manuel Klimeka7328992013-06-03 13:51:33 +00002292 else if (Eval->Evaluated.needsCleanup())
George Burgess IVb61bfbd2017-02-14 05:37:36 +00002293 getASTContext().addDestruction(&Eval->Evaluated);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002294
2295 Eval->IsEvaluating = false;
2296 Eval->WasEvaluated = true;
2297
2298 // In C++11, we have determined whether the initializer was a constant
2299 // expression as a side-effect.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002300 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00002301 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00002302 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00002303 }
2304
Craig Topper36250ad2014-05-12 05:36:57 +00002305 return Result ? &Eval->Evaluated : nullptr;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002306}
2307
Chandler Carruth813faed2015-12-30 02:51:00 +00002308APValue *VarDecl::getEvaluatedValue() const {
2309 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2310 if (Eval->WasEvaluated)
2311 return &Eval->Evaluated;
2312
2313 return nullptr;
2314}
2315
2316bool VarDecl::isInitKnownICE() const {
2317 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2318 return Eval->CheckedICE;
2319
2320 return false;
2321}
2322
2323bool VarDecl::isInitICE() const {
2324 assert(isInitKnownICE() &&
2325 "Check whether we already know that the initializer is an ICE");
2326 return Init.get<EvaluatedStmt *>()->IsICE;
2327}
2328
Richard Smithd0b4dd62011-12-19 06:19:21 +00002329bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00002330 // Initializers of weak variables are never ICEs.
2331 if (isWeak())
2332 return false;
2333
Richard Smithd0b4dd62011-12-19 06:19:21 +00002334 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2335 if (Eval->CheckedICE)
2336 // We have already checked whether this subexpression is an
2337 // integral constant expression.
2338 return Eval->IsICE;
2339
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002340 const auto *Init = cast<Expr>(Eval->Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002341 assert(!Init->isValueDependent());
2342
2343 // In C++11, evaluate the initializer to check whether it's a constant
2344 // expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002345 if (getASTContext().getLangOpts().CPlusPlus11) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002346 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002347 evaluateValue(Notes);
2348 return Eval->IsICE;
2349 }
2350
2351 // It's an ICE whether or not the definition we found is
2352 // out-of-line. See DR 721 and the discussion in Clang PR
2353 // 6206 for details.
2354
2355 if (Eval->CheckingICE)
2356 return false;
2357 Eval->CheckingICE = true;
2358
2359 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2360 Eval->CheckingICE = false;
2361 Eval->CheckedICE = true;
2362 return Eval->IsICE;
2363}
2364
Richard Smith2195ec92017-04-21 01:15:13 +00002365template<typename DeclT>
2366static DeclT *getDefinitionOrSelf(DeclT *D) {
2367 assert(D);
2368 if (auto *Def = D->getDefinition())
2369 return Def;
2370 return D;
2371}
2372
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002373bool VarDecl::isEscapingByref() const {
2374 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2375}
2376
2377bool VarDecl::isNonEscapingByref() const {
2378 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2379}
2380
Richard Smithedbc6e92016-10-14 21:41:24 +00002381VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2382 // If it's a variable template specialization, find the template or partial
2383 // specialization from which it was instantiated.
2384 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2385 auto From = VDTemplSpec->getInstantiatedFrom();
2386 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2387 while (auto *NewVTD = VTD->getInstantiatedFromMemberTemplate()) {
2388 if (NewVTD->isMemberSpecialization())
2389 break;
2390 VTD = NewVTD;
2391 }
Richard Smith2195ec92017-04-21 01:15:13 +00002392 return getDefinitionOrSelf(VTD->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002393 }
2394 if (auto *VTPSD =
2395 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2396 while (auto *NewVTPSD = VTPSD->getInstantiatedFromMember()) {
2397 if (NewVTPSD->isMemberSpecialization())
2398 break;
2399 VTPSD = NewVTPSD;
2400 }
Richard Smith2195ec92017-04-21 01:15:13 +00002401 return getDefinitionOrSelf<VarDecl>(VTPSD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002402 }
2403 }
2404
2405 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
2406 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2407 VarDecl *VD = getInstantiatedFromStaticDataMember();
2408 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2409 VD = NewVD;
Richard Smith2195ec92017-04-21 01:15:13 +00002410 return getDefinitionOrSelf(VD);
Richard Smithedbc6e92016-10-14 21:41:24 +00002411 }
2412 }
2413
2414 if (VarTemplateDecl *VarTemplate = getDescribedVarTemplate()) {
Richard Smithedbc6e92016-10-14 21:41:24 +00002415 while (VarTemplate->getInstantiatedFromMemberTemplate()) {
2416 if (VarTemplate->isMemberSpecialization())
2417 break;
2418 VarTemplate = VarTemplate->getInstantiatedFromMemberTemplate();
2419 }
2420
Richard Smith2195ec92017-04-21 01:15:13 +00002421 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
Richard Smithedbc6e92016-10-14 21:41:24 +00002422 }
2423 return nullptr;
2424}
2425
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002426VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002427 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002428 return cast<VarDecl>(MSI->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00002429
2430 return nullptr;
Douglas Gregor86d142a2009-10-08 07:24:58 +00002431}
2432
Douglas Gregor3c74d412009-10-14 20:14:33 +00002433TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002434 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002435 return Spec->getSpecializationKind();
2436
Sebastian Redl35351a92010-01-31 22:27:38 +00002437 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002438 return MSI->getTemplateSpecializationKind();
Richard Smith8809a0c2013-09-27 20:14:12 +00002439
Douglas Gregor86d142a2009-10-08 07:24:58 +00002440 return TSK_Undeclared;
2441}
2442
Richard Smith8809a0c2013-09-27 20:14:12 +00002443SourceLocation VarDecl::getPointOfInstantiation() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002444 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
Richard Smith8809a0c2013-09-27 20:14:12 +00002445 return Spec->getPointOfInstantiation();
2446
2447 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2448 return MSI->getPointOfInstantiation();
2449
2450 return SourceLocation();
2451}
2452
Larisse Voufo39a1e502013-08-06 01:03:05 +00002453VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2454 return getASTContext().getTemplateOrSpecializationInfo(this)
2455 .dyn_cast<VarTemplateDecl *>();
2456}
2457
2458void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2459 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2460}
2461
Justin Lebar5489f852018-05-17 16:15:07 +00002462bool VarDecl::isKnownToBeDefined() const {
2463 const auto &LangOpts = getASTContext().getLangOpts();
2464 // In CUDA mode without relocatable device code, variables of form 'extern
2465 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2466 // memory pool. These are never undefined variables, even if they appear
2467 // inside of an anon namespace or static function.
2468 //
2469 // With CUDA relocatable device code enabled, these variables don't get
2470 // special handling; they're treated like regular extern variables.
Yaxun Liu97670892018-10-02 17:48:54 +00002471 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
Justin Lebar5489f852018-05-17 16:15:07 +00002472 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2473 isa<IncompleteArrayType>(getType()))
2474 return true;
2475
2476 return hasDefinition();
2477}
2478
Erik Pilkington5a559e62018-08-21 17:24:06 +00002479bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2480 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2481 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2482 !hasAttr<AlwaysDestroyAttr>()));
2483}
2484
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002485MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Richard Smithb71782b2013-08-01 04:12:04 +00002486 if (isStaticDataMember())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002487 // FIXME: Remove ?
2488 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2489 return getASTContext().getTemplateOrSpecializationInfo(this)
2490 .dyn_cast<MemberSpecializationInfo *>();
Craig Topper36250ad2014-05-12 05:36:57 +00002491 return nullptr;
Douglas Gregor06db9f52009-10-12 20:18:28 +00002492}
2493
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002494void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2495 SourceLocation PointOfInstantiation) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002496 assert((isa<VarTemplateSpecializationDecl>(this) ||
2497 getMemberSpecializationInfo()) &&
2498 "not a variable or static data member template specialization");
2499
Larisse Voufo39a1e502013-08-06 01:03:05 +00002500 if (VarTemplateSpecializationDecl *Spec =
2501 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2502 Spec->setSpecializationKind(TSK);
2503 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002504 Spec->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002505 Spec->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002506 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2507 L->InstantiationRequested(this);
2508 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002509 }
2510
2511 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2512 MSI->setTemplateSpecializationKind(TSK);
2513 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00002514 MSI->getPointOfInstantiation().isInvalid()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002515 MSI->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002516 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2517 L->InstantiationRequested(this);
2518 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002519 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00002520}
2521
2522void
2523VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2524 TemplateSpecializationKind TSK) {
2525 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2526 "Previous template or instantiation?");
2527 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002528}
2529
Sebastian Redl833ef452010-01-26 22:01:41 +00002530//===----------------------------------------------------------------------===//
2531// ParmVarDecl Implementation
2532//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00002533
Sebastian Redl833ef452010-01-26 22:01:41 +00002534ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002535 SourceLocation StartLoc,
2536 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00002537 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002538 StorageClass S, Expr *DefArg) {
Richard Smith053f6c62014-05-16 23:01:30 +00002539 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smithf7981722013-11-22 09:01:48 +00002540 S, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00002541}
2542
Reid Kleckner8a365022013-06-24 17:51:48 +00002543QualType ParmVarDecl::getOriginalType() const {
2544 TypeSourceInfo *TSI = getTypeSourceInfo();
2545 QualType T = TSI ? TSI->getType() : getType();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002546 if (const auto *DT = dyn_cast<DecayedType>(T))
Reid Kleckner8a365022013-06-24 17:51:48 +00002547 return DT->getOriginalType();
2548 return T;
2549}
2550
Douglas Gregor72172e92012-01-05 21:55:30 +00002551ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00002552 return new (C, ID)
2553 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2554 nullptr, QualType(), nullptr, SC_None, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00002555}
2556
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002557SourceRange ParmVarDecl::getSourceRange() const {
2558 if (!hasInheritedDefaultArg()) {
2559 SourceRange ArgRange = getDefaultArgRange();
2560 if (ArgRange.isValid())
2561 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2562 }
2563
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002564 // DeclaratorDecl considers the range of postfix types as overlapping with the
2565 // declaration name, but this is not the case with parameters in ObjC methods.
2566 if (isa<ObjCMethodDecl>(getDeclContext()))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002567 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
Argyrios Kyrtzidisa0772792013-04-17 01:56:48 +00002568
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00002569 return DeclaratorDecl::getSourceRange();
2570}
2571
Sebastian Redl833ef452010-01-26 22:01:41 +00002572Expr *ParmVarDecl::getDefaultArg() {
2573 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2574 assert(!hasUninstantiatedDefaultArg() &&
2575 "Default argument is not yet instantiated!");
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002576
Sebastian Redl833ef452010-01-26 22:01:41 +00002577 Expr *Arg = getInit();
Bill Wendling7c44da22018-10-31 03:48:47 +00002578 if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00002579 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00002580
Sebastian Redl833ef452010-01-26 22:01:41 +00002581 return Arg;
2582}
2583
Chandler Carruth813faed2015-12-30 02:51:00 +00002584void ParmVarDecl::setDefaultArg(Expr *defarg) {
2585 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2586 Init = defarg;
2587}
Sebastian Redl833ef452010-01-26 22:01:41 +00002588
Chandler Carruth813faed2015-12-30 02:51:00 +00002589SourceRange ParmVarDecl::getDefaultArgRange() const {
2590 switch (ParmVarDeclBits.DefaultArgKind) {
2591 case DAK_None:
2592 case DAK_Unparsed:
2593 // Nothing we can do here.
2594 return SourceRange();
2595
2596 case DAK_Uninstantiated:
Sebastian Redl833ef452010-01-26 22:01:41 +00002597 return getUninstantiatedDefaultArg()->getSourceRange();
2598
Chandler Carruth813faed2015-12-30 02:51:00 +00002599 case DAK_Normal:
2600 if (const Expr *E = getInit())
2601 return E->getSourceRange();
2602
2603 // Missing an actual expression, may be invalid.
2604 return SourceRange();
2605 }
2606 llvm_unreachable("Invalid default argument kind.");
2607}
2608
2609void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2610 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2611 Init = arg;
2612}
2613
2614Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2615 assert(hasUninstantiatedDefaultArg() &&
2616 "Wrong kind of initialization expression!");
2617 return cast_or_null<Expr>(Init.get<Stmt *>());
2618}
2619
2620bool ParmVarDecl::hasDefaultArg() const {
2621 // FIXME: We should just return false for DAK_None here once callers are
2622 // prepared for the case that we encountered an invalid default argument and
2623 // were unable to even build an invalid expression.
2624 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2625 !Init.isNull();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00002626}
2627
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00002628bool ParmVarDecl::isParameterPack() const {
2629 return isa<PackExpansionType>(getType());
2630}
2631
Ted Kremenek540017e2011-10-06 05:00:56 +00002632void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2633 getASTContext().setParameterIndex(this, parameterIndex);
2634 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2635}
2636
2637unsigned ParmVarDecl::getParameterIndexLarge() const {
2638 return getASTContext().getParameterIndex(this);
2639}
2640
Nuno Lopes394ec982008-12-17 23:39:55 +00002641//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002642// FunctionDecl Implementation
2643//===----------------------------------------------------------------------===//
2644
Erich Keane9c665062018-08-01 21:02:40 +00002645FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2646 SourceLocation StartLoc,
2647 const DeclarationNameInfo &NameInfo, QualType T,
2648 TypeSourceInfo *TInfo, StorageClass S,
2649 bool isInlineSpecified, bool isConstexprSpecified)
2650 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2651 StartLoc),
2652 DeclContext(DK), redeclarable_base(C), ODRHash(0),
2653 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
Jonas Devlieghere64a26302018-11-11 00:56:15 +00002654 assert(T.isNull() || T->isFunctionType());
Bruno Ricci0b639da2018-12-03 13:04:10 +00002655 FunctionDeclBits.SClass = S;
2656 FunctionDeclBits.IsInline = isInlineSpecified;
2657 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2658 FunctionDeclBits.IsExplicitSpecified = false;
2659 FunctionDeclBits.IsVirtualAsWritten = false;
2660 FunctionDeclBits.IsPure = false;
2661 FunctionDeclBits.HasInheritedPrototype = false;
2662 FunctionDeclBits.HasWrittenPrototype = true;
2663 FunctionDeclBits.IsDeleted = false;
2664 FunctionDeclBits.IsTrivial = false;
2665 FunctionDeclBits.IsTrivialForCall = false;
2666 FunctionDeclBits.IsDefaulted = false;
2667 FunctionDeclBits.IsExplicitlyDefaulted = false;
2668 FunctionDeclBits.HasImplicitReturnZero = false;
2669 FunctionDeclBits.IsLateTemplateParsed = false;
2670 FunctionDeclBits.IsConstexpr = isConstexprSpecified;
2671 FunctionDeclBits.InstantiationIsPending = false;
2672 FunctionDeclBits.UsesSEHTry = false;
2673 FunctionDeclBits.HasSkippedBody = false;
2674 FunctionDeclBits.WillHaveBody = false;
2675 FunctionDeclBits.IsMultiVersion = false;
2676 FunctionDeclBits.IsCopyDeductionCandidate = false;
2677 FunctionDeclBits.HasODRHash = false;
Erich Keane9c665062018-08-01 21:02:40 +00002678}
2679
Benjamin Kramer9170e912013-02-22 15:46:01 +00002680void FunctionDecl::getNameForDiagnostic(
2681 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2682 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002683 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2684 if (TemplateArgs)
Serge Pavlov03e672c2017-11-28 16:14:14 +00002685 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
Douglas Gregorb11aad82011-02-19 18:51:44 +00002686}
2687
Ted Kremenek186a0742010-04-29 16:49:01 +00002688bool FunctionDecl::isVariadic() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002689 if (const auto *FT = getType()->getAs<FunctionProtoType>())
Ted Kremenek186a0742010-04-29 16:49:01 +00002690 return FT->isVariadic();
2691 return false;
2692}
2693
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002694bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002695 for (auto I : redecls()) {
Serge Pavlov9a618e12017-02-15 12:30:35 +00002696 if (I->doesThisDeclarationHaveABody()) {
Aaron Ballman86c93902014-03-06 23:45:36 +00002697 Definition = I;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002698 return true;
2699 }
2700 }
2701
2702 return false;
2703}
2704
Anders Carlsson9bd7d162011-05-14 23:26:09 +00002705bool FunctionDecl::hasTrivialBody() const
2706{
2707 Stmt *S = getBody();
2708 if (!S) {
2709 // Since we don't have a body for this function, we don't know if it's
2710 // trivial or not.
2711 return false;
2712 }
2713
2714 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2715 return true;
2716 return false;
2717}
2718
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002719bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
Aaron Ballman86c93902014-03-06 23:45:36 +00002720 for (auto I : redecls()) {
Serge Pavlov10673c92017-06-04 12:53:12 +00002721 if (I->isThisDeclarationADefinition()) {
2722 Definition = I;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002723 return true;
2724 }
2725 }
2726
2727 return false;
2728}
2729
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002730Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Rafael Espindola44503012013-10-19 01:37:17 +00002731 if (!hasBody(Definition))
Craig Topper36250ad2014-05-12 05:36:57 +00002732 return nullptr;
Rafael Espindola44503012013-10-19 01:37:17 +00002733
2734 if (Definition->Body)
2735 return Definition->Body.get(getASTContext().getExternalSource());
Douglas Gregor89f238c2008-04-21 02:02:58 +00002736
Craig Topper36250ad2014-05-12 05:36:57 +00002737 return nullptr;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002738}
2739
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002740void FunctionDecl::setBody(Stmt *B) {
2741 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00002742 if (B)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002743 EndRangeLoc = B->getEndLoc();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00002744}
2745
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002746void FunctionDecl::setPure(bool P) {
Erich Keane9c665062018-08-01 21:02:40 +00002747 FunctionDeclBits.IsPure = P;
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002748 if (P)
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002749 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
Douglas Gregor7d9120c2010-09-28 21:55:22 +00002750 Parent->markedVirtualFunctionPure();
2751}
2752
Richard Smith8d0dc312013-07-21 23:12:18 +00002753template<std::size_t Len>
2754static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2755 IdentifierInfo *II = ND->getIdentifier();
2756 return II && II->isStr(Str);
2757}
2758
Douglas Gregor16618f22009-09-12 00:17:51 +00002759bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00002760 const TranslationUnitDecl *tunit =
2761 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2762 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002763 !tunit->getASTContext().getLangOpts().Freestanding &&
Richard Smith8d0dc312013-07-21 23:12:18 +00002764 isNamed(this, "main");
John McCall53ffd372011-05-15 17:49:20 +00002765}
2766
David Majnemerc729b0b2013-09-16 22:44:20 +00002767bool FunctionDecl::isMSVCRTEntryPoint() const {
2768 const TranslationUnitDecl *TUnit =
2769 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2770 if (!TUnit)
2771 return false;
2772
2773 // Even though we aren't really targeting MSVCRT if we are freestanding,
2774 // semantic analysis for these functions remains the same.
2775
2776 // MSVCRT entry points only exist on MSVCRT targets.
2777 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2778 return false;
2779
2780 // Nameless functions like constructors cannot be entry points.
2781 if (!getIdentifier())
2782 return false;
2783
2784 return llvm::StringSwitch<bool>(getName())
2785 .Cases("main", // an ANSI console app
2786 "wmain", // a Unicode console App
2787 "WinMain", // an ANSI GUI app
2788 "wWinMain", // a Unicode GUI app
2789 "DllMain", // a DLL
2790 true)
2791 .Default(false);
2792}
2793
John McCall53ffd372011-05-15 17:49:20 +00002794bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2795 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2796 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2797 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2798 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2799 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2800
Richard Smithf6004412014-01-19 23:25:37 +00002801 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2802 return false;
John McCall53ffd372011-05-15 17:49:20 +00002803
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002804 const auto *proto = getType()->castAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002805 if (proto->getNumParams() != 2 || proto->isVariadic())
2806 return false;
John McCall53ffd372011-05-15 17:49:20 +00002807
2808 ASTContext &Context =
2809 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2810 ->getASTContext();
2811
2812 // The result type and first argument type are constant across all
2813 // these operators. The second argument must be exactly void*.
Alp Toker9cacbab2014-01-20 20:26:09 +00002814 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00002815}
2816
Akira Hatanakacae83f72017-06-29 18:48:40 +00002817bool FunctionDecl::isReplaceableGlobalAllocationFunction(bool *IsAligned) const {
Richard Smith8d0dc312013-07-21 23:12:18 +00002818 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2819 return false;
2820 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2821 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2822 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2823 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2824 return false;
2825
2826 if (isa<CXXRecordDecl>(getDeclContext()))
2827 return false;
Richard Smithf6004412014-01-19 23:25:37 +00002828
2829 // This can only fail for an invalid 'operator new' declaration.
2830 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2831 return false;
Richard Smith8d0dc312013-07-21 23:12:18 +00002832
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002833 const auto *FPT = getType()->castAs<FunctionProtoType>();
Richard Smithb2f0f052016-10-10 18:54:32 +00002834 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
Richard Smith8d0dc312013-07-21 23:12:18 +00002835 return false;
2836
2837 // If this is a single-parameter function, it must be a replaceable global
2838 // allocation or deallocation function.
Alp Toker9cacbab2014-01-20 20:26:09 +00002839 if (FPT->getNumParams() == 1)
Richard Smith8d0dc312013-07-21 23:12:18 +00002840 return true;
2841
Richard Smithb2f0f052016-10-10 18:54:32 +00002842 unsigned Params = 1;
2843 QualType Ty = FPT->getParamType(Params);
Richard Smith1cdec012013-09-29 04:40:38 +00002844 ASTContext &Ctx = getASTContext();
Richard Smithb2f0f052016-10-10 18:54:32 +00002845
2846 auto Consume = [&] {
2847 ++Params;
2848 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
2849 };
2850
2851 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
2852 bool IsSizedDelete = false;
Richard Smithb47c36f2013-11-05 09:12:18 +00002853 if (Ctx.getLangOpts().SizedDeallocation &&
Richard Smithb2f0f052016-10-10 18:54:32 +00002854 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2855 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
2856 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
2857 IsSizedDelete = true;
2858 Consume();
2859 }
2860
2861 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
2862 // new/delete.
Akira Hatanakacae83f72017-06-29 18:48:40 +00002863 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
2864 if (IsAligned)
2865 *IsAligned = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00002866 Consume();
Akira Hatanakacae83f72017-06-29 18:48:40 +00002867 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002868
2869 // Finally, if this is not a sized delete, the final parameter can
2870 // be a 'const std::nothrow_t&'.
2871 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
2872 Ty = Ty->getPointeeType();
2873 if (Ty.getCVRQualifiers() != Qualifiers::Const)
2874 return false;
2875 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2876 if (RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace())
2877 Consume();
2878 }
2879
2880 return Params == FPT->getNumParams();
Richard Smith8d0dc312013-07-21 23:12:18 +00002881}
2882
Richard Smith5b349582017-10-13 01:55:36 +00002883bool FunctionDecl::isDestroyingOperatorDelete() const {
2884 // C++ P0722:
2885 // Within a class C, a single object deallocation function with signature
2886 // (T, std::destroying_delete_t, <more params>)
2887 // is a destroying operator delete.
2888 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
2889 getNumParams() < 2)
2890 return false;
2891
2892 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
2893 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
2894 RD->getIdentifier()->isStr("destroying_delete_t");
2895}
2896
Rafael Espindolaf4187652013-02-14 01:18:37 +00002897LanguageLinkage FunctionDecl::getLanguageLinkage() const {
Alp Toker84212df2014-05-31 06:11:02 +00002898 return getDeclLanguageLinkage(*this);
Rafael Espindola576127d2012-12-28 14:21:58 +00002899}
2900
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002901bool FunctionDecl::isExternC() const {
Alp Toker84212df2014-05-31 06:11:02 +00002902 return isDeclExternC(*this);
Rafael Espindola0e0d0092013-03-14 03:07:35 +00002903}
2904
Rafael Espindola593537a2013-05-05 20:15:21 +00002905bool FunctionDecl::isInExternCContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002906 return getLexicalDeclContext()->isExternCContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002907}
2908
2909bool FunctionDecl::isInExternCXXContext() const {
Serge Pavlov3cb80222013-11-14 02:13:03 +00002910 return getLexicalDeclContext()->isExternCXXContext();
Rafael Espindola593537a2013-05-05 20:15:21 +00002911}
2912
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002913bool FunctionDecl::isGlobal() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002914 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002915 return Method->isStatic();
2916
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002917 if (getCanonicalDecl()->getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002918 return false;
2919
Mike Stump11289f42009-09-09 15:08:12 +00002920 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002921 DC->isNamespace();
2922 DC = DC->getParent()) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00002923 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
Douglas Gregorf1b876d2009-03-31 16:35:03 +00002924 if (!Namespace->getDeclName())
2925 return false;
2926 break;
2927 }
2928 }
2929
2930 return true;
2931}
2932
Richard Smith10876ef2013-01-17 01:30:42 +00002933bool FunctionDecl::isNoReturn() const {
Adrian Prantl721c7cb2016-08-17 16:42:15 +00002934 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2935 hasAttr<C11NoReturnAttr>())
2936 return true;
2937
2938 if (auto *FnTy = getType()->getAs<FunctionType>())
2939 return FnTy->getNoReturnAttr();
2940
2941 return false;
Richard Smith10876ef2013-01-17 01:30:42 +00002942}
2943
Erich Keane5c0d1922018-11-28 18:34:14 +00002944
2945MultiVersionKind FunctionDecl::getMultiVersionKind() const {
2946 if (hasAttr<TargetAttr>())
2947 return MultiVersionKind::Target;
2948 if (hasAttr<CPUDispatchAttr>())
2949 return MultiVersionKind::CPUDispatch;
2950 if (hasAttr<CPUSpecificAttr>())
2951 return MultiVersionKind::CPUSpecific;
2952 return MultiVersionKind::None;
2953}
2954
Erich Keane3efe0022018-07-20 14:13:28 +00002955bool FunctionDecl::isCPUDispatchMultiVersion() const {
2956 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
2957}
2958
2959bool FunctionDecl::isCPUSpecificMultiVersion() const {
2960 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
2961}
2962
Erich Keane19a8adc2018-10-25 18:57:19 +00002963bool FunctionDecl::isTargetMultiVersion() const {
2964 return isMultiVersion() && hasAttr<TargetAttr>();
2965}
2966
Sebastian Redl833ef452010-01-26 22:01:41 +00002967void
2968FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002969 redeclarable_base::setPreviousDecl(PrevDecl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002970
2971 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2972 FunctionTemplateDecl *PrevFunTmpl
Craig Topper36250ad2014-05-12 05:36:57 +00002973 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
Sebastian Redl833ef452010-01-26 22:01:41 +00002974 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
Rafael Espindola8db352d2013-10-17 15:37:26 +00002975 FunTmpl->setPreviousDecl(PrevFunTmpl);
Sebastian Redl833ef452010-01-26 22:01:41 +00002976 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002977
Erich Keane9c665062018-08-01 21:02:40 +00002978 if (PrevDecl && PrevDecl->isInlined())
2979 setImplicitlyInline(true);
Sebastian Redl833ef452010-01-26 22:01:41 +00002980}
2981
Rafael Espindola8db352d2013-10-17 15:37:26 +00002982FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
Sebastian Redl833ef452010-01-26 22:01:41 +00002983
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002984/// Returns a value indicating whether this function
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002985/// corresponds to a builtin function.
2986///
2987/// The function corresponds to a built-in function if it is
2988/// declared at translation scope or within an extern "C" block and
2989/// its name matches with the name of a builtin. The returned value
2990/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00002991/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002992/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002993unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00002994 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00002995 return 0;
2996
2997 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00002998 if (!BuiltinID)
2999 return 0;
3000
3001 ASTContext &Context = getASTContext();
Warren Hunt445d83e2013-11-01 23:46:51 +00003002 if (Context.getLangOpts().CPlusPlus) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003003 const auto *LinkageDecl =
3004 dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
Warren Hunt445d83e2013-11-01 23:46:51 +00003005 // In C++, the first declaration of a builtin is always inside an implicit
3006 // extern "C".
3007 // FIXME: A recognised library function may not be directly in an extern "C"
3008 // declaration, for instance "extern "C" { namespace std { decl } }".
David Majnemerba3e5ec2015-03-13 18:26:17 +00003009 if (!LinkageDecl) {
3010 if (BuiltinID == Builtin::BI__GetExceptionInfo &&
David Majnemer145abde2016-01-26 01:12:17 +00003011 Context.getTargetInfo().getCXXABI().isMicrosoft())
David Majnemerba3e5ec2015-03-13 18:26:17 +00003012 return Builtin::BI__GetExceptionInfo;
3013 return 0;
3014 }
3015 if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
Warren Hunt445d83e2013-11-01 23:46:51 +00003016 return 0;
3017 }
3018
3019 // If the function is marked "overloadable", it has a different mangled name
3020 // and is not the C library function.
Aaron Ballman9ead1242013-12-19 02:39:40 +00003021 if (hasAttr<OverloadableAttr>())
Warren Hunt445d83e2013-11-01 23:46:51 +00003022 return 0;
3023
Douglas Gregore711f702009-02-14 18:57:46 +00003024 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3025 return BuiltinID;
3026
3027 // This function has the name of a known C library
3028 // function. Determine whether it actually refers to the C library
3029 // function or whether it just has the same name.
3030
Douglas Gregora908e7f2009-02-17 03:23:10 +00003031 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00003032 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00003033 return 0;
3034
Anastasia Stulova1202de32016-02-12 12:07:04 +00003035 // OpenCL v1.2 s6.9.f - The library functions defined in
3036 // the C99 standard headers are not available.
3037 if (Context.getLangOpts().OpenCL &&
3038 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3039 return 0;
3040
Artem Belevich5ecdb942018-01-23 19:08:18 +00003041 // CUDA does not have device-side standard library. printf and malloc are the
3042 // only special cases that are supported by device-side runtime.
3043 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3044 !hasAttr<CUDAHostAttr>() &&
3045 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3046 return 0;
3047
Warren Hunt445d83e2013-11-01 23:46:51 +00003048 return BuiltinID;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00003049}
3050
Chris Lattner47c0d002009-04-25 06:03:53 +00003051/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00003052/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00003053/// after it has been created.
3054unsigned FunctionDecl::getNumParams() const {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003055 const auto *FPT = getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00003056 return FPT ? FPT->getNumParams() : 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00003057}
3058
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003059void FunctionDecl::setParams(ASTContext &C,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003060 ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00003061 assert(!ParamInfo && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00003062 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00003063
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00003064 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00003065 if (!NewParamInfo.empty()) {
3066 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3067 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00003068 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00003069}
Chris Lattner41943152007-01-25 04:52:46 +00003070
Chris Lattner58258242008-04-10 02:22:51 +00003071/// getMinRequiredArguments - Returns the minimum number of arguments
3072/// needed to call this function. This may be fewer than the number of
3073/// function parameters, if some of the parameters have default
Richard Smith91151782014-04-01 19:18:16 +00003074/// arguments (in C++) or are parameter packs (C++11).
Chris Lattner58258242008-04-10 02:22:51 +00003075unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003076 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003077 return getNumParams();
Chris Lattner58258242008-04-10 02:22:51 +00003078
Richard Smith91151782014-04-01 19:18:16 +00003079 unsigned NumRequiredArgs = 0;
David Majnemer59f77922016-06-24 04:05:48 +00003080 for (auto *Param : parameters())
Richard Smith91151782014-04-01 19:18:16 +00003081 if (!Param->isParameterPack() && !Param->hasDefaultArg())
3082 ++NumRequiredArgs;
Chris Lattner58258242008-04-10 02:22:51 +00003083 return NumRequiredArgs;
3084}
3085
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003086/// The combination of the extern and inline keywords under MSVC forces
David Majnemer54e3ba52014-04-02 23:17:29 +00003087/// the function to be required.
3088///
3089/// Note: This function assumes that we will only get called when isInlined()
3090/// would return true for this FunctionDecl.
3091bool FunctionDecl::isMSExternInline() const {
3092 assert(isInlined() && "expected to get called on an inlined function!");
3093
3094 const ASTContext &Context = getASTContext();
David Majnemer3f021502015-10-08 04:53:31 +00003095 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3096 !hasAttr<DLLExportAttr>())
David Majnemer54e3ba52014-04-02 23:17:29 +00003097 return false;
3098
David Majnemer73768702015-03-20 00:02:27 +00003099 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3100 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003101 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003102 return true;
3103
3104 return false;
3105}
3106
3107static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3108 if (Redecl->getStorageClass() != SC_Extern)
3109 return false;
3110
3111 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3112 FD = FD->getPreviousDecl())
David Majnemerc0c42f32015-07-10 20:55:38 +00003113 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
David Majnemer54e3ba52014-04-02 23:17:29 +00003114 return false;
3115
3116 return true;
3117}
3118
Eli Friedman1b125c32012-02-07 03:50:18 +00003119static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3120 // Only consider file-scope declarations in this test.
3121 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3122 return false;
3123
3124 // Only consider explicit declarations; the presence of a builtin for a
3125 // libcall shouldn't affect whether a definition is externally visible.
3126 if (Redecl->isImplicit())
3127 return false;
3128
Fangrui Song6907ce22018-07-30 19:24:48 +00003129 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003130 return true; // Not an inline definition
3131
3132 return false;
3133}
3134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003135/// For a function declaration in C or C++, determine whether this
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003136/// declaration causes the definition to be externally visible.
3137///
David Majnemer54e3ba52014-04-02 23:17:29 +00003138/// For instance, this determines if adding the current declaration to the set
Eli Friedman1b125c32012-02-07 03:50:18 +00003139/// of redeclarations of the given functions causes
3140/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003141bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
Justin Lebar0241c962016-10-28 16:46:39 +00003142 assert(!doesThisDeclarationHaveABody() &&
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003143 "Must have a declaration without a body.");
3144
3145 ASTContext &Context = getASTContext();
3146
David Majnemer54e3ba52014-04-02 23:17:29 +00003147 if (Context.getLangOpts().MSVCCompat) {
3148 const FunctionDecl *Definition;
3149 if (hasBody(Definition) && Definition->isInlined() &&
3150 redeclForcesDefMSVC(this))
3151 return true;
3152 }
3153
David Blaikiebbafb8a2012-03-11 07:00:24 +00003154 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003155 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3156 // an externally visible definition.
3157 //
3158 // FIXME: What happens if gnu_inline gets added on after the first
3159 // declaration?
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003160 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003161 return false;
3162
3163 const FunctionDecl *Prev = this;
3164 bool FoundBody = false;
3165 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003166 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003167
3168 if (Prev->Body) {
3169 // If it's not the case that both 'inline' and 'extern' are
3170 // specified on the definition, then it is always externally visible.
3171 if (!Prev->isInlineSpecified() ||
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003172 Prev->getStorageClass() != SC_Extern)
Eli Friedman1b125c32012-02-07 03:50:18 +00003173 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003174 } else if (Prev->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003175 Prev->getStorageClass() != SC_Extern) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003176 return false;
3177 }
3178 }
3179 return FoundBody;
3180 }
3181
David Blaikiebbafb8a2012-03-11 07:00:24 +00003182 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003183 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003184
3185 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003186 // [...] If all of the file scope declarations for a function in a
3187 // translation unit include the inline function specifier without extern,
Eli Friedman1b125c32012-02-07 03:50:18 +00003188 // then the definition in that translation unit is an inline definition.
3189 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003190 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00003191 const FunctionDecl *Prev = this;
3192 bool FoundBody = false;
3193 while ((Prev = Prev->getPreviousDecl())) {
David Blaikie7d170102013-05-15 07:37:26 +00003194 FoundBody |= Prev->Body.isValid();
Eli Friedman1b125c32012-02-07 03:50:18 +00003195 if (RedeclForcesDefC99(Prev))
3196 return false;
3197 }
3198 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00003199}
3200
Alp Tokerd0787eb2014-07-02 01:47:15 +00003201SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3202 const TypeSourceInfo *TSI = getTypeSourceInfo();
3203 if (!TSI)
3204 return SourceRange();
Alp Tokerf5b10792014-07-02 12:55:58 +00003205 FunctionTypeLoc FTL =
3206 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3207 if (!FTL)
Alp Tokerd0787eb2014-07-02 01:47:15 +00003208 return SourceRange();
3209
Alp Tokerf5b10792014-07-02 12:55:58 +00003210 // Skip self-referential return types.
3211 const SourceManager &SM = getASTContext().getSourceManager();
3212 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003213 SourceLocation Boundary = getNameInfo().getBeginLoc();
Alp Tokerf5b10792014-07-02 12:55:58 +00003214 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3215 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3216 return SourceRange();
Alp Tokerd0787eb2014-07-02 01:47:15 +00003217
Alp Tokerf5b10792014-07-02 12:55:58 +00003218 return RTRange;
Alp Tokerd0787eb2014-07-02 01:47:15 +00003219}
3220
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00003221SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3222 const TypeSourceInfo *TSI = getTypeSourceInfo();
3223 if (!TSI)
3224 return SourceRange();
3225 FunctionTypeLoc FTL =
3226 TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
3227 if (!FTL)
3228 return SourceRange();
3229
3230 return FTL.getExceptionSpecRange();
3231}
3232
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003233/// For an inline function definition in C, or for a gnu_inline function
Richard Smithf3814ad2013-01-25 00:08:28 +00003234/// in C++, determine whether the definition will be externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00003235///
3236/// Inline function definitions are always available for inlining optimizations.
3237/// However, depending on the language dialect, declaration specifiers, and
3238/// attributes, the definition of an inline function may or may not be
3239/// "externally" visible to other translation units in the program.
3240///
3241/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00003242/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00003243/// inline definition becomes externally visible (C99 6.7.4p6).
3244///
3245/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
Fangrui Song6907ce22018-07-30 19:24:48 +00003246/// definition, we use the GNU semantics for inline, which are nearly the
3247/// opposite of C99 semantics. In particular, "inline" by itself will create
3248/// an externally visible symbol, but "extern inline" will not create an
Douglas Gregor299d76e2009-09-13 07:46:26 +00003249/// externally visible symbol.
3250bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Manuel Klimekda7456a2016-11-01 10:30:50 +00003251 assert((doesThisDeclarationHaveABody() || willHaveBody()) &&
3252 "Must be a function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003253 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00003254 ASTContext &Context = getASTContext();
Fangrui Song6907ce22018-07-30 19:24:48 +00003255
David Blaikiebbafb8a2012-03-11 07:00:24 +00003256 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00003257 // Note: If you change the logic here, please change
3258 // doesDeclarationForceExternallyVisibleDefinition as well.
3259 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00003260 // If it's not the case that both 'inline' and 'extern' are
3261 // specified on the definition, then this inline definition is
3262 // externally visible.
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003263 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
Douglas Gregorff76cb92010-12-09 16:59:22 +00003264 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003265
Douglas Gregorff76cb92010-12-09 16:59:22 +00003266 // If any declaration is 'inline' but not 'extern', then this definition
3267 // is externally visible.
Aaron Ballman86c93902014-03-06 23:45:36 +00003268 for (auto Redecl : redecls()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003269 if (Redecl->isInlineSpecified() &&
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003270 Redecl->getStorageClass() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00003271 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003272 }
3273
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003274 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003275 }
Eli Friedman1b125c32012-02-07 03:50:18 +00003276
Richard Smithf3814ad2013-01-25 00:08:28 +00003277 // The rest of this function is C-only.
3278 assert(!Context.getLangOpts().CPlusPlus &&
3279 "should not use C inline rules in C++");
3280
Douglas Gregor299d76e2009-09-13 07:46:26 +00003281 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003282 // [...] If all of the file scope declarations for a function in a
3283 // translation unit include the inline function specifier without extern,
Douglas Gregor299d76e2009-09-13 07:46:26 +00003284 // then the definition in that translation unit is an inline definition.
Aaron Ballman86c93902014-03-06 23:45:36 +00003285 for (auto Redecl : redecls()) {
3286 if (RedeclForcesDefC99(Redecl))
Eli Friedman1b125c32012-02-07 03:50:18 +00003287 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00003288 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003289
Douglas Gregor299d76e2009-09-13 07:46:26 +00003290 // C99 6.7.4p6:
Fangrui Song6907ce22018-07-30 19:24:48 +00003291 // An inline definition does not provide an external definition for the
3292 // function, and does not forbid an external definition in another
Douglas Gregor299d76e2009-09-13 07:46:26 +00003293 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00003294 return false;
3295}
3296
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003297/// getOverloadedOperator - Which C++ overloaded operator this
3298/// function represents, if any.
3299OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00003300 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3301 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00003302 else
3303 return OO_None;
3304}
3305
Alexis Huntc88db062010-01-13 09:01:02 +00003306/// getLiteralIdentifier - The literal suffix identifier this function
3307/// represents, if any.
3308const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3309 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3310 return getDeclName().getCXXLiteralIdentifier();
3311 else
Craig Topper36250ad2014-05-12 05:36:57 +00003312 return nullptr;
Alexis Huntc88db062010-01-13 09:01:02 +00003313}
3314
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003315FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3316 if (TemplateOrSpecialization.isNull())
3317 return TK_NonTemplate;
3318 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3319 return TK_FunctionTemplate;
3320 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3321 return TK_MemberSpecialization;
3322 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3323 return TK_FunctionTemplateSpecialization;
3324 if (TemplateOrSpecialization.is
3325 <DependentFunctionTemplateSpecializationInfo*>())
3326 return TK_DependentFunctionTemplateSpecialization;
3327
David Blaikie83d382b2011-09-23 05:06:16 +00003328 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00003329}
3330
Douglas Gregord801b062009-10-07 23:56:10 +00003331FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00003332 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00003333 return cast<FunctionDecl>(Info->getInstantiatedFrom());
Craig Topper36250ad2014-05-12 05:36:57 +00003334
3335 return nullptr;
Douglas Gregord801b062009-10-07 23:56:10 +00003336}
3337
Chandler Carruth21c90602015-12-30 03:24:14 +00003338MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3339 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3340}
3341
Fangrui Song6907ce22018-07-30 19:24:48 +00003342void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003343FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3344 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00003345 TemplateSpecializationKind TSK) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003346 assert(TemplateOrSpecialization.isNull() &&
Douglas Gregord801b062009-10-07 23:56:10 +00003347 "Member function is already a specialization");
Fangrui Song6907ce22018-07-30 19:24:48 +00003348 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003349 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00003350 TemplateOrSpecialization = Info;
3351}
3352
Chandler Carruth21c90602015-12-30 03:24:14 +00003353FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3354 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3355}
3356
3357void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3358 TemplateOrSpecialization = Template;
3359}
3360
Douglas Gregorafca3b42009-10-27 20:53:28 +00003361bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00003362 // If the function is invalid, it can't be implicitly instantiated.
3363 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00003364 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003365
Douglas Gregorafca3b42009-10-27 20:53:28 +00003366 switch (getTemplateSpecializationKind()) {
3367 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00003368 case TSK_ExplicitInstantiationDefinition:
3369 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003370
Douglas Gregorafca3b42009-10-27 20:53:28 +00003371 case TSK_ImplicitInstantiation:
3372 return true;
3373
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003374 // It is possible to instantiate TSK_ExplicitSpecialization kind
3375 // if the FunctionDecl has a class scope specialization pattern.
3376 case TSK_ExplicitSpecialization:
Craig Topper36250ad2014-05-12 05:36:57 +00003377 return getClassScopeSpecializationPattern() != nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003378
Douglas Gregorafca3b42009-10-27 20:53:28 +00003379 case TSK_ExplicitInstantiationDeclaration:
3380 // Handled below.
3381 break;
3382 }
3383
3384 // Find the actual template from which we will instantiate.
3385 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003386 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003387 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003388 HasPattern = PatternDecl->hasBody(PatternDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00003389
Douglas Gregorafca3b42009-10-27 20:53:28 +00003390 // C++0x [temp.explicit]p9:
3391 // Except for inline functions, other explicit instantiation declarations
3392 // have the effect of suppressing the implicit instantiation of the entity
Fangrui Song6907ce22018-07-30 19:24:48 +00003393 // to which they refer.
3394 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00003395 return true;
3396
Douglas Gregor583dcaf2009-10-27 21:11:48 +00003397 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00003398}
3399
3400bool FunctionDecl::isTemplateInstantiation() const {
3401 switch (getTemplateSpecializationKind()) {
3402 case TSK_Undeclared:
3403 case TSK_ExplicitSpecialization:
Fangrui Song6907ce22018-07-30 19:24:48 +00003404 return false;
Ted Kremenek85825ae2011-12-01 00:59:17 +00003405 case TSK_ImplicitInstantiation:
3406 case TSK_ExplicitInstantiationDeclaration:
3407 case TSK_ExplicitInstantiationDefinition:
3408 return true;
3409 }
3410 llvm_unreachable("All TSK values handled.");
3411}
Fangrui Song6907ce22018-07-30 19:24:48 +00003412
Douglas Gregorafca3b42009-10-27 20:53:28 +00003413FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003414 // Handle class scope explicit specialization special case.
Richard Smith2195ec92017-04-21 01:15:13 +00003415 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
3416 if (auto *Spec = getClassScopeSpecializationPattern())
3417 return getDefinitionOrSelf(Spec);
3418 return nullptr;
3419 }
3420
Fangrui Song6907ce22018-07-30 19:24:48 +00003421 // If this is a generic lambda call operator specialization, its
Faisal Valib90b2112014-04-03 16:32:21 +00003422 // instantiation pattern is always its primary template's pattern
Fangrui Song6907ce22018-07-30 19:24:48 +00003423 // even if its primary template was instantiated from another
Faisal Valib90b2112014-04-03 16:32:21 +00003424 // member template (which happens with nested generic lambdas).
Fangrui Song6907ce22018-07-30 19:24:48 +00003425 // Since a lambda's call operator's body is transformed eagerly,
3426 // we don't have to go hunting for a prototype definition template
3427 // (i.e. instantiated-from-member-template) to use as an instantiation
Faisal Valib90b2112014-04-03 16:32:21 +00003428 // pattern.
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003429
Faisal Valib90b2112014-04-03 16:32:21 +00003430 if (isGenericLambdaCallOperatorSpecialization(
3431 dyn_cast<CXXMethodDecl>(this))) {
Richard Smith2195ec92017-04-21 01:15:13 +00003432 assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3433 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
Faisal Valib90b2112014-04-03 16:32:21 +00003434 }
Richard Smith2195ec92017-04-21 01:15:13 +00003435
Douglas Gregorafca3b42009-10-27 20:53:28 +00003436 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3437 while (Primary->getInstantiatedFromMemberTemplate()) {
3438 // If we have hit a point where the user provided a specialization of
3439 // this template, we're done looking.
3440 if (Primary->isMemberSpecialization())
3441 break;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003442 Primary = Primary->getInstantiatedFromMemberTemplate();
3443 }
Richard Smith2195ec92017-04-21 01:15:13 +00003444
3445 return getDefinitionOrSelf(Primary->getTemplatedDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00003446 }
Richard Smith2195ec92017-04-21 01:15:13 +00003447
3448 if (auto *MFD = getInstantiatedFromMemberFunction())
3449 return getDefinitionOrSelf(MFD);
3450
3451 return nullptr;
Douglas Gregorafca3b42009-10-27 20:53:28 +00003452}
3453
Douglas Gregor70d83e22009-06-29 17:30:29 +00003454FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00003455 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003456 = TemplateOrSpecialization
3457 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00003458 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00003459 }
Craig Topper36250ad2014-05-12 05:36:57 +00003460 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003461}
3462
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003463FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3464 return getASTContext().getClassScopeSpecializationPattern(this);
3465}
3466
Chandler Carruth21c90602015-12-30 03:24:14 +00003467FunctionTemplateSpecializationInfo *
3468FunctionDecl::getTemplateSpecializationInfo() const {
3469 return TemplateOrSpecialization
3470 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3471}
3472
Douglas Gregor70d83e22009-06-29 17:30:29 +00003473const TemplateArgumentList *
3474FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00003475 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00003476 = TemplateOrSpecialization
3477 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003478 return Info->TemplateArguments;
3479 }
Craig Topper36250ad2014-05-12 05:36:57 +00003480 return nullptr;
Douglas Gregor70d83e22009-06-29 17:30:29 +00003481}
3482
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00003483const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003484FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3485 if (FunctionTemplateSpecializationInfo *Info
3486 = TemplateOrSpecialization
3487 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3488 return Info->TemplateArgumentsAsWritten;
3489 }
Craig Topper36250ad2014-05-12 05:36:57 +00003490 return nullptr;
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003491}
3492
Mike Stump11289f42009-09-09 15:08:12 +00003493void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00003494FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3495 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003496 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003497 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00003498 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00003499 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3500 SourceLocation PointOfInstantiation) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003501 assert(TSK != TSK_Undeclared &&
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00003502 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00003503 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00003504 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003505 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00003506 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3507 TemplateArgs,
3508 TemplateArgsAsWritten,
3509 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003510 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00003511 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00003512}
3513
John McCallb9c78482010-04-08 09:05:18 +00003514void
3515FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3516 const UnresolvedSetImpl &Templates,
3517 const TemplateArgumentListInfo &TemplateArgs) {
3518 assert(TemplateOrSpecialization.isNull());
John McCallb9c78482010-04-08 09:05:18 +00003519 DependentFunctionTemplateSpecializationInfo *Info =
James Y Knight7a22b242015-08-06 20:26:32 +00003520 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3521 TemplateArgs);
John McCallb9c78482010-04-08 09:05:18 +00003522 TemplateOrSpecialization = Info;
3523}
3524
James Y Knight7a22b242015-08-06 20:26:32 +00003525DependentFunctionTemplateSpecializationInfo *
Chandler Carruth21c90602015-12-30 03:24:14 +00003526FunctionDecl::getDependentSpecializationInfo() const {
3527 return TemplateOrSpecialization
3528 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3529}
3530
3531DependentFunctionTemplateSpecializationInfo *
James Y Knight7a22b242015-08-06 20:26:32 +00003532DependentFunctionTemplateSpecializationInfo::Create(
3533 ASTContext &Context, const UnresolvedSetImpl &Ts,
3534 const TemplateArgumentListInfo &TArgs) {
3535 void *Buffer = Context.Allocate(
3536 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3537 TArgs.size(), Ts.size()));
3538 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3539}
3540
John McCallb9c78482010-04-08 09:05:18 +00003541DependentFunctionTemplateSpecializationInfo::
3542DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3543 const TemplateArgumentListInfo &TArgs)
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003544 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
James Y Knight53c76162015-07-17 18:21:37 +00003545 NumTemplates = Ts.size();
3546 NumArgs = TArgs.size();
Benjamin Kramer3ebba522015-04-02 12:43:31 +00003547
James Y Knight7a22b242015-08-06 20:26:32 +00003548 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
John McCallb9c78482010-04-08 09:05:18 +00003549 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3550 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3551
James Y Knight7a22b242015-08-06 20:26:32 +00003552 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
John McCallb9c78482010-04-08 09:05:18 +00003553 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3554 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3555}
3556
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003557TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00003558 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003559 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00003560 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00003561 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00003562 if (FTSInfo)
3563 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00003564
Douglas Gregord801b062009-10-07 23:56:10 +00003565 MemberSpecializationInfo *MSInfo
3566 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3567 if (MSInfo)
3568 return MSInfo->getTemplateSpecializationKind();
Fangrui Song6907ce22018-07-30 19:24:48 +00003569
Douglas Gregord801b062009-10-07 23:56:10 +00003570 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003571}
3572
Mike Stump11289f42009-09-09 15:08:12 +00003573void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003574FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3575 SourceLocation PointOfInstantiation) {
3576 if (FunctionTemplateSpecializationInfo *FTSInfo
3577 = TemplateOrSpecialization.dyn_cast<
3578 FunctionTemplateSpecializationInfo*>()) {
3579 FTSInfo->setTemplateSpecializationKind(TSK);
3580 if (TSK != TSK_ExplicitSpecialization &&
3581 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003582 FTSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003583 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003584 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3585 L->InstantiationRequested(this);
3586 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003587 } else if (MemberSpecializationInfo *MSInfo
3588 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3589 MSInfo->setTemplateSpecializationKind(TSK);
3590 if (TSK != TSK_ExplicitSpecialization &&
3591 PointOfInstantiation.isValid() &&
Richard Smith891fc7f2017-12-05 01:31:47 +00003592 MSInfo->getPointOfInstantiation().isInvalid()) {
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003593 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00003594 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3595 L->InstantiationRequested(this);
3596 }
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003597 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003598 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003599}
3600
3601SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00003602 if (FunctionTemplateSpecializationInfo *FTSInfo
3603 = TemplateOrSpecialization.dyn_cast<
3604 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003605 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00003606 else if (MemberSpecializationInfo *MSInfo
3607 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003608 return MSInfo->getPointOfInstantiation();
Fangrui Song6907ce22018-07-30 19:24:48 +00003609
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00003610 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00003611}
3612
Douglas Gregor6411b922009-09-11 20:15:17 +00003613bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00003614 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00003615 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003616
3617 // If this function was instantiated from a member function of a
Douglas Gregor6411b922009-09-11 20:15:17 +00003618 // class template, check whether that member function was defined out-of-line.
3619 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3620 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003621 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003622 return Definition->isOutOfLine();
3623 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003624
Douglas Gregor6411b922009-09-11 20:15:17 +00003625 // If this function was instantiated from a function template,
3626 // check whether that function template was defined out-of-line.
3627 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3628 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003629 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00003630 return Definition->isOutOfLine();
3631 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003632
Douglas Gregor6411b922009-09-11 20:15:17 +00003633 return false;
3634}
3635
Abramo Bagnaraea947882011-03-08 16:41:52 +00003636SourceRange FunctionDecl::getSourceRange() const {
3637 return SourceRange(getOuterLocStart(), EndRangeLoc);
3638}
3639
Anna Zaks28db7ce2012-01-18 02:45:01 +00003640unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00003641 IdentifierInfo *FnInfo = getIdentifier();
3642
3643 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00003644 return 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00003645
Anna Zaks201d4892012-01-13 21:52:01 +00003646 // Builtin handling.
3647 switch (getBuiltinID()) {
3648 case Builtin::BI__builtin_memset:
3649 case Builtin::BI__builtin___memset_chk:
3650 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00003651 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003652
3653 case Builtin::BI__builtin_memcpy:
3654 case Builtin::BI__builtin___memcpy_chk:
3655 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00003656 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003657
3658 case Builtin::BI__builtin_memmove:
3659 case Builtin::BI__builtin___memmove_chk:
3660 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00003661 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003662
3663 case Builtin::BIstrlcpy:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003664 case Builtin::BI__builtin___strlcpy_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003665 return Builtin::BIstrlcpy;
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003666
Anna Zaks201d4892012-01-13 21:52:01 +00003667 case Builtin::BIstrlcat:
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00003668 case Builtin::BI__builtin___strlcat_chk:
Anna Zaks22122702012-01-17 00:37:07 +00003669 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00003670
3671 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00003672 case Builtin::BImemcmp:
3673 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003674
3675 case Builtin::BI__builtin_strncpy:
3676 case Builtin::BI__builtin___strncpy_chk:
3677 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00003678 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003679
3680 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00003681 case Builtin::BIstrncmp:
3682 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003683
3684 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00003685 case Builtin::BIstrncasecmp:
3686 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003687
3688 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00003689 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00003690 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00003691 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003692
3693 case Builtin::BI__builtin_strndup:
3694 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00003695 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00003696
Anna Zaks314cd092012-02-01 19:08:57 +00003697 case Builtin::BI__builtin_strlen:
3698 case Builtin::BIstrlen:
3699 return Builtin::BIstrlen;
3700
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003701 case Builtin::BI__builtin_bzero:
3702 case Builtin::BIbzero:
3703 return Builtin::BIbzero;
3704
Anna Zaks201d4892012-01-13 21:52:01 +00003705 default:
Rafael Espindola5bda63f2013-02-14 01:47:04 +00003706 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00003707 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00003708 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00003709 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003710 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003711 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00003712 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00003713 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003714 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003715 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00003716 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00003717 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003718 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003719 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00003720 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00003721 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00003722 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00003723 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00003724 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00003725 else if (FnInfo->isStr("strlen"))
3726 return Builtin::BIstrlen;
Bruno Cardoso Lopes7ea9fd22016-08-10 18:34:47 +00003727 else if (FnInfo->isStr("bzero"))
3728 return Builtin::BIbzero;
Anna Zaks201d4892012-01-13 21:52:01 +00003729 }
3730 break;
3731 }
Anna Zaks22122702012-01-17 00:37:07 +00003732 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00003733}
3734
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003735unsigned FunctionDecl::getODRHash() const {
Erich Keane9c665062018-08-01 21:02:40 +00003736 assert(hasODRHash());
Richard Trieu27c1b1a2018-07-10 01:40:50 +00003737 return ODRHash;
3738}
3739
Richard Trieue6caa262017-12-23 00:41:01 +00003740unsigned FunctionDecl::getODRHash() {
Erich Keane9c665062018-08-01 21:02:40 +00003741 if (hasODRHash())
Richard Trieue6caa262017-12-23 00:41:01 +00003742 return ODRHash;
3743
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003744 if (auto *FT = getInstantiatedFromMemberFunction()) {
Erich Keane9c665062018-08-01 21:02:40 +00003745 setHasODRHash(true);
Richard Trieu0ac2eb72018-02-22 05:50:29 +00003746 ODRHash = FT->getODRHash();
3747 return ODRHash;
3748 }
3749
Richard Trieue6caa262017-12-23 00:41:01 +00003750 class ODRHash Hash;
3751 Hash.AddFunctionDecl(this);
Erich Keane9c665062018-08-01 21:02:40 +00003752 setHasODRHash(true);
Richard Trieue6caa262017-12-23 00:41:01 +00003753 ODRHash = Hash.CalculateHash();
3754 return ODRHash;
3755}
3756
Chris Lattner59a25942008-03-31 00:36:02 +00003757//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003758// FieldDecl Implementation
3759//===----------------------------------------------------------------------===//
3760
Jay Foad39c79802011-01-12 09:06:06 +00003761FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00003762 SourceLocation StartLoc, SourceLocation IdLoc,
3763 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00003764 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
Richard Smith2b013182012-06-10 03:12:00 +00003765 InClassInitStyle InitStyle) {
Richard Smithf7981722013-11-22 09:01:48 +00003766 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3767 BW, Mutable, InitStyle);
Sebastian Redl833ef452010-01-26 22:01:41 +00003768}
3769
Douglas Gregor72172e92012-01-05 21:55:30 +00003770FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00003771 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3772 SourceLocation(), nullptr, QualType(), nullptr,
3773 nullptr, false, ICIS_NoInit);
Douglas Gregor72172e92012-01-05 21:55:30 +00003774}
3775
Sebastian Redl833ef452010-01-26 22:01:41 +00003776bool FieldDecl::isAnonymousStructOrUnion() const {
3777 if (!isImplicit() || getDeclName())
3778 return false;
3779
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003780 if (const auto *Record = getType()->getAs<RecordType>())
Sebastian Redl833ef452010-01-26 22:01:41 +00003781 return Record->getDecl()->isAnonymousStructOrUnion();
3782
3783 return false;
3784}
3785
Richard Smithcaf33902011-10-10 18:28:20 +00003786unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3787 assert(isBitField() && "not a bitfield");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003788 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
Richard Smithcaf33902011-10-10 18:28:20 +00003789}
3790
Richard Smith866dee42018-04-02 18:29:43 +00003791bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
3792 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
3793 getBitWidthValue(Ctx) == 0;
3794}
3795
John McCall4e819612011-01-20 07:57:12 +00003796unsigned FieldDecl::getFieldIndex() const {
Richard Smith0b87e072013-10-07 08:02:11 +00003797 const FieldDecl *Canonical = getCanonicalDecl();
3798 if (Canonical != this)
3799 return Canonical->getFieldIndex();
3800
John McCall4e819612011-01-20 07:57:12 +00003801 if (CachedFieldIndex) return CachedFieldIndex - 1;
3802
Richard Smithd62306a2011-11-10 06:34:14 +00003803 unsigned Index = 0;
Richard Smith85567dd2017-11-15 01:33:46 +00003804 const RecordDecl *RD = getParent()->getDefinition();
3805 assert(RD && "requested index for field of struct with no definition");
Richard Smithd62306a2011-11-10 06:34:14 +00003806
Hans Wennborga302cd92014-08-21 16:06:57 +00003807 for (auto *Field : RD->fields()) {
3808 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3809 ++Index;
3810 }
John McCall4e819612011-01-20 07:57:12 +00003811
Richard Smithd62306a2011-11-10 06:34:14 +00003812 assert(CachedFieldIndex && "failed to find field in parent");
3813 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00003814}
3815
Abramo Bagnara20c9e242011-03-08 11:07:11 +00003816SourceRange FieldDecl::getSourceRange() const {
Richard Smith6b8e3c02017-08-28 00:28:14 +00003817 const Expr *FinalExpr = getInClassInitializer();
3818 if (!FinalExpr)
3819 FinalExpr = getBitWidth();
3820 if (FinalExpr)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003821 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
Richard Smith6b8e3c02017-08-28 00:28:14 +00003822 return DeclaratorDecl::getSourceRange();
Alexey Bataev39c81e22014-08-28 04:28:19 +00003823}
3824
3825void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
David Blaikie11ab0782014-10-31 17:18:09 +00003826 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
Alexey Bataev330de032014-10-29 12:21:55 +00003827 "capturing type in non-lambda or captured record.");
Richard Smith6b8e3c02017-08-28 00:28:14 +00003828 assert(InitStorage.getInt() == ISK_NoInit &&
John McCallc90c1492014-10-10 18:44:34 +00003829 InitStorage.getPointer() == nullptr &&
Alexey Bataev39c81e22014-08-28 04:28:19 +00003830 "bit width, initializer or captured type already set");
John McCallc90c1492014-10-10 18:44:34 +00003831 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3832 ISK_CapturedVLAType);
Alexey Bataev39c81e22014-08-28 04:28:19 +00003833}
3834
Sebastian Redl833ef452010-01-26 22:01:41 +00003835//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003836// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00003837//===----------------------------------------------------------------------===//
3838
Erich Keanef92f31c2018-08-01 20:48:16 +00003839TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
3840 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
3841 SourceLocation StartL)
3842 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
3843 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
3844 assert((DK != Enum || TK == TTK_Enum) &&
3845 "EnumDecl not matched with TTK_Enum");
3846 setPreviousDecl(PrevDecl);
3847 setTagKind(TK);
3848 setCompleteDefinition(false);
3849 setBeingDefined(false);
3850 setEmbeddedInDeclarator(false);
3851 setFreeStanding(false);
3852 setCompleteDefinitionRequired(false);
3853}
3854
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003855SourceLocation TagDecl::getOuterLocStart() const {
3856 return getTemplateOrInnerLocStart(this);
3857}
3858
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003859SourceRange TagDecl::getSourceRange() const {
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00003860 SourceLocation RBraceLoc = BraceRange.getEnd();
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003861 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00003862 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00003863}
3864
Rafael Espindola8db352d2013-10-17 15:37:26 +00003865TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00003866
Rafael Espindolabf5c33b2013-03-12 21:06:00 +00003867void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
David Majnemer00350522015-08-31 18:48:39 +00003868 TypedefNameDeclOrQualifier = TDD;
Reid Klecknercae82a22014-04-23 22:03:04 +00003869 if (const Type *T = getTypeForDecl()) {
3870 (void)T;
Richard Smith5b21db82014-04-23 18:20:42 +00003871 assert(T->isLinkageValid());
Reid Klecknercae82a22014-04-23 22:03:04 +00003872 }
Rafael Espindola0e0d0092013-03-14 03:07:35 +00003873 assert(isLinkageValid());
Douglas Gregora72a4e32010-05-19 18:39:18 +00003874}
3875
Douglas Gregordee1be82009-01-17 00:42:38 +00003876void TagDecl::startDefinition() {
Erich Keanef92f31c2018-08-01 20:48:16 +00003877 setBeingDefined(true);
John McCall67da35c2010-02-04 22:26:26 +00003878
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003879 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
Richard Smith053f6c62014-05-16 23:01:30 +00003880 struct CXXRecordDecl::DefinitionData *Data =
John McCall67da35c2010-02-04 22:26:26 +00003881 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
Aaron Ballman86c93902014-03-06 23:45:36 +00003882 for (auto I : redecls())
Richard Smith64c06302014-05-22 23:19:02 +00003883 cast<CXXRecordDecl>(I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00003884 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003885}
3886
3887void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00003888 assert((!isa<CXXRecordDecl>(this) ||
3889 cast<CXXRecordDecl>(this)->hasDefinition()) &&
3890 "definition completed but not started");
3891
Erich Keanef92f31c2018-08-01 20:48:16 +00003892 setCompleteDefinition(true);
3893 setBeingDefined(false);
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00003894
3895 if (ASTMutationListener *L = getASTMutationListener())
3896 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00003897}
3898
John McCallf937c022011-10-07 06:10:15 +00003899TagDecl *TagDecl::getDefinition() const {
3900 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00003901 return const_cast<TagDecl *>(this);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003902
3903 // If it's possible for us to have an out-of-date definition, check now.
Erich Keanef92f31c2018-08-01 20:48:16 +00003904 if (mayHaveOutOfDateDef()) {
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003905 if (IdentifierInfo *II = getIdentifier()) {
3906 if (II->isOutOfDate()) {
3907 updateOutOfDate(*II);
3908 }
3909 }
3910 }
3911
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003912 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
Andrew Trickba266ee2010-10-19 21:54:32 +00003913 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003914
Aaron Ballman86c93902014-03-06 23:45:36 +00003915 for (auto R : redecls())
John McCallf937c022011-10-07 06:10:15 +00003916 if (R->isCompleteDefinition())
Aaron Ballman86c93902014-03-06 23:45:36 +00003917 return R;
Mike Stump11289f42009-09-09 15:08:12 +00003918
Craig Topper36250ad2014-05-12 05:36:57 +00003919 return nullptr;
Ted Kremenek21475702008-09-05 17:16:31 +00003920}
3921
Douglas Gregor14454802011-02-25 02:25:35 +00003922void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3923 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00003924 // Make sure the extended qualifier info is allocated.
3925 if (!hasExtInfo())
David Majnemer00350522015-08-31 18:48:39 +00003926 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00003927 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00003928 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00003929 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00003930 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00003931 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00003932 if (getExtInfo()->NumTemplParamLists == 0) {
3933 getASTContext().Deallocate(getExtInfo());
David Majnemer00350522015-08-31 18:48:39 +00003934 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003935 }
3936 else
3937 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00003938 }
3939 }
3940}
3941
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003942void TagDecl::setTemplateParameterListsInfo(
3943 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3944 assert(!TPLists.empty());
Abramo Bagnara60804e12011-03-18 15:16:37 +00003945 // Make sure the extended decl info is allocated.
3946 if (!hasExtInfo())
3947 // Allocate external info struct.
David Majnemer00350522015-08-31 18:48:39 +00003948 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00003949 // Set the template parameter lists info.
Benjamin Kramer9cc210652015-08-05 09:40:49 +00003950 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
Abramo Bagnara60804e12011-03-18 15:16:37 +00003951}
3952
Ted Kremenek21475702008-09-05 17:16:31 +00003953//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00003954// EnumDecl Implementation
3955//===----------------------------------------------------------------------===//
3956
Erich Keanef92f31c2018-08-01 20:48:16 +00003957EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3958 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
3959 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
3960 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3961 assert(Scoped || !ScopedUsingClassTag);
3962 IntegerType = nullptr;
3963 setNumPositiveBits(0);
3964 setNumNegativeBits(0);
3965 setScoped(Scoped);
3966 setScopedUsingClassTag(ScopedUsingClassTag);
3967 setFixed(Fixed);
3968 setHasODRHash(false);
3969 ODRHash = 0;
3970}
3971
Eugene Zelenkode0215c2017-11-13 23:01:27 +00003972void EnumDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00003973
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003974EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3975 SourceLocation StartLoc, SourceLocation IdLoc,
3976 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00003977 EnumDecl *PrevDecl, bool IsScoped,
3978 bool IsScopedUsingClassTag, bool IsFixed) {
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00003979 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3980 IsScoped, IsScopedUsingClassTag, IsFixed);
Erich Keanef92f31c2018-08-01 20:48:16 +00003981 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Sebastian Redl833ef452010-01-26 22:01:41 +00003982 C.getTypeDeclType(Enum, PrevDecl);
3983 return Enum;
3984}
3985
Douglas Gregor72172e92012-01-05 21:55:30 +00003986EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00003987 EnumDecl *Enum =
3988 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3989 nullptr, nullptr, false, false, false);
Erich Keanef92f31c2018-08-01 20:48:16 +00003990 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00003991 return Enum;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00003992}
3993
Alp Tokerb9fa5122014-01-06 11:31:18 +00003994SourceRange EnumDecl::getIntegerTypeRange() const {
3995 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3996 return TI->getTypeLoc().getSourceRange();
3997 return SourceRange();
3998}
3999
Douglas Gregord5058122010-02-11 01:19:42 +00004000void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00004001 QualType NewPromotionType,
4002 unsigned NumPositiveBits,
4003 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00004004 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00004005 if (!IntegerType)
4006 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00004007 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00004008 setNumPositiveBits(NumPositiveBits);
4009 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00004010 TagDecl::completeDefinition();
4011}
4012
Akira Hatanaka3c268af2017-03-21 02:23:00 +00004013bool EnumDecl::isClosed() const {
4014 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4015 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4016 return true;
4017}
4018
4019bool EnumDecl::isClosedFlag() const {
4020 return isClosed() && hasAttr<FlagEnumAttr>();
4021}
4022
4023bool EnumDecl::isClosedNonFlag() const {
4024 return isClosed() && !hasAttr<FlagEnumAttr>();
4025}
4026
Richard Smith7d137e32012-03-23 03:33:32 +00004027TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4028 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4029 return MSI->getTemplateSpecializationKind();
4030
4031 return TSK_Undeclared;
4032}
4033
4034void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4035 SourceLocation PointOfInstantiation) {
4036 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4037 assert(MSI && "Not an instantiated member enumeration?");
4038 MSI->setTemplateSpecializationKind(TSK);
4039 if (TSK != TSK_ExplicitSpecialization &&
4040 PointOfInstantiation.isValid() &&
4041 MSI->getPointOfInstantiation().isInvalid())
4042 MSI->setPointOfInstantiation(PointOfInstantiation);
4043}
4044
Richard Smith6739a102016-05-05 00:56:12 +00004045EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4046 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4047 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4048 EnumDecl *ED = getInstantiatedFromMemberEnum();
4049 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4050 ED = NewED;
Richard Smith2195ec92017-04-21 01:15:13 +00004051 return getDefinitionOrSelf(ED);
Richard Smith6739a102016-05-05 00:56:12 +00004052 }
4053 }
4054
4055 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4056 "couldn't find pattern for enum instantiation");
4057 return nullptr;
4058}
4059
Richard Smith4b38ded2012-03-14 23:13:10 +00004060EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4061 if (SpecializationInfo)
4062 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4063
Craig Topper36250ad2014-05-12 05:36:57 +00004064 return nullptr;
Richard Smith4b38ded2012-03-14 23:13:10 +00004065}
4066
4067void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4068 TemplateSpecializationKind TSK) {
4069 assert(!SpecializationInfo && "Member enum is already a specialization");
4070 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4071}
4072
Richard Trieuab4d7302018-07-25 22:52:05 +00004073unsigned EnumDecl::getODRHash() {
Erich Keanef92f31c2018-08-01 20:48:16 +00004074 if (hasODRHash())
Richard Trieuab4d7302018-07-25 22:52:05 +00004075 return ODRHash;
4076
4077 class ODRHash Hash;
4078 Hash.AddEnumDecl(this);
Erich Keanef92f31c2018-08-01 20:48:16 +00004079 setHasODRHash(true);
Richard Trieuab4d7302018-07-25 22:52:05 +00004080 ODRHash = Hash.CalculateHash();
4081 return ODRHash;
4082}
4083
Sebastian Redl833ef452010-01-26 22:01:41 +00004084//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00004085// RecordDecl Implementation
4086//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00004087
Richard Smith053f6c62014-05-16 23:01:30 +00004088RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4089 DeclContext *DC, SourceLocation StartLoc,
4090 SourceLocation IdLoc, IdentifierInfo *Id,
4091 RecordDecl *PrevDecl)
Erich Keanef92f31c2018-08-01 20:48:16 +00004092 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4093 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4094 setHasFlexibleArrayMember(false);
4095 setAnonymousStructOrUnion(false);
4096 setHasObjectMember(false);
4097 setHasVolatileMember(false);
4098 setHasLoadedFieldsFromExternalStorage(false);
4099 setNonTrivialToPrimitiveDefaultInitialize(false);
4100 setNonTrivialToPrimitiveCopy(false);
4101 setNonTrivialToPrimitiveDestroy(false);
4102 setParamDestroyedInCallee(false);
4103 setArgPassingRestrictions(APK_CanPassInRegs);
Ted Kremenek52baf502008-09-02 21:12:32 +00004104}
4105
Jay Foad39c79802011-01-12 09:06:06 +00004106RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004107 SourceLocation StartLoc, SourceLocation IdLoc,
4108 IdentifierInfo *Id, RecordDecl* PrevDecl) {
Richard Smith053f6c62014-05-16 23:01:30 +00004109 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4110 StartLoc, IdLoc, Id, PrevDecl);
Erich Keanef92f31c2018-08-01 20:48:16 +00004111 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004112
Ted Kremenek21475702008-09-05 17:16:31 +00004113 C.getTypeDeclType(R, PrevDecl);
4114 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00004115}
4116
Douglas Gregor72172e92012-01-05 21:55:30 +00004117RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004118 RecordDecl *R =
4119 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4120 SourceLocation(), nullptr, nullptr);
Erich Keanef92f31c2018-08-01 20:48:16 +00004121 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
Douglas Gregor7dab26b2013-02-09 01:35:03 +00004122 return R;
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00004123}
4124
Douglas Gregordfcad112009-03-25 15:59:44 +00004125bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00004126 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00004127 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4128}
4129
Alexey Bataev39c81e22014-08-28 04:28:19 +00004130bool RecordDecl::isLambda() const {
4131 if (auto RD = dyn_cast<CXXRecordDecl>(this))
4132 return RD->isLambda();
4133 return false;
4134}
4135
Alexey Bataev330de032014-10-29 12:21:55 +00004136bool RecordDecl::isCapturedRecord() const {
4137 return hasAttr<CapturedRecordAttr>();
4138}
4139
4140void RecordDecl::setCapturedRecord() {
4141 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4142}
4143
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004144RecordDecl::field_iterator RecordDecl::field_begin() const {
Erich Keanef92f31c2018-08-01 20:48:16 +00004145 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004146 LoadFieldsFromExternalStorage();
4147
4148 return field_iterator(decl_iterator(FirstDecl));
4149}
4150
Douglas Gregorb11aad82011-02-19 18:51:44 +00004151/// completeDefinition - Notes that the definition of this type is now
4152/// complete.
4153void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00004154 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00004155 TagDecl::completeDefinition();
4156}
4157
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004158/// isMsStruct - Get whether or not this record uses ms_struct layout.
4159/// This which can be turned on with an attribute, pragma, or the
4160/// -mms-bitfields command-line option.
4161bool RecordDecl::isMsStruct(const ASTContext &C) const {
David Majnemer8ab003a2015-02-02 19:30:52 +00004162 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
Eli Friedman9ee2d0472012-10-12 23:29:20 +00004163}
4164
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004165void RecordDecl::LoadFieldsFromExternalStorage() const {
4166 ExternalASTSource *Source = getASTContext().getExternalSource();
4167 assert(hasExternalLexicalStorage() && Source && "No external storage?");
4168
4169 // Notify that we have a RecordDecl doing some initialization.
4170 ExternalASTSource::Deserializing TheFields(Source);
4171
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004172 SmallVector<Decl*, 64> Decls;
Erich Keanef92f31c2018-08-01 20:48:16 +00004173 setHasLoadedFieldsFromExternalStorage(true);
Richard Smith3cb15722015-08-05 22:41:45 +00004174 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4175 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4176 }, Decls);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004177
4178#ifndef NDEBUG
4179 // Check that all decls we got were FieldDecls.
4180 for (unsigned i=0, e=Decls.size(); i != e; ++i)
Argyrios Kyrtzidisf89a9272012-09-10 22:04:22 +00004181 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004182#endif
4183
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004184 if (Decls.empty())
4185 return;
4186
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004187 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00004188 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00004189}
4190
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004191bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4192 ASTContext &Context = getASTContext();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004193 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4194 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4195 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004196 return false;
Alexey Samsonov33e00e22014-10-16 23:50:26 +00004197 const auto &Blacklist = Context.getSanitizerBlacklist();
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004198 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004199 // We may be able to relax some of these requirements.
4200 int ReasonToReject = -1;
4201 if (!CXXRD || CXXRD->isExternCContext())
4202 ReasonToReject = 0; // is not C++.
4203 else if (CXXRD->hasAttr<PackedAttr>())
4204 ReasonToReject = 1; // is packed.
4205 else if (CXXRD->isUnion())
4206 ReasonToReject = 2; // is a union.
4207 else if (CXXRD->isTriviallyCopyable())
4208 ReasonToReject = 3; // is trivially copyable.
4209 else if (CXXRD->hasTrivialDestructor())
4210 ReasonToReject = 4; // has trivial destructor.
4211 else if (CXXRD->isStandardLayout())
4212 ReasonToReject = 5; // is standard layout.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004213 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4214 "field-padding"))
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004215 ReasonToReject = 6; // is in a blacklisted file.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00004216 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4217 getQualifiedNameAsString(),
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00004218 "field-padding"))
4219 ReasonToReject = 7; // is blacklisted.
4220
4221 if (EmitRemark) {
4222 if (ReasonToReject >= 0)
4223 Context.getDiagnostics().Report(
4224 getLocation(),
4225 diag::remark_sanitize_address_insert_extra_padding_rejected)
4226 << getQualifiedNameAsString() << ReasonToReject;
4227 else
4228 Context.getDiagnostics().Report(
4229 getLocation(),
4230 diag::remark_sanitize_address_insert_extra_padding_accepted)
4231 << getQualifiedNameAsString();
4232 }
4233 return ReasonToReject < 0;
4234}
4235
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004236const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4237 for (const auto *I : fields()) {
4238 if (I->getIdentifier())
4239 return I;
4240
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004241 if (const auto *RT = I->getType()->getAs<RecordType>())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004242 if (const FieldDecl *NamedDataMember =
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004243 RT->getDecl()->findFirstNamedDataMember())
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004244 return NamedDataMember;
4245 }
4246
4247 // We didn't find a named data member.
4248 return nullptr;
4249}
4250
Steve Naroff415d3d52008-10-08 17:01:13 +00004251//===----------------------------------------------------------------------===//
4252// BlockDecl Implementation
4253//===----------------------------------------------------------------------===//
4254
Erich Keanec9d29902018-08-01 21:16:54 +00004255BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4256 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4257 setIsVariadic(false);
4258 setCapturesCXXThis(false);
4259 setBlockMissingReturnType(true);
4260 setIsConversionFromLambda(false);
4261 setDoesNotEscape(false);
4262}
4263
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004264void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
Craig Topper36250ad2014-05-12 05:36:57 +00004265 assert(!ParamInfo && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00004266
Steve Naroffc4b30e52009-03-13 16:56:44 +00004267 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00004268 if (!NewParamInfo.empty()) {
4269 NumParams = NewParamInfo.size();
4270 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4271 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00004272 }
4273}
4274
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004275void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4276 bool CapturesCXXThis) {
Erich Keanec9d29902018-08-01 21:16:54 +00004277 this->setCapturesCXXThis(CapturesCXXThis);
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004278 this->NumCaptures = Captures.size();
John McCallc63de662011-02-02 13:00:07 +00004279
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004280 if (Captures.empty()) {
4281 this->Captures = nullptr;
John McCallc63de662011-02-02 13:00:07 +00004282 return;
4283 }
4284
Benjamin Kramerb40e4af2015-08-05 09:40:35 +00004285 this->Captures = Captures.copy(Context).data();
Steve Naroffc4b30e52009-03-13 16:56:44 +00004286}
Sebastian Redl833ef452010-01-26 22:01:41 +00004287
John McCallce45f882011-06-15 22:51:16 +00004288bool BlockDecl::capturesVariable(const VarDecl *variable) const {
Aaron Ballman9371dd22014-03-14 18:34:04 +00004289 for (const auto &I : captures())
John McCallce45f882011-06-15 22:51:16 +00004290 // Only auto vars can be captured, so no redeclaration worries.
Aaron Ballman9371dd22014-03-14 18:34:04 +00004291 if (I.getVariable() == variable)
John McCallce45f882011-06-15 22:51:16 +00004292 return true;
4293
4294 return false;
4295}
4296
Douglas Gregor70226da2010-12-21 16:27:07 +00004297SourceRange BlockDecl::getSourceRange() const {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004298 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
Douglas Gregor70226da2010-12-21 16:27:07 +00004299}
Sebastian Redl833ef452010-01-26 22:01:41 +00004300
4301//===----------------------------------------------------------------------===//
4302// Other Decl Allocation/Deallocation Method Implementations
4303//===----------------------------------------------------------------------===//
4304
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004305void TranslationUnitDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004306
Sebastian Redl833ef452010-01-26 22:01:41 +00004307TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
Craig Topper36250ad2014-05-12 05:36:57 +00004308 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
Sebastian Redl833ef452010-01-26 22:01:41 +00004309}
4310
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004311void PragmaCommentDecl::anchor() {}
Nico Weber66220292016-03-02 17:28:48 +00004312
4313PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4314 TranslationUnitDecl *DC,
4315 SourceLocation CommentLoc,
4316 PragmaMSCommentKind CommentKind,
4317 StringRef Arg) {
4318 PragmaCommentDecl *PCD =
4319 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4320 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4321 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4322 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4323 return PCD;
4324}
4325
4326PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4327 unsigned ID,
4328 unsigned ArgSize) {
4329 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4330 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4331}
4332
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004333void PragmaDetectMismatchDecl::anchor() {}
Nico Webercbbaeb12016-03-02 19:28:54 +00004334
4335PragmaDetectMismatchDecl *
4336PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4337 SourceLocation Loc, StringRef Name,
4338 StringRef Value) {
4339 size_t ValueStart = Name.size() + 1;
4340 PragmaDetectMismatchDecl *PDMD =
4341 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4342 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4343 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4344 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4345 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4346 Value.size());
4347 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4348 return PDMD;
4349}
4350
4351PragmaDetectMismatchDecl *
4352PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4353 unsigned NameValueSize) {
4354 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4355 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4356}
Nico Weber66220292016-03-02 17:28:48 +00004357
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004358void ExternCContextDecl::anchor() {}
Richard Smithf19e1272015-03-07 00:04:49 +00004359
4360ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4361 TranslationUnitDecl *DC) {
4362 return new (C, DC) ExternCContextDecl(DC);
4363}
4364
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004365void LabelDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004366
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004367LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004368 SourceLocation IdentL, IdentifierInfo *II) {
Craig Topper36250ad2014-05-12 05:36:57 +00004369 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
Abramo Bagnara1c3af962011-03-05 18:21:20 +00004370}
4371
4372LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4373 SourceLocation IdentL, IdentifierInfo *II,
4374 SourceLocation GnuLabelL) {
4375 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
Craig Topper36250ad2014-05-12 05:36:57 +00004376 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00004377}
4378
Douglas Gregor72172e92012-01-05 21:55:30 +00004379LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004380 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4381 SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00004382}
4383
Ehsan Akhgari31097582014-09-22 02:21:54 +00004384void LabelDecl::setMSAsmLabel(StringRef Name) {
4385 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4386 memcpy(Buffer, Name.data(), Name.size());
4387 Buffer[Name.size()] = '\0';
4388 MSAsmName = Buffer;
4389}
4390
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004391void ValueDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004392
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004393bool ValueDecl::isWeak() const {
Aaron Ballmanb97112e2014-03-08 22:19:01 +00004394 for (const auto *I : attrs())
4395 if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
Benjamin Kramerea70eb32012-12-01 15:09:41 +00004396 return true;
4397
4398 return isWeakImported();
4399}
4400
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004401void ImplicitParamDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004402
Sebastian Redl833ef452010-01-26 22:01:41 +00004403ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004404 SourceLocation IdLoc,
Alexey Bataev56223232017-06-09 13:40:18 +00004405 IdentifierInfo *Id, QualType Type,
4406 ImplicitParamKind ParamKind) {
4407 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4408}
4409
4410ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4411 ImplicitParamKind ParamKind) {
4412 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
Sebastian Redl833ef452010-01-26 22:01:41 +00004413}
4414
Richard Smithf7981722013-11-22 09:01:48 +00004415ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004416 unsigned ID) {
Alexey Bataev56223232017-06-09 13:40:18 +00004417 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
Douglas Gregor72172e92012-01-05 21:55:30 +00004418}
4419
Sebastian Redl833ef452010-01-26 22:01:41 +00004420FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00004421 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004422 const DeclarationNameInfo &NameInfo,
4423 QualType T, TypeSourceInfo *TInfo,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004424 StorageClass SC,
Richard Smithf7981722013-11-22 09:01:48 +00004425 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00004426 bool hasWrittenPrototype,
4427 bool isConstexprSpecified) {
Richard Smithf7981722013-11-22 09:01:48 +00004428 FunctionDecl *New =
Richard Smith053f6c62014-05-16 23:01:30 +00004429 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4430 SC, isInlineSpecified, isConstexprSpecified);
Erich Keane9c665062018-08-01 21:02:40 +00004431 New->setHasWrittenPrototype(hasWrittenPrototype);
Sebastian Redl833ef452010-01-26 22:01:41 +00004432 return New;
4433}
4434
Douglas Gregor72172e92012-01-05 21:55:30 +00004435FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004436 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004437 DeclarationNameInfo(), QualType(), nullptr,
Richard Smithf7981722013-11-22 09:01:48 +00004438 SC_None, false, false);
Douglas Gregor72172e92012-01-05 21:55:30 +00004439}
4440
Sebastian Redl833ef452010-01-26 22:01:41 +00004441BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004442 return new (C, DC) BlockDecl(DC, L);
Sebastian Redl833ef452010-01-26 22:01:41 +00004443}
4444
Douglas Gregor72172e92012-01-05 21:55:30 +00004445BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004446 return new (C, ID) BlockDecl(nullptr, SourceLocation());
John McCall5e77d762013-04-16 07:28:30 +00004447}
4448
Chandler Carruth21c90602015-12-30 03:24:14 +00004449CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4450 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4451 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4452
Ben Langmuir37943a72013-05-03 19:00:33 +00004453CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4454 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004455 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Richard Smithf7981722013-11-22 09:01:48 +00004456 CapturedDecl(DC, NumParams);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00004457}
4458
Ben Langmuirce914fc2013-05-03 19:20:19 +00004459CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
Richard Smithf7981722013-11-22 09:01:48 +00004460 unsigned NumParams) {
James Y Knight7a22b242015-08-06 20:26:32 +00004461 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
Craig Topper36250ad2014-05-12 05:36:57 +00004462 CapturedDecl(nullptr, NumParams);
Ben Langmuirce914fc2013-05-03 19:20:19 +00004463}
4464
Chandler Carruth21c90602015-12-30 03:24:14 +00004465Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4466void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4467
4468bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4469void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4470
Sebastian Redl833ef452010-01-26 22:01:41 +00004471EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4472 SourceLocation L,
4473 IdentifierInfo *Id, QualType T,
4474 Expr *E, const llvm::APSInt &V) {
Richard Smithf7981722013-11-22 09:01:48 +00004475 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
Sebastian Redl833ef452010-01-26 22:01:41 +00004476}
4477
Douglas Gregor72172e92012-01-05 21:55:30 +00004478EnumConstantDecl *
4479EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004480 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4481 QualType(), nullptr, llvm::APSInt());
Douglas Gregor72172e92012-01-05 21:55:30 +00004482}
4483
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004484void IndirectFieldDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004485
Richard Smith9f951822016-01-06 22:49:11 +00004486IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4487 SourceLocation L, DeclarationName N,
David Majnemer59f77922016-06-24 04:05:48 +00004488 QualType T,
4489 MutableArrayRef<NamedDecl *> CH)
4490 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4491 ChainingSize(CH.size()) {
Richard Smith9f951822016-01-06 22:49:11 +00004492 // In C++, indirect field declarations conflict with tag declarations in the
4493 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4494 if (C.getLangOpts().CPlusPlus)
4495 IdentifierNamespace |= IDNS_Tag;
4496}
4497
Benjamin Kramer39593702010-11-21 14:11:41 +00004498IndirectFieldDecl *
4499IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
David Majnemer59f77922016-06-24 04:05:48 +00004500 IdentifierInfo *Id, QualType T,
4501 llvm::MutableArrayRef<NamedDecl *> CH) {
4502 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
Francois Pichet783dd6e2010-11-21 06:08:52 +00004503}
4504
Douglas Gregor72172e92012-01-05 21:55:30 +00004505IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4506 unsigned ID) {
Richard Smith9f951822016-01-06 22:49:11 +00004507 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
David Majnemer59f77922016-06-24 04:05:48 +00004508 DeclarationName(), QualType(), None);
Douglas Gregor72172e92012-01-05 21:55:30 +00004509}
4510
Douglas Gregorbe996932010-09-01 20:41:53 +00004511SourceRange EnumConstantDecl::getSourceRange() const {
4512 SourceLocation End = getLocation();
4513 if (Init)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004514 End = Init->getEndLoc();
Douglas Gregorbe996932010-09-01 20:41:53 +00004515 return SourceRange(getLocation(), End);
4516}
4517
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004518void TypeDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004519
Sebastian Redl833ef452010-01-26 22:01:41 +00004520TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00004521 SourceLocation StartLoc, SourceLocation IdLoc,
4522 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004523 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00004524}
4525
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004526void TypedefNameDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004527
Richard Smith42413142015-05-15 20:05:43 +00004528TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4529 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4530 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4531 auto *ThisTypedef = this;
4532 if (AnyRedecl && OwningTypedef) {
4533 OwningTypedef = OwningTypedef->getCanonicalDecl();
4534 ThisTypedef = ThisTypedef->getCanonicalDecl();
4535 }
4536 if (OwningTypedef == ThisTypedef)
Richard Smitha5230222015-03-27 01:37:43 +00004537 return TT->getDecl();
Richard Smith42413142015-05-15 20:05:43 +00004538 }
Richard Smitha5230222015-03-27 01:37:43 +00004539
4540 return nullptr;
4541}
4542
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004543bool TypedefNameDecl::isTransparentTagSlow() const {
4544 auto determineIsTransparent = [&]() {
4545 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4546 if (auto *TD = TT->getDecl()) {
4547 if (TD->getName() != getName())
4548 return false;
4549 SourceLocation TTLoc = getLocation();
4550 SourceLocation TDLoc = TD->getLocation();
4551 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4552 return false;
4553 SourceManager &SM = getASTContext().getSourceManager();
4554 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4555 }
4556 }
4557 return false;
4558 };
4559
4560 bool isTransparent = determineIsTransparent();
Benjamin Kramerdfb730a2018-01-26 14:14:11 +00004561 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
Argyrios Kyrtzidis3b25c912017-03-21 16:56:02 +00004562 return isTransparent;
4563}
4564
Douglas Gregor72172e92012-01-05 21:55:30 +00004565TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004566 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00004567 nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004568}
4569
Richard Smithdda56e42011-04-15 14:24:37 +00004570TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4571 SourceLocation StartLoc,
4572 SourceLocation IdLoc, IdentifierInfo *Id,
4573 TypeSourceInfo *TInfo) {
Richard Smith053f6c62014-05-16 23:01:30 +00004574 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00004575}
4576
Douglas Gregor72172e92012-01-05 21:55:30 +00004577TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Richard Smith053f6c62014-05-16 23:01:30 +00004578 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4579 SourceLocation(), nullptr, nullptr);
Douglas Gregor72172e92012-01-05 21:55:30 +00004580}
4581
Abramo Bagnaraea947882011-03-08 16:41:52 +00004582SourceRange TypedefDecl::getSourceRange() const {
4583 SourceLocation RangeEnd = getLocation();
4584 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4585 if (typeIsPostfix(TInfo->getType()))
4586 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4587 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004588 return SourceRange(getBeginLoc(), RangeEnd);
Abramo Bagnaraea947882011-03-08 16:41:52 +00004589}
4590
Richard Smithdda56e42011-04-15 14:24:37 +00004591SourceRange TypeAliasDecl::getSourceRange() const {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004592 SourceLocation RangeEnd = getBeginLoc();
Richard Smithdda56e42011-04-15 14:24:37 +00004593 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4594 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004595 return SourceRange(getBeginLoc(), RangeEnd);
Richard Smithdda56e42011-04-15 14:24:37 +00004596}
4597
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004598void FileScopeAsmDecl::anchor() {}
David Blaikie68e081d2011-12-20 02:48:34 +00004599
Sebastian Redl833ef452010-01-26 22:01:41 +00004600FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00004601 StringLiteral *Str,
4602 SourceLocation AsmLoc,
4603 SourceLocation RParenLoc) {
Richard Smithf7981722013-11-22 09:01:48 +00004604 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00004605}
Douglas Gregorba345522011-12-02 23:23:56 +00004606
Richard Smithf7981722013-11-22 09:01:48 +00004607FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
Douglas Gregor72172e92012-01-05 21:55:30 +00004608 unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004609 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4610 SourceLocation());
Douglas Gregor72172e92012-01-05 21:55:30 +00004611}
4612
Michael Han84324352013-02-22 17:15:32 +00004613void EmptyDecl::anchor() {}
4614
4615EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
Richard Smithf7981722013-11-22 09:01:48 +00004616 return new (C, DC) EmptyDecl(DC, L);
Michael Han84324352013-02-22 17:15:32 +00004617}
4618
4619EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
Craig Topper36250ad2014-05-12 05:36:57 +00004620 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
Michael Han84324352013-02-22 17:15:32 +00004621}
4622
Douglas Gregorba345522011-12-02 23:23:56 +00004623//===----------------------------------------------------------------------===//
4624// ImportDecl Implementation
4625//===----------------------------------------------------------------------===//
4626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004627/// Retrieve the number of module identifiers needed to name the given
Douglas Gregorba345522011-12-02 23:23:56 +00004628/// module.
4629static unsigned getNumModuleIdentifiers(Module *Mod) {
4630 unsigned Result = 1;
4631 while (Mod->Parent) {
4632 Mod = Mod->Parent;
4633 ++Result;
4634 }
4635 return Result;
4636}
4637
Fangrui Song6907ce22018-07-30 19:24:48 +00004638ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004639 Module *Imported,
4640 ArrayRef<SourceLocation> IdentifierLocs)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004641 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true) {
Douglas Gregorba345522011-12-02 23:23:56 +00004642 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004643 auto *StoredLocs = getTrailingObjects<SourceLocation>();
James Y Knight7a22b242015-08-06 20:26:32 +00004644 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4645 StoredLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004646}
4647
Fangrui Song6907ce22018-07-30 19:24:48 +00004648ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00004649 Module *Imported, SourceLocation EndLoc)
Eugene Zelenkode0215c2017-11-13 23:01:27 +00004650 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false) {
James Y Knight7a22b242015-08-06 20:26:32 +00004651 *getTrailingObjects<SourceLocation>() = EndLoc;
Douglas Gregorba345522011-12-02 23:23:56 +00004652}
4653
Richard Smithf7981722013-11-22 09:01:48 +00004654ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004655 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004656 ArrayRef<SourceLocation> IdentifierLocs) {
James Y Knight7a22b242015-08-06 20:26:32 +00004657 return new (C, DC,
4658 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
Richard Smithf7981722013-11-22 09:01:48 +00004659 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00004660}
4661
Richard Smithf7981722013-11-22 09:01:48 +00004662ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00004663 SourceLocation StartLoc,
Richard Smithf7981722013-11-22 09:01:48 +00004664 Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00004665 SourceLocation EndLoc) {
James Y Knight7a22b242015-08-06 20:26:32 +00004666 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4667 ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00004668 Import->setImplicit();
4669 return Import;
4670}
4671
Douglas Gregor72172e92012-01-05 21:55:30 +00004672ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4673 unsigned NumLocations) {
James Y Knight7a22b242015-08-06 20:26:32 +00004674 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
Richard Smithf7981722013-11-22 09:01:48 +00004675 ImportDecl(EmptyShell());
Douglas Gregorba345522011-12-02 23:23:56 +00004676}
4677
4678ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4679 if (!ImportedAndComplete.getInt())
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00004680 return None;
Douglas Gregorba345522011-12-02 23:23:56 +00004681
Alexander Kornienkofd6ce042015-11-09 17:53:06 +00004682 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
Craig Topper5fc8fc22014-08-27 06:28:36 +00004683 return llvm::makeArrayRef(StoredLocs,
4684 getNumModuleIdentifiers(getImportedModule()));
Douglas Gregorba345522011-12-02 23:23:56 +00004685}
4686
4687SourceRange ImportDecl::getSourceRange() const {
4688 if (!ImportedAndComplete.getInt())
James Y Knight7a22b242015-08-06 20:26:32 +00004689 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4690
Douglas Gregorba345522011-12-02 23:23:56 +00004691 return SourceRange(getLocation(), getIdentifierLocs().back());
4692}
Richard Smith8df390f2016-09-08 23:14:54 +00004693
4694//===----------------------------------------------------------------------===//
4695// ExportDecl Implementation
4696//===----------------------------------------------------------------------===//
4697
4698void ExportDecl::anchor() {}
4699
4700ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
4701 SourceLocation ExportLoc) {
4702 return new (C, DC) ExportDecl(DC, ExportLoc);
4703}
4704
4705ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4706 return new (C, ID) ExportDecl(nullptr, SourceLocation());
4707}