blob: 7db38a9130099a235638f3e7189f6deb5f1b11d7 [file] [log] [blame]
Chris Lattnera11999d2006-10-15 22:34:45 +00001//===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnera11999d2006-10-15 22:34:45 +00007//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis63018842008-06-04 13:04:04 +000010// This file implements the Decl subclasses.
Chris Lattnera11999d2006-10-15 22:34:45 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Decl.h"
Douglas Gregor889ceb72009-02-03 19:21:40 +000015#include "clang/AST/DeclCXX.h"
Steve Naroffc4173fa2009-02-22 19:35:57 +000016#include "clang/AST/DeclObjC.h"
Douglas Gregore362cea2009-05-10 22:57:19 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattnera7b32872008-03-15 06:12:44 +000018#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +000019#include "clang/AST/TypeLoc.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000020#include "clang/AST/Stmt.h"
Nuno Lopes394ec982008-12-17 23:39:55 +000021#include "clang/AST/Expr.h"
Anders Carlsson714d0962009-12-15 19:16:31 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor7de59662009-05-29 20:38:28 +000023#include "clang/AST/PrettyPrinter.h"
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +000024#include "clang/AST/ASTMutationListener.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000026#include "clang/Basic/IdentifierTable.h"
Douglas Gregorba345522011-12-02 23:23:56 +000027#include "clang/Basic/Module.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000028#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000029#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000030#include "llvm/Support/ErrorHandling.h"
Ted Kremenekce20e8f2008-05-20 00:43:19 +000031
David Blaikie9c70e042011-09-21 18:16:56 +000032#include <algorithm>
33
Chris Lattner6d9a6852006-10-25 05:11:20 +000034using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000035
Chris Lattner88f70d62008-03-15 05:43:15 +000036//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000037// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000038//===----------------------------------------------------------------------===//
39
Douglas Gregor1baf38f2011-03-26 12:10:19 +000040static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
41 // If this declaration has an explicit visibility attribute, use it.
42 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
43 switch (A->getVisibility()) {
44 case VisibilityAttr::Default:
45 return DefaultVisibility;
46 case VisibilityAttr::Hidden:
47 return HiddenVisibility;
48 case VisibilityAttr::Protected:
49 return ProtectedVisibility;
50 }
John McCall457a04e2010-10-22 21:05:15 +000051 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +000052
53 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
54 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +000055 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +000056 for (specific_attr_iterator<AvailabilityAttr>
57 A = D->specific_attr_begin<AvailabilityAttr>(),
58 AEnd = D->specific_attr_end<AvailabilityAttr>();
59 A != AEnd; ++A)
60 if ((*A)->getPlatform()->getName().equals("macosx"))
61 return DefaultVisibility;
62 }
63
64 return llvm::Optional<Visibility>();
John McCall457a04e2010-10-22 21:05:15 +000065}
66
John McCallc273f242010-10-30 11:50:40 +000067typedef NamedDecl::LinkageInfo LinkageInfo;
John McCallc273f242010-10-30 11:50:40 +000068
Benjamin Kramer396dcf32010-11-05 19:56:37 +000069namespace {
John McCall07072662010-11-02 01:45:15 +000070/// Flags controlling the computation of linkage and visibility.
71struct LVFlags {
Rafael Espindola505a7c82012-04-16 18:25:01 +000072 const bool ConsiderGlobalVisibility;
73 const bool ConsiderVisibilityAttributes;
74 const bool ConsiderTemplateParameterTypes;
John McCall07072662010-11-02 01:45:15 +000075
76 LVFlags() : ConsiderGlobalVisibility(true),
John McCall8bc6d5b2011-03-04 10:39:25 +000077 ConsiderVisibilityAttributes(true),
78 ConsiderTemplateParameterTypes(true) {
John McCall07072662010-11-02 01:45:15 +000079 }
80
Rafael Espindola9d287402012-04-16 13:44:41 +000081 LVFlags(bool Global, bool Attributes, bool Parameters) :
82 ConsiderGlobalVisibility(Global),
83 ConsiderVisibilityAttributes(Attributes),
84 ConsiderTemplateParameterTypes(Parameters) {
85 }
86
Douglas Gregorbf62d642010-12-06 18:36:25 +000087 /// \brief Returns a set of flags that is only useful for computing the
88 /// linkage, not the visibility, of a declaration.
89 static LVFlags CreateOnlyDeclLinkage() {
Rafael Espindola9d287402012-04-16 13:44:41 +000090 return LVFlags(false, false, false);
John McCall07072662010-11-02 01:45:15 +000091 }
Douglas Gregor91df6cf2010-12-06 18:50:56 +000092};
Benjamin Kramer396dcf32010-11-05 19:56:37 +000093} // end anonymous namespace
John McCall07072662010-11-02 01:45:15 +000094
Rafael Espindola2f869a32012-01-14 00:30:36 +000095static LinkageInfo getLVForType(QualType T) {
96 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
97 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
98}
99
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000100/// \brief Get the most restrictive linkage for the types in the given
101/// template parameter list.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000102static LinkageInfo
John McCall457a04e2010-10-22 21:05:15 +0000103getLVForTemplateParameterList(const TemplateParameterList *Params) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000104 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000105 for (TemplateParameterList::const_iterator P = Params->begin(),
106 PEnd = Params->end();
107 P != PEnd; ++P) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000108 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
109 if (NTTP->isExpandedParameterPack()) {
110 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
111 QualType T = NTTP->getExpansionType(I);
112 if (!T->isDependentType())
Rafael Espindola2f869a32012-01-14 00:30:36 +0000113 LV.merge(getLVForType(T));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000114 }
115 continue;
116 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000117
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000118 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000119 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000120 continue;
121 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000122 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000123
124 if (TemplateTemplateParmDecl *TTP
125 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000126 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000127 }
128 }
129
John McCall457a04e2010-10-22 21:05:15 +0000130 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000131}
132
Douglas Gregorbf62d642010-12-06 18:36:25 +0000133/// getLVForDecl - Get the linkage and visibility for the given declaration.
134static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
135
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000136/// \brief Get the most restrictive linkage for the types and
137/// declarations in the given template argument list.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000138static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
139 unsigned NumArgs,
140 LVFlags &F) {
141 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000142
143 for (unsigned I = 0; I != NumArgs; ++I) {
144 switch (Args[I].getKind()) {
145 case TemplateArgument::Null:
146 case TemplateArgument::Integral:
147 case TemplateArgument::Expression:
148 break;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000149
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000150 case TemplateArgument::Type:
Rafael Espindola2f869a32012-01-14 00:30:36 +0000151 LV.merge(getLVForType(Args[I].getAsType()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000152 break;
153
154 case TemplateArgument::Declaration:
John McCall457a04e2010-10-22 21:05:15 +0000155 // The decl can validly be null as the representation of nullptr
156 // arguments, valid only in C++0x.
157 if (Decl *D = Args[I].getAsDecl()) {
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000158 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
159 LV = merge(LV, getLVForDecl(ND, F));
John McCall457a04e2010-10-22 21:05:15 +0000160 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000161 break;
162
163 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000164 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000165 if (TemplateDecl *Template
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000166 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindola2f869a32012-01-14 00:30:36 +0000167 LV.merge(getLVForDecl(Template, F));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000168 break;
169
170 case TemplateArgument::Pack:
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000171 LV.mergeWithMin(getLVForTemplateArgumentList(Args[I].pack_begin(),
172 Args[I].pack_size(),
173 F));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000174 break;
175 }
176 }
177
John McCall457a04e2010-10-22 21:05:15 +0000178 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000179}
180
Rafael Espindola2f869a32012-01-14 00:30:36 +0000181static LinkageInfo
Douglas Gregorbf62d642010-12-06 18:36:25 +0000182getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
183 LVFlags &F) {
184 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
John McCall8823c652010-08-13 08:35:10 +0000185}
186
John McCallb8c604a2011-06-27 23:06:04 +0000187static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
188 const FunctionTemplateSpecializationInfo *spec) {
189 return !(spec->isExplicitSpecialization() &&
190 fn->hasAttr<VisibilityAttr>());
191}
192
193static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
194 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
195}
196
John McCall07072662010-11-02 01:45:15 +0000197static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000198 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000199 "Not a name having namespace scope");
200 ASTContext &Context = D->getASTContext();
201
202 // C++ [basic.link]p3:
203 // A name having namespace scope (3.3.6) has internal linkage if it
204 // is the name of
205 // - an object, reference, function or function template that is
206 // explicitly declared static; or,
207 // (This bullet corresponds to C99 6.2.2p3.)
208 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
209 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000210 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000211 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000212
213 // - an object or reference that is explicitly declared const
214 // and neither explicitly declared extern nor previously
215 // declared to have external linkage; or
216 // (there is no equivalent in C99)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000217 if (Context.getLangOpts().CPlusPlus &&
Eli Friedmanf873c2f2009-11-26 03:04:01 +0000218 Var->getType().isConstant(Context) &&
John McCall8e7d6562010-08-26 03:08:43 +0000219 Var->getStorageClass() != SC_Extern &&
220 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000221 bool FoundExtern = false;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000222 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000223 PrevVar && !FoundExtern;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000224 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000225 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000226 FoundExtern = true;
227
228 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000229 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000230 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000231 if (Var->getStorageClass() == SC_None) {
Douglas Gregorec9fd132012-01-14 16:38:05 +0000232 const VarDecl *PrevVar = Var->getPreviousDecl();
233 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000234 if (PrevVar->getStorageClass() == SC_PrivateExtern)
235 break;
236 if (PrevVar)
237 return PrevVar->getLinkageAndVisibility();
238 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000239 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000240 // C++ [temp]p4:
241 // A non-member function template can have internal linkage; any
242 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000243 const FunctionDecl *Function = 0;
244 if (const FunctionTemplateDecl *FunTmpl
245 = dyn_cast<FunctionTemplateDecl>(D))
246 Function = FunTmpl->getTemplatedDecl();
247 else
248 Function = cast<FunctionDecl>(D);
249
250 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000251 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000252 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000253 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
254 // - a data member of an anonymous union.
255 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000256 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000257 }
258
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000259 if (D->isInAnonymousNamespace()) {
260 const VarDecl *Var = dyn_cast<VarDecl>(D);
261 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Eli Friedman839192f2012-01-15 01:23:58 +0000262 if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
263 (!Func || !Func->getDeclContext()->isExternCContext()))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000264 return LinkageInfo::uniqueExternal();
265 }
John McCallb7139c42010-10-28 04:18:25 +0000266
John McCall457a04e2010-10-22 21:05:15 +0000267 // Set up the defaults.
268
269 // C99 6.2.2p5:
270 // If the declaration of an identifier for an object has file
271 // scope and no storage-class specifier, its linkage is
272 // external.
John McCallc273f242010-10-30 11:50:40 +0000273 LinkageInfo LV;
274
Rafael Espindola78158af2012-04-16 18:46:26 +0000275 if (F.ConsiderVisibilityAttributes) {
276 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000277 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000278 } else {
279 // If we're declared in a namespace with a visibility attribute,
280 // use that namespace's visibility, but don't call it explicit.
281 for (const DeclContext *DC = D->getDeclContext();
282 !isa<TranslationUnitDecl>(DC);
283 DC = DC->getParent()) {
284 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
285 if (!ND) continue;
286 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000287 LV.mergeVisibility(*Vis, true);
Rafael Espindola78158af2012-04-16 18:46:26 +0000288 break;
289 }
290 }
291 }
292 }
293
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000294 LV.mergeVisibility(Context.getLangOpts().getVisibilityMode());
295
Douglas Gregorf73b2822009-11-25 22:24:25 +0000296 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000297
Douglas Gregorf73b2822009-11-25 22:24:25 +0000298 // A name having namespace scope has external linkage if it is the
299 // name of
300 //
301 // - an object or reference, unless it has internal linkage; or
302 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000303 // GCC applies the following optimization to variables and static
304 // data members, but not to functions:
305 //
John McCall457a04e2010-10-22 21:05:15 +0000306 // Modify the variable's LV by the LV of its type unless this is
307 // C or extern "C". This follows from [basic.link]p9:
308 // A type without linkage shall not be used as the type of a
309 // variable or function with external linkage unless
310 // - the entity has C language linkage, or
311 // - the entity is declared within an unnamed namespace, or
312 // - the entity is not used or is defined in the same
313 // translation unit.
314 // and [basic.link]p10:
315 // ...the types specified by all declarations referring to a
316 // given variable or function shall be identical...
317 // C does not have an equivalent rule.
318 //
John McCall5fe84122010-10-26 04:59:26 +0000319 // Ignore this if we've got an explicit attribute; the user
320 // probably knows what they're doing.
321 //
John McCall457a04e2010-10-22 21:05:15 +0000322 // Note that we don't want to make the variable non-external
323 // because of this, but unique-external linkage suits us.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000324 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000325 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000326 LinkageInfo TypeLV = getLVForType(Var->getType());
327 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000328 return LinkageInfo::uniqueExternal();
Rafael Espindola2dd5ed52012-04-17 18:47:20 +0000329 LV.mergeVisibilityWithMin(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000330 }
331
John McCall23032652010-11-02 18:38:13 +0000332 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000333 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000334
David Blaikiebbafb8a2012-03-11 07:00:24 +0000335 if (!Context.getLangOpts().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000336 (Var->getStorageClass() == SC_Extern ||
337 Var->getStorageClass() == SC_PrivateExtern)) {
John McCall457a04e2010-10-22 21:05:15 +0000338
Douglas Gregorf73b2822009-11-25 22:24:25 +0000339 // C99 6.2.2p4:
340 // For an identifier declared with the storage-class specifier
341 // extern in a scope in which a prior declaration of that
342 // identifier is visible, if the prior declaration specifies
343 // internal or external linkage, the linkage of the identifier
344 // at the later declaration is the same as the linkage
345 // specified at the prior declaration. If no prior declaration
346 // is visible, or if the prior declaration specifies no
347 // linkage, then the identifier has external linkage.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000348 if (const VarDecl *PrevVar = Var->getPreviousDecl()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000349 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
John McCallc273f242010-10-30 11:50:40 +0000350 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
351 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000352 }
353 }
354
Douglas Gregorf73b2822009-11-25 22:24:25 +0000355 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000356 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000357 // In theory, we can modify the function's LV by the LV of its
358 // type unless it has C linkage (see comment above about variables
359 // for justification). In practice, GCC doesn't do this, so it's
360 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000361
John McCall23032652010-11-02 18:38:13 +0000362 if (Function->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000363 LV.mergeVisibility(HiddenVisibility, true);
John McCall23032652010-11-02 18:38:13 +0000364
Douglas Gregorf73b2822009-11-25 22:24:25 +0000365 // C99 6.2.2p5:
366 // If the declaration of an identifier for a function has no
367 // storage-class specifier, its linkage is determined exactly
368 // as if it were declared with the storage-class specifier
369 // extern.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000370 if (!Context.getLangOpts().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000371 (Function->getStorageClass() == SC_Extern ||
372 Function->getStorageClass() == SC_PrivateExtern ||
373 Function->getStorageClass() == SC_None)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000374 // C99 6.2.2p4:
375 // For an identifier declared with the storage-class specifier
376 // extern in a scope in which a prior declaration of that
377 // identifier is visible, if the prior declaration specifies
378 // internal or external linkage, the linkage of the identifier
379 // at the later declaration is the same as the linkage
380 // specified at the prior declaration. If no prior declaration
381 // is visible, or if the prior declaration specifies no
382 // linkage, then the identifier has external linkage.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000383 if (const FunctionDecl *PrevFunc = Function->getPreviousDecl()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000384 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
John McCallc273f242010-10-30 11:50:40 +0000385 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
386 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000387 }
388 }
389
John McCallf768aa72011-02-10 06:50:24 +0000390 // In C++, then if the type of the function uses a type with
391 // unique-external linkage, it's not legally usable from outside
392 // this translation unit. However, we should use the C linkage
393 // rules instead for extern "C" declarations.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000394 if (Context.getLangOpts().CPlusPlus &&
Eli Friedman839192f2012-01-15 01:23:58 +0000395 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000396 Function->getType()->getLinkage() == UniqueExternalLinkage)
397 return LinkageInfo::uniqueExternal();
398
John McCallb8c604a2011-06-27 23:06:04 +0000399 // Consider LV from the template and the template arguments unless
400 // this is an explicit specialization with a visibility attribute.
401 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000402 = Function->getTemplateSpecializationInfo()) {
John McCallb8c604a2011-06-27 23:06:04 +0000403 if (shouldConsiderTemplateLV(Function, specInfo)) {
404 LV.merge(getLVForDecl(specInfo->getTemplate(),
Rafael Espindola9d287402012-04-16 13:44:41 +0000405 LVFlags::CreateOnlyDeclLinkage()));
John McCallb8c604a2011-06-27 23:06:04 +0000406 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000407 LV.mergeWithMin(getLVForTemplateArgumentList(templateArgs, F));
John McCallb8c604a2011-06-27 23:06:04 +0000408 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000409 }
410
Douglas Gregorf73b2822009-11-25 22:24:25 +0000411 // - a named class (Clause 9), or an unnamed class defined in a
412 // typedef declaration in which the class has the typedef name
413 // for linkage purposes (7.1.3); or
414 // - a named enumeration (7.2), or an unnamed enumeration
415 // defined in a typedef declaration in which the enumeration
416 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000417 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
418 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000419 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000420 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000421
John McCall457a04e2010-10-22 21:05:15 +0000422 // If this is a class template specialization, consider the
423 // linkage of the template and template arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000424 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000425 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCallb8c604a2011-06-27 23:06:04 +0000426 if (shouldConsiderTemplateLV(spec)) {
427 // From the template.
428 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
Rafael Espindola9d287402012-04-16 13:44:41 +0000429 LVFlags::CreateOnlyDeclLinkage()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000430
John McCallb8c604a2011-06-27 23:06:04 +0000431 // The arguments at which the template was instantiated.
432 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000433 LV.mergeWithMin(getLVForTemplateArgumentList(TemplateArgs, F));
John McCallb8c604a2011-06-27 23:06:04 +0000434 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000435 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000436
437 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000438 } else if (isa<EnumConstantDecl>(D)) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000439 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
John McCallc273f242010-10-30 11:50:40 +0000440 if (!isExternalLinkage(EnumLV.linkage()))
441 return LinkageInfo::none();
442 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000443
444 // - a template, unless it is a function template that has
445 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000446 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
447 if (F.ConsiderTemplateParameterTypes)
448 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000449
Douglas Gregorf73b2822009-11-25 22:24:25 +0000450 // - a namespace (7.3), unless it is declared within an unnamed
451 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000452 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
453 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000454
John McCall457a04e2010-10-22 21:05:15 +0000455 // By extension, we assign external linkage to Objective-C
456 // interfaces.
457 } else if (isa<ObjCInterfaceDecl>(D)) {
458 // fallout
459
460 // Everything not covered here has no linkage.
461 } else {
John McCallc273f242010-10-30 11:50:40 +0000462 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000463 }
464
465 // If we ended up with non-external linkage, visibility should
466 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000467 if (LV.linkage() != ExternalLinkage)
468 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000469
John McCall457a04e2010-10-22 21:05:15 +0000470 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000471}
472
John McCall07072662010-11-02 01:45:15 +0000473static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
John McCall457a04e2010-10-22 21:05:15 +0000474 // Only certain class members have linkage. Note that fields don't
475 // really have linkage, but it's convenient to say they do for the
476 // purposes of calculating linkage of pointer-to-data-member
477 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000478 if (!(isa<CXXMethodDecl>(D) ||
479 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000480 isa<FieldDecl>(D) ||
John McCall8823c652010-08-13 08:35:10 +0000481 (isa<TagDecl>(D) &&
Richard Smithdda56e42011-04-15 14:24:37 +0000482 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
John McCallc273f242010-10-30 11:50:40 +0000483 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000484
John McCall07072662010-11-02 01:45:15 +0000485 LinkageInfo LV;
486
John McCall07072662010-11-02 01:45:15 +0000487 // If we have an explicit visibility attribute, merge that in.
488 if (F.ConsiderVisibilityAttributes) {
Rafael Espindola3d3d3392012-04-19 04:27:47 +0000489 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility())
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000490 LV.mergeVisibility(*Vis, true);
John McCall07072662010-11-02 01:45:15 +0000491 }
Rafael Espindola505a7c82012-04-16 18:25:01 +0000492 // Ignore both global visibility and attributes when computing our
493 // parent's visibility if we already have an explicit one.
Rafael Espindola3d3d3392012-04-19 04:27:47 +0000494 LVFlags ClassF = LV.visibilityExplicit() ?
Rafael Espindola505a7c82012-04-16 18:25:01 +0000495 LVFlags::CreateOnlyDeclLinkage() : F;
496
497 // If we're paying attention to global visibility, apply
498 // -finline-visibility-hidden if this is an inline method.
499 //
500 // Note that we do this before merging information about
501 // the class visibility.
502 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
503 TemplateSpecializationKind TSK = TSK_Undeclared;
504 if (FunctionTemplateSpecializationInfo *spec
505 = MD->getTemplateSpecializationInfo()) {
506 TSK = spec->getTemplateSpecializationKind();
507 } else if (MemberSpecializationInfo *MSI =
508 MD->getMemberSpecializationInfo()) {
509 TSK = MSI->getTemplateSpecializationKind();
510 }
511
512 const FunctionDecl *Def = 0;
513 // InlineVisibilityHidden only applies to definitions, and
514 // isInlined() only gives meaningful answers on definitions
515 // anyway.
516 if (TSK != TSK_ExplicitInstantiationDeclaration &&
517 TSK != TSK_ExplicitInstantiationDefinition &&
518 F.ConsiderGlobalVisibility &&
519 !LV.visibilityExplicit() &&
520 MD->getASTContext().getLangOpts().InlineVisibilityHidden &&
521 MD->hasBody(Def) && Def->isInlined())
522 LV.mergeVisibility(HiddenVisibility, true);
523 }
John McCallc273f242010-10-30 11:50:40 +0000524
525 // Class members only have linkage if their class has external
John McCall07072662010-11-02 01:45:15 +0000526 // linkage.
527 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
528 if (!isExternalLinkage(LV.linkage()))
John McCallc273f242010-10-30 11:50:40 +0000529 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000530
531 // If the class already has unique-external linkage, we can't improve.
John McCall07072662010-11-02 01:45:15 +0000532 if (LV.linkage() == UniqueExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000533 return LinkageInfo::uniqueExternal();
John McCall8823c652010-08-13 08:35:10 +0000534
Rafael Espindolaaf690f52012-04-19 02:55:01 +0000535 LV.mergeVisibility(D->getASTContext().getLangOpts().getVisibilityMode());
536
John McCall8823c652010-08-13 08:35:10 +0000537 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000538 // If the type of the function uses a type with unique-external
539 // linkage, it's not legally usable from outside this translation unit.
540 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
541 return LinkageInfo::uniqueExternal();
542
John McCall457a04e2010-10-22 21:05:15 +0000543 // If this is a method template specialization, use the linkage for
544 // the template parameters and arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000545 if (FunctionTemplateSpecializationInfo *spec
John McCall8823c652010-08-13 08:35:10 +0000546 = MD->getTemplateSpecializationInfo()) {
John McCallb8c604a2011-06-27 23:06:04 +0000547 if (shouldConsiderTemplateLV(MD, spec)) {
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000548 LV.mergeWithMin(getLVForTemplateArgumentList(*spec->TemplateArguments,
549 F));
John McCallb8c604a2011-06-27 23:06:04 +0000550 if (F.ConsiderTemplateParameterTypes)
551 LV.merge(getLVForTemplateParameterList(
552 spec->getTemplate()->getTemplateParameters()));
553 }
John McCalle6e622e2010-11-01 01:29:57 +0000554 }
John McCall457a04e2010-10-22 21:05:15 +0000555
John McCall37bb6c92010-10-29 22:22:43 +0000556 // Note that in contrast to basically every other situation, we
557 // *do* apply -fvisibility to method declarations.
558
559 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000560 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000561 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCallb8c604a2011-06-27 23:06:04 +0000562 if (shouldConsiderTemplateLV(spec)) {
563 // Merge template argument/parameter information for member
564 // class template specializations.
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000565 LV.mergeWithMin(getLVForTemplateArgumentList(spec->getTemplateArgs(),
566 F));
John McCall8bc6d5b2011-03-04 10:39:25 +0000567 if (F.ConsiderTemplateParameterTypes)
568 LV.merge(getLVForTemplateParameterList(
John McCallb8c604a2011-06-27 23:06:04 +0000569 spec->getSpecializedTemplate()->getTemplateParameters()));
570 }
John McCall37bb6c92010-10-29 22:22:43 +0000571 }
572
John McCall37bb6c92010-10-29 22:22:43 +0000573 // Static data members.
574 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000575 // Modify the variable's linkage by its type, but ignore the
576 // type's visibility unless it's a definition.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000577 LinkageInfo TypeLV = getLVForType(VD->getType());
578 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000579 LV.mergeLinkage(UniqueExternalLinkage);
580 if (!LV.visibilityExplicit())
Rafael Espindola2dd5ed52012-04-17 18:47:20 +0000581 LV.mergeVisibility(TypeLV);
John McCall37bb6c92010-10-29 22:22:43 +0000582 }
583
John McCall457a04e2010-10-22 21:05:15 +0000584 return LV;
John McCall8823c652010-08-13 08:35:10 +0000585}
586
John McCalld396b972011-02-08 19:01:05 +0000587static void clearLinkageForClass(const CXXRecordDecl *record) {
588 for (CXXRecordDecl::decl_iterator
589 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
590 Decl *child = *i;
591 if (isa<NamedDecl>(child))
592 cast<NamedDecl>(child)->ClearLinkageCache();
593 }
594}
595
David Blaikie68e081d2011-12-20 02:48:34 +0000596void NamedDecl::anchor() { }
597
John McCalld396b972011-02-08 19:01:05 +0000598void NamedDecl::ClearLinkageCache() {
599 // Note that we can't skip clearing the linkage of children just
600 // because the parent doesn't have cached linkage: we don't cache
601 // when computing linkage for parent contexts.
602
603 HasCachedLinkage = 0;
604
605 // If we're changing the linkage of a class, we need to reset the
606 // linkage of child declarations, too.
607 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
608 clearLinkageForClass(record);
609
John McCall83779672011-02-19 02:53:41 +0000610 if (ClassTemplateDecl *temp =
611 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
John McCalld396b972011-02-08 19:01:05 +0000612 // Clear linkage for the template pattern.
613 CXXRecordDecl *record = temp->getTemplatedDecl();
614 record->HasCachedLinkage = 0;
615 clearLinkageForClass(record);
616
John McCall83779672011-02-19 02:53:41 +0000617 // We need to clear linkage for specializations, too.
618 for (ClassTemplateDecl::spec_iterator
619 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
620 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000621 }
John McCall83779672011-02-19 02:53:41 +0000622
623 // Clear cached linkage for function template decls, too.
624 if (FunctionTemplateDecl *temp =
John McCall8f9a4292011-03-22 06:58:49 +0000625 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
626 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000627 for (FunctionTemplateDecl::spec_iterator
628 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
629 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000630 }
John McCall83779672011-02-19 02:53:41 +0000631
John McCalld396b972011-02-08 19:01:05 +0000632}
633
Douglas Gregorbf62d642010-12-06 18:36:25 +0000634Linkage NamedDecl::getLinkage() const {
635 if (HasCachedLinkage) {
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000636 assert(Linkage(CachedLinkage) ==
637 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000638 return Linkage(CachedLinkage);
639 }
640
641 CachedLinkage = getLVForDecl(this,
642 LVFlags::CreateOnlyDeclLinkage()).linkage();
643 HasCachedLinkage = 1;
644 return Linkage(CachedLinkage);
645}
646
John McCallc273f242010-10-30 11:50:40 +0000647LinkageInfo NamedDecl::getLinkageAndVisibility() const {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000648 LinkageInfo LI = getLVForDecl(this, LVFlags());
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000649 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000650 HasCachedLinkage = 1;
651 CachedLinkage = LI.linkage();
652 return LI;
John McCall033caa52010-10-29 00:29:13 +0000653}
Ted Kremenek926d8602010-04-20 23:15:35 +0000654
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000655llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
656 // Use the most recent declaration of a variable.
657 if (const VarDecl *var = dyn_cast<VarDecl>(this))
Douglas Gregorec9fd132012-01-14 16:38:05 +0000658 return getVisibilityOf(var->getMostRecentDecl());
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000659
660 // Use the most recent declaration of a function, and also handle
661 // function template specializations.
662 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
663 if (llvm::Optional<Visibility> V
Douglas Gregorec9fd132012-01-14 16:38:05 +0000664 = getVisibilityOf(fn->getMostRecentDecl()))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000665 return V;
666
667 // If the function is a specialization of a template with an
668 // explicit visibility attribute, use that.
669 if (FunctionTemplateSpecializationInfo *templateInfo
670 = fn->getTemplateSpecializationInfo())
671 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
672
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000673 // If the function is a member of a specialization of a class template
674 // and the corresponding decl has explicit visibility, use that.
675 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
676 if (InstantiatedFrom)
677 return getVisibilityOf(InstantiatedFrom);
678
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000679 return llvm::Optional<Visibility>();
680 }
681
682 // Otherwise, just check the declaration itself first.
683 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
684 return V;
685
686 // If there wasn't explicit visibility there, and this is a
687 // specialization of a class template, check for visibility
688 // on the pattern.
689 if (const ClassTemplateSpecializationDecl *spec
690 = dyn_cast<ClassTemplateSpecializationDecl>(this))
691 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
692
Rafael Espindola8093fdf2012-02-23 04:17:32 +0000693 // If this is a member class of a specialization of a class template
694 // and the corresponding decl has explicit visibility, use that.
695 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
696 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
697 if (InstantiatedFrom)
698 return getVisibilityOf(InstantiatedFrom);
699 }
700
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000701 return llvm::Optional<Visibility>();
702}
703
John McCall07072662010-11-02 01:45:15 +0000704static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000705 // Objective-C: treat all Objective-C declarations as having external
706 // linkage.
John McCall033caa52010-10-29 00:29:13 +0000707 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000708 default:
709 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +0000710 case Decl::ParmVar:
711 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000712 case Decl::TemplateTemplateParm: // count these as external
713 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +0000714 case Decl::ObjCAtDefsField:
715 case Decl::ObjCCategory:
716 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +0000717 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +0000718 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +0000719 case Decl::ObjCMethod:
720 case Decl::ObjCProperty:
721 case Decl::ObjCPropertyImpl:
722 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +0000723 return LinkageInfo::external();
Douglas Gregor6f88e5e2012-02-21 04:17:39 +0000724
725 case Decl::CXXRecord: {
726 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
727 if (Record->isLambda()) {
728 if (!Record->getLambdaManglingNumber()) {
729 // This lambda has no mangling number, so it's internal.
730 return LinkageInfo::internal();
731 }
732
733 // This lambda has its linkage/visibility determined by its owner.
734 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
735 if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
736 if (isa<ParmVarDecl>(ContextDecl))
737 DC = ContextDecl->getDeclContext()->getRedeclContext();
738 else
739 return getLVForDecl(cast<NamedDecl>(ContextDecl), Flags);
740 }
741
742 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
743 return getLVForDecl(ND, Flags);
744
745 return LinkageInfo::external();
746 }
747
748 break;
749 }
Ted Kremenek926d8602010-04-20 23:15:35 +0000750 }
751
Douglas Gregorf73b2822009-11-25 22:24:25 +0000752 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +0000753 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall07072662010-11-02 01:45:15 +0000754 return getLVForNamespaceScopeDecl(D, Flags);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000755
756 // C++ [basic.link]p5:
757 // In addition, a member function, static data member, a named
758 // class or enumeration of class scope, or an unnamed class or
759 // enumeration defined in a class-scope typedef declaration such
760 // that the class or enumeration has the typedef name for linkage
761 // purposes (7.1.3), has external linkage if the name of the class
762 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +0000763 if (D->getDeclContext()->isRecord())
John McCall07072662010-11-02 01:45:15 +0000764 return getLVForClassMember(D, Flags);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000765
766 // C++ [basic.link]p6:
767 // The name of a function declared in block scope and the name of
768 // an object declared by a block scope extern declaration have
769 // linkage. If there is a visible declaration of an entity with
770 // linkage having the same name and type, ignoring entities
771 // declared outside the innermost enclosing namespace scope, the
772 // block scope declaration declares that same entity and receives
773 // the linkage of the previous declaration. If there is more than
774 // one such matching entity, the program is ill-formed. Otherwise,
775 // if no matching entity is found, the block scope entity receives
776 // external linkage.
John McCall033caa52010-10-29 00:29:13 +0000777 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
778 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Eli Friedman839192f2012-01-15 01:23:58 +0000779 if (Function->isInAnonymousNamespace() &&
780 !Function->getDeclContext()->isExternCContext())
John McCallc273f242010-10-30 11:50:40 +0000781 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000782
John McCallc273f242010-10-30 11:50:40 +0000783 LinkageInfo LV;
Douglas Gregorbf62d642010-12-06 18:36:25 +0000784 if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000785 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000786 LV.mergeVisibility(*Vis, true);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000787 }
788
Douglas Gregorec9fd132012-01-14 16:38:05 +0000789 if (const FunctionDecl *Prev = Function->getPreviousDecl()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000790 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallc273f242010-10-30 11:50:40 +0000791 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
792 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000793 }
794
795 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000796 }
797
John McCall033caa52010-10-29 00:29:13 +0000798 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
John McCall8e7d6562010-08-26 03:08:43 +0000799 if (Var->getStorageClass() == SC_Extern ||
800 Var->getStorageClass() == SC_PrivateExtern) {
Eli Friedman839192f2012-01-15 01:23:58 +0000801 if (Var->isInAnonymousNamespace() &&
802 !Var->getDeclContext()->isExternCContext())
John McCallc273f242010-10-30 11:50:40 +0000803 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000804
John McCallc273f242010-10-30 11:50:40 +0000805 LinkageInfo LV;
John McCall457a04e2010-10-22 21:05:15 +0000806 if (Var->getStorageClass() == SC_PrivateExtern)
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000807 LV.mergeVisibility(HiddenVisibility, true);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000808 else if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000809 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
Rafael Espindola7a5543d2012-04-19 02:22:07 +0000810 LV.mergeVisibility(*Vis, true);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000811 }
812
Douglas Gregorec9fd132012-01-14 16:38:05 +0000813 if (const VarDecl *Prev = Var->getPreviousDecl()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000814 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallc273f242010-10-30 11:50:40 +0000815 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
816 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000817 }
818
819 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000820 }
821 }
822
823 // C++ [basic.link]p6:
824 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +0000825 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000826}
Douglas Gregorf73b2822009-11-25 22:24:25 +0000827
Douglas Gregor2ada0482009-02-04 17:27:36 +0000828std::string NamedDecl::getQualifiedNameAsString() const {
Douglas Gregor78254c82012-03-27 23:34:16 +0000829 return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
Anders Carlsson2fb08242009-09-08 18:24:21 +0000830}
831
832std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000833 const DeclContext *Ctx = getDeclContext();
834
835 if (Ctx->isFunctionOrMethod())
836 return getNameAsString();
837
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000838 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000839 ContextsTy Contexts;
840
841 // Collect contexts.
842 while (Ctx && isa<NamedDecl>(Ctx)) {
843 Contexts.push_back(Ctx);
844 Ctx = Ctx->getParent();
845 };
846
847 std::string QualName;
848 llvm::raw_string_ostream OS(QualName);
849
850 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
851 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000852 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000853 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregor85673582009-05-18 17:01:57 +0000854 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
855 std::string TemplateArgsStr
856 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +0000857 TemplateArgs.data(),
858 TemplateArgs.size(),
Anders Carlsson2fb08242009-09-08 18:24:21 +0000859 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000860 OS << Spec->getName() << TemplateArgsStr;
861 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +0000862 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000863 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +0000864 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000865 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000866 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
867 if (!RD->getIdentifier())
868 OS << "<anonymous " << RD->getKindName() << '>';
869 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000870 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000871 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +0000872 const FunctionProtoType *FT = 0;
873 if (FD->hasWrittenPrototype())
874 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
875
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000876 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +0000877 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +0000878 unsigned NumParams = FD->getNumParams();
879 for (unsigned i = 0; i < NumParams; ++i) {
880 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000881 OS << ", ";
Sam Weinigb999f682009-12-28 03:19:38 +0000882 std::string Param;
883 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000884 OS << Param;
Sam Weinigb999f682009-12-28 03:19:38 +0000885 }
886
887 if (FT->isVariadic()) {
888 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000889 OS << ", ";
890 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +0000891 }
892 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000893 OS << ')';
894 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000895 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000896 }
897 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000898 }
899
John McCalla2a3f7d2010-03-16 21:48:18 +0000900 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000901 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +0000902 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000903 OS << "<anonymous>";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000904
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000905 return OS.str();
Douglas Gregor2ada0482009-02-04 17:27:36 +0000906}
907
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000908bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000909 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
910
Douglas Gregor889ceb72009-02-03 19:21:40 +0000911 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
912 // We want to keep it, unless it nominates same namespace.
913 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +0000914 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
915 ->getOriginalNamespace() ==
916 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
917 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000918 }
Mike Stump11289f42009-09-09 15:08:12 +0000919
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000920 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
921 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000922 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000923
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000924 // For function templates, the underlying function declarations are linked.
925 if (const FunctionTemplateDecl *FunctionTemplate
926 = dyn_cast<FunctionTemplateDecl>(this))
927 if (const FunctionTemplateDecl *OldFunctionTemplate
928 = dyn_cast<FunctionTemplateDecl>(OldD))
929 return FunctionTemplate->getTemplatedDecl()
930 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000931
Steve Naroffc4173fa2009-02-22 19:35:57 +0000932 // For method declarations, we keep track of redeclarations.
933 if (isa<ObjCMethodDecl>(this))
934 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000935
John McCall9f3059a2009-10-09 21:13:30 +0000936 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
937 return true;
938
John McCall3f746822009-11-17 05:59:44 +0000939 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
940 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
941 cast<UsingShadowDecl>(OldD)->getTargetDecl();
942
Douglas Gregora9d87bc2011-02-25 00:36:19 +0000943 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
944 ASTContext &Context = getASTContext();
945 return Context.getCanonicalNestedNameSpecifier(
946 cast<UsingDecl>(this)->getQualifier()) ==
947 Context.getCanonicalNestedNameSpecifier(
948 cast<UsingDecl>(OldD)->getQualifier());
949 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +0000950
Douglas Gregorb59643b2012-01-03 23:26:26 +0000951 // A typedef of an Objective-C class type can replace an Objective-C class
952 // declaration or definition, and vice versa.
953 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
954 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
955 return true;
956
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000957 // For non-function declarations, if the declarations are of the
958 // same kind then this must be a redeclaration, or semantic analysis
959 // would not have given us the new declaration.
960 return this->getKind() == OldD->getKind();
961}
962
Douglas Gregoreddf4332009-02-24 20:03:32 +0000963bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000964 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000965}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000966
Daniel Dunbar166ea9ad2012-03-08 18:20:41 +0000967NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
Anders Carlsson6915bf62009-06-26 06:29:23 +0000968 NamedDecl *ND = this;
Benjamin Kramerba0495a2012-03-08 21:00:45 +0000969 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
970 ND = UD->getTargetDecl();
971
972 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
973 return AD->getClassInterface();
974
975 return ND;
Anders Carlsson6915bf62009-06-26 06:29:23 +0000976}
977
John McCalla8ae2222010-04-06 21:38:20 +0000978bool NamedDecl::isCXXInstanceMember() const {
Douglas Gregor3f28ec22012-03-08 02:08:05 +0000979 if (!isCXXClassMember())
980 return false;
981
John McCalla8ae2222010-04-06 21:38:20 +0000982 const NamedDecl *D = this;
983 if (isa<UsingShadowDecl>(D))
984 D = cast<UsingShadowDecl>(D)->getTargetDecl();
985
Francois Pichet783dd6e2010-11-21 06:08:52 +0000986 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +0000987 return true;
988 if (isa<CXXMethodDecl>(D))
989 return cast<CXXMethodDecl>(D)->isInstance();
990 if (isa<FunctionTemplateDecl>(D))
991 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
992 ->getTemplatedDecl())->isInstance();
993 return false;
994}
995
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000996//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000997// DeclaratorDecl Implementation
998//===----------------------------------------------------------------------===//
999
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001000template <typename DeclT>
1001static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1002 if (decl->getNumTemplateParameterLists() > 0)
1003 return decl->getTemplateParameterList(0)->getTemplateLoc();
1004 else
1005 return decl->getInnerLocStart();
1006}
1007
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001008SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +00001009 TypeSourceInfo *TSI = getTypeSourceInfo();
1010 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001011 return SourceLocation();
1012}
1013
Douglas Gregor14454802011-02-25 02:25:35 +00001014void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1015 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001016 // Make sure the extended decl info is allocated.
1017 if (!hasExtInfo()) {
1018 // Save (non-extended) type source info pointer.
1019 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1020 // Allocate external info struct.
1021 DeclInfo = new (getASTContext()) ExtInfo;
1022 // Restore savedTInfo into (extended) decl info.
1023 getExtInfo()->TInfo = savedTInfo;
1024 }
1025 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001026 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001027 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001028 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001029 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001030 if (getExtInfo()->NumTemplParamLists == 0) {
1031 // Save type source info pointer.
1032 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1033 // Deallocate the extended decl info.
1034 getASTContext().Deallocate(getExtInfo());
1035 // Restore savedTInfo into (non-extended) decl info.
1036 DeclInfo = savedTInfo;
1037 }
1038 else
1039 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001040 }
1041 }
1042}
1043
Abramo Bagnara60804e12011-03-18 15:16:37 +00001044void
1045DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1046 unsigned NumTPLists,
1047 TemplateParameterList **TPLists) {
1048 assert(NumTPLists > 0);
1049 // Make sure the extended decl info is allocated.
1050 if (!hasExtInfo()) {
1051 // Save (non-extended) type source info pointer.
1052 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1053 // Allocate external info struct.
1054 DeclInfo = new (getASTContext()) ExtInfo;
1055 // Restore savedTInfo into (extended) decl info.
1056 getExtInfo()->TInfo = savedTInfo;
1057 }
1058 // Set the template parameter lists info.
1059 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1060}
1061
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001062SourceLocation DeclaratorDecl::getOuterLocStart() const {
1063 return getTemplateOrInnerLocStart(this);
1064}
1065
Abramo Bagnaraea947882011-03-08 16:41:52 +00001066namespace {
1067
1068// Helper function: returns true if QT is or contains a type
1069// having a postfix component.
1070bool typeIsPostfix(clang::QualType QT) {
1071 while (true) {
1072 const Type* T = QT.getTypePtr();
1073 switch (T->getTypeClass()) {
1074 default:
1075 return false;
1076 case Type::Pointer:
1077 QT = cast<PointerType>(T)->getPointeeType();
1078 break;
1079 case Type::BlockPointer:
1080 QT = cast<BlockPointerType>(T)->getPointeeType();
1081 break;
1082 case Type::MemberPointer:
1083 QT = cast<MemberPointerType>(T)->getPointeeType();
1084 break;
1085 case Type::LValueReference:
1086 case Type::RValueReference:
1087 QT = cast<ReferenceType>(T)->getPointeeType();
1088 break;
1089 case Type::PackExpansion:
1090 QT = cast<PackExpansionType>(T)->getPattern();
1091 break;
1092 case Type::Paren:
1093 case Type::ConstantArray:
1094 case Type::DependentSizedArray:
1095 case Type::IncompleteArray:
1096 case Type::VariableArray:
1097 case Type::FunctionProto:
1098 case Type::FunctionNoProto:
1099 return true;
1100 }
1101 }
1102}
1103
1104} // namespace
1105
1106SourceRange DeclaratorDecl::getSourceRange() const {
1107 SourceLocation RangeEnd = getLocation();
1108 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1109 if (typeIsPostfix(TInfo->getType()))
1110 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1111 }
1112 return SourceRange(getOuterLocStart(), RangeEnd);
1113}
1114
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001115void
Douglas Gregor20527e22010-06-15 17:44:38 +00001116QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1117 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001118 TemplateParameterList **TPLists) {
1119 assert((NumTPLists == 0 || TPLists != 0) &&
1120 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001121
1122 // Free previous template parameters (if any).
1123 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001124 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001125 TemplParamLists = 0;
1126 NumTemplParamLists = 0;
1127 }
1128 // Set info on matched template parameter lists (if any).
1129 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001130 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001131 NumTemplParamLists = NumTPLists;
1132 for (unsigned i = NumTPLists; i-- > 0; )
1133 TemplParamLists[i] = TPLists[i];
1134 }
1135}
1136
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001137//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001138// VarDecl Implementation
1139//===----------------------------------------------------------------------===//
1140
Sebastian Redl833ef452010-01-26 22:01:41 +00001141const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1142 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001143 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001144 case SC_Auto: return "auto";
1145 case SC_Extern: return "extern";
1146 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1147 case SC_PrivateExtern: return "__private_extern__";
1148 case SC_Register: return "register";
1149 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001150 }
1151
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001152 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001153}
1154
Abramo Bagnaradff19302011-03-08 08:55:46 +00001155VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1156 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001157 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001158 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001159 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001160}
1161
Douglas Gregor72172e92012-01-05 21:55:30 +00001162VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1163 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1164 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1165 QualType(), 0, SC_None, SC_None);
1166}
1167
Douglas Gregorbf62d642010-12-06 18:36:25 +00001168void VarDecl::setStorageClass(StorageClass SC) {
1169 assert(isLegalForVariable(SC));
1170 if (getStorageClass() != SC)
1171 ClearLinkageCache();
1172
John McCallbeaa11c2011-05-01 02:13:58 +00001173 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001174}
1175
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001176SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001177 if (getInit())
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001178 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00001179 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001180}
1181
Sebastian Redl833ef452010-01-26 22:01:41 +00001182bool VarDecl::isExternC() const {
Eli Friedman839192f2012-01-15 01:23:58 +00001183 if (getLinkage() != ExternalLinkage)
Chandler Carruth4322a282011-02-25 00:05:02 +00001184 return false;
1185
Eli Friedman839192f2012-01-15 01:23:58 +00001186 const DeclContext *DC = getDeclContext();
1187 if (DC->isRecord())
1188 return false;
Sebastian Redl833ef452010-01-26 22:01:41 +00001189
Eli Friedman839192f2012-01-15 01:23:58 +00001190 ASTContext &Context = getASTContext();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 if (!Context.getLangOpts().CPlusPlus)
Eli Friedman839192f2012-01-15 01:23:58 +00001192 return true;
1193 return DC->isExternCContext();
Sebastian Redl833ef452010-01-26 22:01:41 +00001194}
1195
1196VarDecl *VarDecl::getCanonicalDecl() {
1197 return getFirstDeclaration();
1198}
1199
Daniel Dunbar9d355812012-03-09 01:51:51 +00001200VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1201 ASTContext &C) const
1202{
Sebastian Redl35351a92010-01-31 22:27:38 +00001203 // C++ [basic.def]p2:
1204 // A declaration is a definition unless [...] it contains the 'extern'
1205 // specifier or a linkage-specification and neither an initializer [...],
1206 // it declares a static data member in a class declaration [...].
1207 // C++ [temp.expl.spec]p15:
1208 // An explicit specialization of a static data member of a template is a
1209 // definition if the declaration includes an initializer; otherwise, it is
1210 // a declaration.
1211 if (isStaticDataMember()) {
1212 if (isOutOfLine() && (hasInit() ||
1213 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1214 return Definition;
1215 else
1216 return DeclarationOnly;
1217 }
1218 // C99 6.7p5:
1219 // A definition of an identifier is a declaration for that identifier that
1220 // [...] causes storage to be reserved for that object.
1221 // Note: that applies for all non-file-scope objects.
1222 // C99 6.9.2p1:
1223 // If the declaration of an identifier for an object has file scope and an
1224 // initializer, the declaration is an external definition for the identifier
1225 if (hasInit())
1226 return Definition;
1227 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1228 if (hasExternalStorage())
1229 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001230
John McCall8e7d6562010-08-26 03:08:43 +00001231 if (getStorageClassAsWritten() == SC_Extern ||
1232 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001233 for (const VarDecl *PrevVar = getPreviousDecl();
1234 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001235 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1236 return DeclarationOnly;
1237 }
1238 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001239 // C99 6.9.2p2:
1240 // A declaration of an object that has file scope without an initializer,
1241 // and without a storage class specifier or the scs 'static', constitutes
1242 // a tentative definition.
1243 // No such thing in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001244 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
Sebastian Redl35351a92010-01-31 22:27:38 +00001245 return TentativeDefinition;
1246
1247 // What's left is (in C, block-scope) declarations without initializers or
1248 // external storage. These are definitions.
1249 return Definition;
1250}
1251
Sebastian Redl35351a92010-01-31 22:27:38 +00001252VarDecl *VarDecl::getActingDefinition() {
1253 DefinitionKind Kind = isThisDeclarationADefinition();
1254 if (Kind != TentativeDefinition)
1255 return 0;
1256
Chris Lattner48eb14d2010-06-14 18:31:46 +00001257 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001258 VarDecl *First = getFirstDeclaration();
1259 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1260 I != E; ++I) {
1261 Kind = (*I)->isThisDeclarationADefinition();
1262 if (Kind == Definition)
1263 return 0;
1264 else if (Kind == TentativeDefinition)
1265 LastTentative = *I;
1266 }
1267 return LastTentative;
1268}
1269
1270bool VarDecl::isTentativeDefinitionNow() const {
1271 DefinitionKind Kind = isThisDeclarationADefinition();
1272 if (Kind != TentativeDefinition)
1273 return false;
1274
1275 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1276 if ((*I)->isThisDeclarationADefinition() == Definition)
1277 return false;
1278 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001279 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001280}
1281
Daniel Dunbar9d355812012-03-09 01:51:51 +00001282VarDecl *VarDecl::getDefinition(ASTContext &C) {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001283 VarDecl *First = getFirstDeclaration();
1284 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1285 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001286 if ((*I)->isThisDeclarationADefinition(C) == Definition)
Sebastian Redl5ca79842010-02-01 20:16:42 +00001287 return *I;
1288 }
1289 return 0;
1290}
1291
Daniel Dunbar9d355812012-03-09 01:51:51 +00001292VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
John McCall37bb6c92010-10-29 22:22:43 +00001293 DefinitionKind Kind = DeclarationOnly;
1294
1295 const VarDecl *First = getFirstDeclaration();
1296 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001297 I != E; ++I) {
Daniel Dunbar9d355812012-03-09 01:51:51 +00001298 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
Daniel Dunbar082c62d2012-03-06 23:52:46 +00001299 if (Kind == Definition)
1300 break;
1301 }
John McCall37bb6c92010-10-29 22:22:43 +00001302
1303 return Kind;
1304}
1305
Sebastian Redl5ca79842010-02-01 20:16:42 +00001306const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001307 redecl_iterator I = redecls_begin(), E = redecls_end();
1308 while (I != E && !I->getInit())
1309 ++I;
1310
1311 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001312 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001313 return I->getInit();
1314 }
1315 return 0;
1316}
1317
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001318bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001319 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001320 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001321
1322 if (!isStaticDataMember())
1323 return false;
1324
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001325 // If this static data member was instantiated from a static data member of
1326 // a class template, check whether that static data member was defined
1327 // out-of-line.
1328 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1329 return VD->isOutOfLine();
1330
1331 return false;
1332}
1333
Douglas Gregor1d957a32009-10-27 18:42:08 +00001334VarDecl *VarDecl::getOutOfLineDefinition() {
1335 if (!isStaticDataMember())
1336 return 0;
1337
1338 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1339 RD != RDEnd; ++RD) {
1340 if (RD->getLexicalDeclContext()->isFileContext())
1341 return *RD;
1342 }
1343
1344 return 0;
1345}
1346
Douglas Gregord5058122010-02-11 01:19:42 +00001347void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001348 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1349 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001350 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001351 }
1352
1353 Init = I;
1354}
1355
Daniel Dunbar9d355812012-03-09 01:51:51 +00001356bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001357 const LangOptions &Lang = C.getLangOpts();
Richard Smith242ad892011-12-21 02:55:12 +00001358
Richard Smith35ecb362012-03-02 04:14:40 +00001359 if (!Lang.CPlusPlus)
1360 return false;
1361
1362 // In C++11, any variable of reference type can be used in a constant
1363 // expression if it is initialized by a constant expression.
1364 if (Lang.CPlusPlus0x && getType()->isReferenceType())
1365 return true;
1366
1367 // Only const objects can be used in constant expressions in C++. C++98 does
Richard Smith242ad892011-12-21 02:55:12 +00001368 // not require the variable to be non-volatile, but we consider this to be a
1369 // defect.
Richard Smith35ecb362012-03-02 04:14:40 +00001370 if (!getType().isConstQualified() || getType().isVolatileQualified())
Richard Smith242ad892011-12-21 02:55:12 +00001371 return false;
1372
1373 // In C++, const, non-volatile variables of integral or enumeration types
1374 // can be used in constant expressions.
1375 if (getType()->isIntegralOrEnumerationType())
1376 return true;
1377
Richard Smith35ecb362012-03-02 04:14:40 +00001378 // Additionally, in C++11, non-volatile constexpr variables can be used in
1379 // constant expressions.
1380 return Lang.CPlusPlus0x && isConstexpr();
Richard Smith242ad892011-12-21 02:55:12 +00001381}
1382
Richard Smithd0b4dd62011-12-19 06:19:21 +00001383/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1384/// form, which contains extra information on the evaluated value of the
1385/// initializer.
1386EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1387 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1388 if (!Eval) {
1389 Stmt *S = Init.get<Stmt *>();
1390 Eval = new (getASTContext()) EvaluatedStmt;
1391 Eval->Value = S;
1392 Init = Eval;
1393 }
1394 return Eval;
1395}
1396
Richard Smithdafff942012-01-14 04:30:29 +00001397APValue *VarDecl::evaluateValue() const {
1398 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1399 return evaluateValue(Notes);
1400}
1401
1402APValue *VarDecl::evaluateValue(
1403 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001404 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1405
1406 // We only produce notes indicating why an initializer is non-constant the
1407 // first time it is evaluated. FIXME: The notes won't always be emitted the
1408 // first time we try evaluation, so might not be produced at all.
1409 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001410 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001411
1412 const Expr *Init = cast<Expr>(Eval->Value);
1413 assert(!Init->isValueDependent());
1414
1415 if (Eval->IsEvaluating) {
1416 // FIXME: Produce a diagnostic for self-initialization.
1417 Eval->CheckedICE = true;
1418 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001419 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001420 }
1421
1422 Eval->IsEvaluating = true;
1423
1424 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1425 this, Notes);
1426
1427 // Ensure the result is an uninitialized APValue if evaluation fails.
1428 if (!Result)
1429 Eval->Evaluated = APValue();
1430
1431 Eval->IsEvaluating = false;
1432 Eval->WasEvaluated = true;
1433
1434 // In C++11, we have determined whether the initializer was a constant
1435 // expression as a side-effect.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001436 if (getASTContext().getLangOpts().CPlusPlus0x && !Eval->CheckedICE) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001437 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001438 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001439 }
1440
Richard Smithdafff942012-01-14 04:30:29 +00001441 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001442}
1443
1444bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001445 // Initializers of weak variables are never ICEs.
1446 if (isWeak())
1447 return false;
1448
Richard Smithd0b4dd62011-12-19 06:19:21 +00001449 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1450 if (Eval->CheckedICE)
1451 // We have already checked whether this subexpression is an
1452 // integral constant expression.
1453 return Eval->IsICE;
1454
1455 const Expr *Init = cast<Expr>(Eval->Value);
1456 assert(!Init->isValueDependent());
1457
1458 // In C++11, evaluate the initializer to check whether it's a constant
1459 // expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001460 if (getASTContext().getLangOpts().CPlusPlus0x) {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001461 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1462 evaluateValue(Notes);
1463 return Eval->IsICE;
1464 }
1465
1466 // It's an ICE whether or not the definition we found is
1467 // out-of-line. See DR 721 and the discussion in Clang PR
1468 // 6206 for details.
1469
1470 if (Eval->CheckingICE)
1471 return false;
1472 Eval->CheckingICE = true;
1473
1474 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1475 Eval->CheckingICE = false;
1476 Eval->CheckedICE = true;
1477 return Eval->IsICE;
1478}
1479
Douglas Gregorfe314812011-06-21 17:03:29 +00001480bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001481 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001482
1483 const Expr *E = getInit();
1484 if (!E)
1485 return false;
1486
1487 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1488 E = Cleanups->getSubExpr();
1489
1490 return isa<MaterializeTemporaryExpr>(E);
1491}
1492
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001493VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001494 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001495 return cast<VarDecl>(MSI->getInstantiatedFrom());
1496
1497 return 0;
1498}
1499
Douglas Gregor3c74d412009-10-14 20:14:33 +00001500TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001501 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001502 return MSI->getTemplateSpecializationKind();
1503
1504 return TSK_Undeclared;
1505}
1506
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001507MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001508 return getASTContext().getInstantiatedFromStaticDataMember(this);
1509}
1510
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001511void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1512 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001513 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001514 assert(MSI && "Not an instantiated static data member?");
1515 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001516 if (TSK != TSK_ExplicitSpecialization &&
1517 PointOfInstantiation.isValid() &&
1518 MSI->getPointOfInstantiation().isInvalid())
1519 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001520}
1521
Sebastian Redl833ef452010-01-26 22:01:41 +00001522//===----------------------------------------------------------------------===//
1523// ParmVarDecl Implementation
1524//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001525
Sebastian Redl833ef452010-01-26 22:01:41 +00001526ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001527 SourceLocation StartLoc,
1528 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001529 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001530 StorageClass S, StorageClass SCAsWritten,
1531 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001532 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001533 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001534}
1535
Douglas Gregor72172e92012-01-05 21:55:30 +00001536ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1537 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1538 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1539 0, QualType(), 0, SC_None, SC_None, 0);
1540}
1541
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001542SourceRange ParmVarDecl::getSourceRange() const {
1543 if (!hasInheritedDefaultArg()) {
1544 SourceRange ArgRange = getDefaultArgRange();
1545 if (ArgRange.isValid())
1546 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1547 }
1548
1549 return DeclaratorDecl::getSourceRange();
1550}
1551
Sebastian Redl833ef452010-01-26 22:01:41 +00001552Expr *ParmVarDecl::getDefaultArg() {
1553 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1554 assert(!hasUninstantiatedDefaultArg() &&
1555 "Default argument is not yet instantiated!");
1556
1557 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001558 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001559 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001560
Sebastian Redl833ef452010-01-26 22:01:41 +00001561 return Arg;
1562}
1563
Sebastian Redl833ef452010-01-26 22:01:41 +00001564SourceRange ParmVarDecl::getDefaultArgRange() const {
1565 if (const Expr *E = getInit())
1566 return E->getSourceRange();
1567
1568 if (hasUninstantiatedDefaultArg())
1569 return getUninstantiatedDefaultArg()->getSourceRange();
1570
1571 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001572}
1573
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001574bool ParmVarDecl::isParameterPack() const {
1575 return isa<PackExpansionType>(getType());
1576}
1577
Ted Kremenek540017e2011-10-06 05:00:56 +00001578void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1579 getASTContext().setParameterIndex(this, parameterIndex);
1580 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1581}
1582
1583unsigned ParmVarDecl::getParameterIndexLarge() const {
1584 return getASTContext().getParameterIndex(this);
1585}
1586
Nuno Lopes394ec982008-12-17 23:39:55 +00001587//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001588// FunctionDecl Implementation
1589//===----------------------------------------------------------------------===//
1590
Douglas Gregorb11aad82011-02-19 18:51:44 +00001591void FunctionDecl::getNameForDiagnostic(std::string &S,
1592 const PrintingPolicy &Policy,
1593 bool Qualified) const {
1594 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1595 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1596 if (TemplateArgs)
1597 S += TemplateSpecializationType::PrintTemplateArgumentList(
1598 TemplateArgs->data(),
1599 TemplateArgs->size(),
1600 Policy);
1601
1602}
1603
Ted Kremenek186a0742010-04-29 16:49:01 +00001604bool FunctionDecl::isVariadic() const {
1605 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1606 return FT->isVariadic();
1607 return false;
1608}
1609
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001610bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1611 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001612 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001613 Definition = *I;
1614 return true;
1615 }
1616 }
1617
1618 return false;
1619}
1620
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001621bool FunctionDecl::hasTrivialBody() const
1622{
1623 Stmt *S = getBody();
1624 if (!S) {
1625 // Since we don't have a body for this function, we don't know if it's
1626 // trivial or not.
1627 return false;
1628 }
1629
1630 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1631 return true;
1632 return false;
1633}
1634
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001635bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1636 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001637 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001638 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1639 return true;
1640 }
1641 }
1642
1643 return false;
1644}
1645
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001646Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00001647 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1648 if (I->Body) {
1649 Definition = *I;
1650 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00001651 } else if (I->IsLateTemplateParsed) {
1652 Definition = *I;
1653 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00001654 }
1655 }
1656
1657 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001658}
1659
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001660void FunctionDecl::setBody(Stmt *B) {
1661 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00001662 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001663 EndRangeLoc = B->getLocEnd();
1664}
1665
Douglas Gregor7d9120c2010-09-28 21:55:22 +00001666void FunctionDecl::setPure(bool P) {
1667 IsPure = P;
1668 if (P)
1669 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1670 Parent->markedVirtualFunctionPure();
1671}
1672
Douglas Gregor16618f22009-09-12 00:17:51 +00001673bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00001674 const TranslationUnitDecl *tunit =
1675 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1676 return tunit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001677 !tunit->getASTContext().getLangOpts().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00001678 getIdentifier() &&
1679 getIdentifier()->isStr("main");
1680}
1681
1682bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1683 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1684 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1685 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1686 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1687 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1688
1689 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1690 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1691
1692 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1693 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1694
1695 ASTContext &Context =
1696 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1697 ->getASTContext();
1698
1699 // The result type and first argument type are constant across all
1700 // these operators. The second argument must be exactly void*.
1701 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001702}
1703
Douglas Gregor16618f22009-09-12 00:17:51 +00001704bool FunctionDecl::isExternC() const {
Eli Friedman839192f2012-01-15 01:23:58 +00001705 if (getLinkage() != ExternalLinkage)
1706 return false;
1707
1708 if (getAttr<OverloadableAttr>())
1709 return false;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001710
Chandler Carruth4322a282011-02-25 00:05:02 +00001711 const DeclContext *DC = getDeclContext();
1712 if (DC->isRecord())
1713 return false;
1714
Eli Friedman839192f2012-01-15 01:23:58 +00001715 ASTContext &Context = getASTContext();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001716 if (!Context.getLangOpts().CPlusPlus)
Eli Friedman839192f2012-01-15 01:23:58 +00001717 return true;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001718
Eli Friedman839192f2012-01-15 01:23:58 +00001719 return isMain() || DC->isExternCContext();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001720}
1721
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001722bool FunctionDecl::isGlobal() const {
1723 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1724 return Method->isStatic();
1725
John McCall8e7d6562010-08-26 03:08:43 +00001726 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001727 return false;
1728
Mike Stump11289f42009-09-09 15:08:12 +00001729 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001730 DC->isNamespace();
1731 DC = DC->getParent()) {
1732 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1733 if (!Namespace->getDeclName())
1734 return false;
1735 break;
1736 }
1737 }
1738
1739 return true;
1740}
1741
Sebastian Redl833ef452010-01-26 22:01:41 +00001742void
1743FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1744 redeclarable_base::setPreviousDeclaration(PrevDecl);
1745
1746 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1747 FunctionTemplateDecl *PrevFunTmpl
1748 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1749 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1750 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1751 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00001752
Axel Naumannfbc7b982011-11-08 18:21:06 +00001753 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00001754 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00001755}
1756
1757const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1758 return getFirstDeclaration();
1759}
1760
1761FunctionDecl *FunctionDecl::getCanonicalDecl() {
1762 return getFirstDeclaration();
1763}
1764
Douglas Gregorbf62d642010-12-06 18:36:25 +00001765void FunctionDecl::setStorageClass(StorageClass SC) {
1766 assert(isLegalForFunction(SC));
1767 if (getStorageClass() != SC)
1768 ClearLinkageCache();
1769
1770 SClass = SC;
1771}
1772
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001773/// \brief Returns a value indicating whether this function
1774/// corresponds to a builtin function.
1775///
1776/// The function corresponds to a built-in function if it is
1777/// declared at translation scope or within an extern "C" block and
1778/// its name matches with the name of a builtin. The returned value
1779/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00001780/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001781/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001782unsigned FunctionDecl::getBuiltinID() const {
Daniel Dunbar304314d2012-03-06 23:52:37 +00001783 if (!getIdentifier())
Douglas Gregore711f702009-02-14 18:57:46 +00001784 return 0;
1785
1786 unsigned BuiltinID = getIdentifier()->getBuiltinID();
Daniel Dunbar304314d2012-03-06 23:52:37 +00001787 if (!BuiltinID)
1788 return 0;
1789
1790 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00001791 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1792 return BuiltinID;
1793
1794 // This function has the name of a known C library
1795 // function. Determine whether it actually refers to the C library
1796 // function or whether it just has the same name.
1797
Douglas Gregora908e7f2009-02-17 03:23:10 +00001798 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00001799 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00001800 return 0;
1801
Douglas Gregore711f702009-02-14 18:57:46 +00001802 // If this function is at translation-unit scope and we're not in
1803 // C++, it refers to the C library function.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001804 if (!Context.getLangOpts().CPlusPlus &&
Douglas Gregore711f702009-02-14 18:57:46 +00001805 getDeclContext()->isTranslationUnit())
1806 return BuiltinID;
1807
1808 // If the function is in an extern "C" linkage specification and is
1809 // not marked "overloadable", it's the real function.
1810 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001811 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00001812 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001813 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00001814 return BuiltinID;
1815
1816 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001817 return 0;
1818}
1819
1820
Chris Lattner47c0d002009-04-25 06:03:53 +00001821/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00001822/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00001823/// after it has been created.
1824unsigned FunctionDecl::getNumParams() const {
John McCall9dd450b2009-09-21 23:43:11 +00001825 const FunctionType *FT = getType()->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001826 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00001827 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001828 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00001829
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001830}
1831
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00001832void FunctionDecl::setParams(ASTContext &C,
David Blaikie9c70e042011-09-21 18:16:56 +00001833 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001834 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00001835 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00001836
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001837 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00001838 if (!NewParamInfo.empty()) {
1839 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1840 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001841 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001842}
Chris Lattner41943152007-01-25 04:52:46 +00001843
James Molloy6f8780b2012-02-29 10:24:19 +00001844void FunctionDecl::setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls) {
1845 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
1846
1847 if (!NewDecls.empty()) {
1848 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
1849 std::copy(NewDecls.begin(), NewDecls.end(), A);
1850 DeclsInPrototypeScope = llvm::ArrayRef<NamedDecl*>(A, NewDecls.size());
1851 }
1852}
1853
Chris Lattner58258242008-04-10 02:22:51 +00001854/// getMinRequiredArguments - Returns the minimum number of arguments
1855/// needed to call this function. This may be fewer than the number of
1856/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00001857/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00001858unsigned FunctionDecl::getMinRequiredArguments() const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001859 if (!getASTContext().getLangOpts().CPlusPlus)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001860 return getNumParams();
1861
Douglas Gregor7825bf32011-01-06 22:09:01 +00001862 unsigned NumRequiredArgs = getNumParams();
1863
1864 // If the last parameter is a parameter pack, we don't need an argument for
1865 // it.
1866 if (NumRequiredArgs > 0 &&
1867 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1868 --NumRequiredArgs;
1869
1870 // If this parameter has a default argument, we don't need an argument for
1871 // it.
1872 while (NumRequiredArgs > 0 &&
1873 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00001874 --NumRequiredArgs;
1875
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001876 // We might have parameter packs before the end. These can't be deduced,
1877 // but they can still handle multiple arguments.
1878 unsigned ArgIdx = NumRequiredArgs;
1879 while (ArgIdx > 0) {
1880 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1881 NumRequiredArgs = ArgIdx;
1882
1883 --ArgIdx;
1884 }
1885
Chris Lattner58258242008-04-10 02:22:51 +00001886 return NumRequiredArgs;
1887}
1888
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001889bool FunctionDecl::isInlined() const {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001890 if (IsInline)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001891 return true;
Anders Carlssoncfb65d72009-12-04 22:35:50 +00001892
1893 if (isa<CXXMethodDecl>(this)) {
1894 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1895 return true;
1896 }
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001897
1898 switch (getTemplateSpecializationKind()) {
1899 case TSK_Undeclared:
1900 case TSK_ExplicitSpecialization:
1901 return false;
1902
1903 case TSK_ImplicitInstantiation:
1904 case TSK_ExplicitInstantiationDeclaration:
1905 case TSK_ExplicitInstantiationDefinition:
1906 // Handle below.
1907 break;
1908 }
1909
1910 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001911 bool HasPattern = false;
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001912 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001913 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001914
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001915 if (HasPattern && PatternDecl)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001916 return PatternDecl->isInlined();
1917
1918 return false;
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001919}
1920
Eli Friedman1b125c32012-02-07 03:50:18 +00001921static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
1922 // Only consider file-scope declarations in this test.
1923 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1924 return false;
1925
1926 // Only consider explicit declarations; the presence of a builtin for a
1927 // libcall shouldn't affect whether a definition is externally visible.
1928 if (Redecl->isImplicit())
1929 return false;
1930
1931 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1932 return true; // Not an inline definition
1933
1934 return false;
1935}
1936
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001937/// \brief For a function declaration in C or C++, determine whether this
1938/// declaration causes the definition to be externally visible.
1939///
Eli Friedman1b125c32012-02-07 03:50:18 +00001940/// Specifically, this determines if adding the current declaration to the set
1941/// of redeclarations of the given functions causes
1942/// isInlineDefinitionExternallyVisible to change from false to true.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001943bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1944 assert(!doesThisDeclarationHaveABody() &&
1945 "Must have a declaration without a body.");
1946
1947 ASTContext &Context = getASTContext();
1948
David Blaikiebbafb8a2012-03-11 07:00:24 +00001949 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00001950 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
1951 // an externally visible definition.
1952 //
1953 // FIXME: What happens if gnu_inline gets added on after the first
1954 // declaration?
1955 if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
1956 return false;
1957
1958 const FunctionDecl *Prev = this;
1959 bool FoundBody = false;
1960 while ((Prev = Prev->getPreviousDecl())) {
1961 FoundBody |= Prev->Body;
1962
1963 if (Prev->Body) {
1964 // If it's not the case that both 'inline' and 'extern' are
1965 // specified on the definition, then it is always externally visible.
1966 if (!Prev->isInlineSpecified() ||
1967 Prev->getStorageClassAsWritten() != SC_Extern)
1968 return false;
1969 } else if (Prev->isInlineSpecified() &&
1970 Prev->getStorageClassAsWritten() != SC_Extern) {
1971 return false;
1972 }
1973 }
1974 return FoundBody;
1975 }
1976
David Blaikiebbafb8a2012-03-11 07:00:24 +00001977 if (Context.getLangOpts().CPlusPlus)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001978 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00001979
1980 // C99 6.7.4p6:
1981 // [...] If all of the file scope declarations for a function in a
1982 // translation unit include the inline function specifier without extern,
1983 // then the definition in that translation unit is an inline definition.
1984 if (isInlineSpecified() && getStorageClass() != SC_Extern)
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001985 return false;
Eli Friedman1b125c32012-02-07 03:50:18 +00001986 const FunctionDecl *Prev = this;
1987 bool FoundBody = false;
1988 while ((Prev = Prev->getPreviousDecl())) {
1989 FoundBody |= Prev->Body;
1990 if (RedeclForcesDefC99(Prev))
1991 return false;
1992 }
1993 return FoundBody;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001994}
1995
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001996/// \brief For an inline function definition in C or C++, determine whether the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001997/// definition will be externally visible.
1998///
1999/// Inline function definitions are always available for inlining optimizations.
2000/// However, depending on the language dialect, declaration specifiers, and
2001/// attributes, the definition of an inline function may or may not be
2002/// "externally" visible to other translation units in the program.
2003///
2004/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00002005/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00002006/// inline definition becomes externally visible (C99 6.7.4p6).
2007///
2008/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2009/// definition, we use the GNU semantics for inline, which are nearly the
2010/// opposite of C99 semantics. In particular, "inline" by itself will create
2011/// an externally visible symbol, but "extern inline" will not create an
2012/// externally visible symbol.
2013bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002014 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002015 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00002016 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00002017
David Blaikiebbafb8a2012-03-11 07:00:24 +00002018 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002019 // Note: If you change the logic here, please change
2020 // doesDeclarationForceExternallyVisibleDefinition as well.
2021 //
Douglas Gregorff76cb92010-12-09 16:59:22 +00002022 // If it's not the case that both 'inline' and 'extern' are
2023 // specified on the definition, then this inline definition is
2024 // externally visible.
2025 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2026 return true;
2027
2028 // If any declaration is 'inline' but not 'extern', then this definition
2029 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00002030 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2031 Redecl != RedeclEnd;
2032 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00002033 if (Redecl->isInlineSpecified() &&
2034 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00002035 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00002036 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00002037
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002038 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002039 }
Eli Friedman1b125c32012-02-07 03:50:18 +00002040
Douglas Gregor299d76e2009-09-13 07:46:26 +00002041 // C99 6.7.4p6:
2042 // [...] If all of the file scope declarations for a function in a
2043 // translation unit include the inline function specifier without extern,
2044 // then the definition in that translation unit is an inline definition.
2045 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2046 Redecl != RedeclEnd;
2047 ++Redecl) {
Eli Friedman1b125c32012-02-07 03:50:18 +00002048 if (RedeclForcesDefC99(*Redecl))
2049 return true;
Douglas Gregor299d76e2009-09-13 07:46:26 +00002050 }
2051
2052 // C99 6.7.4p6:
2053 // An inline definition does not provide an external definition for the
2054 // function, and does not forbid an external definition in another
2055 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00002056 return false;
2057}
2058
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002059/// getOverloadedOperator - Which C++ overloaded operator this
2060/// function represents, if any.
2061OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00002062 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2063 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00002064 else
2065 return OO_None;
2066}
2067
Alexis Huntc88db062010-01-13 09:01:02 +00002068/// getLiteralIdentifier - The literal suffix identifier this function
2069/// represents, if any.
2070const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2071 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2072 return getDeclName().getCXXLiteralIdentifier();
2073 else
2074 return 0;
2075}
2076
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002077FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2078 if (TemplateOrSpecialization.isNull())
2079 return TK_NonTemplate;
2080 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2081 return TK_FunctionTemplate;
2082 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2083 return TK_MemberSpecialization;
2084 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2085 return TK_FunctionTemplateSpecialization;
2086 if (TemplateOrSpecialization.is
2087 <DependentFunctionTemplateSpecializationInfo*>())
2088 return TK_DependentFunctionTemplateSpecialization;
2089
David Blaikie83d382b2011-09-23 05:06:16 +00002090 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002091}
2092
Douglas Gregord801b062009-10-07 23:56:10 +00002093FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002094 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002095 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2096
2097 return 0;
2098}
2099
Douglas Gregor06db9f52009-10-12 20:18:28 +00002100MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2101 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2102}
2103
Douglas Gregord801b062009-10-07 23:56:10 +00002104void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002105FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2106 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002107 TemplateSpecializationKind TSK) {
2108 assert(TemplateOrSpecialization.isNull() &&
2109 "Member function is already a specialization");
2110 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002111 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002112 TemplateOrSpecialization = Info;
2113}
2114
Douglas Gregorafca3b42009-10-27 20:53:28 +00002115bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002116 // If the function is invalid, it can't be implicitly instantiated.
2117 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002118 return false;
2119
2120 switch (getTemplateSpecializationKind()) {
2121 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002122 case TSK_ExplicitInstantiationDefinition:
2123 return false;
2124
2125 case TSK_ImplicitInstantiation:
2126 return true;
2127
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002128 // It is possible to instantiate TSK_ExplicitSpecialization kind
2129 // if the FunctionDecl has a class scope specialization pattern.
2130 case TSK_ExplicitSpecialization:
2131 return getClassScopeSpecializationPattern() != 0;
2132
Douglas Gregorafca3b42009-10-27 20:53:28 +00002133 case TSK_ExplicitInstantiationDeclaration:
2134 // Handled below.
2135 break;
2136 }
2137
2138 // Find the actual template from which we will instantiate.
2139 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002140 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002141 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002142 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002143
2144 // C++0x [temp.explicit]p9:
2145 // Except for inline functions, other explicit instantiation declarations
2146 // have the effect of suppressing the implicit instantiation of the entity
2147 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002148 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002149 return true;
2150
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002151 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002152}
2153
2154bool FunctionDecl::isTemplateInstantiation() const {
2155 switch (getTemplateSpecializationKind()) {
2156 case TSK_Undeclared:
2157 case TSK_ExplicitSpecialization:
2158 return false;
2159 case TSK_ImplicitInstantiation:
2160 case TSK_ExplicitInstantiationDeclaration:
2161 case TSK_ExplicitInstantiationDefinition:
2162 return true;
2163 }
2164 llvm_unreachable("All TSK values handled.");
2165}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002166
2167FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002168 // Handle class scope explicit specialization special case.
2169 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2170 return getClassScopeSpecializationPattern();
2171
Douglas Gregorafca3b42009-10-27 20:53:28 +00002172 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2173 while (Primary->getInstantiatedFromMemberTemplate()) {
2174 // If we have hit a point where the user provided a specialization of
2175 // this template, we're done looking.
2176 if (Primary->isMemberSpecialization())
2177 break;
2178
2179 Primary = Primary->getInstantiatedFromMemberTemplate();
2180 }
2181
2182 return Primary->getTemplatedDecl();
2183 }
2184
2185 return getInstantiatedFromMemberFunction();
2186}
2187
Douglas Gregor70d83e22009-06-29 17:30:29 +00002188FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002189 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002190 = TemplateOrSpecialization
2191 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002192 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002193 }
2194 return 0;
2195}
2196
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002197FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2198 return getASTContext().getClassScopeSpecializationPattern(this);
2199}
2200
Douglas Gregor70d83e22009-06-29 17:30:29 +00002201const TemplateArgumentList *
2202FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002203 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002204 = TemplateOrSpecialization
2205 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002206 return Info->TemplateArguments;
2207 }
2208 return 0;
2209}
2210
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002211const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002212FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2213 if (FunctionTemplateSpecializationInfo *Info
2214 = TemplateOrSpecialization
2215 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2216 return Info->TemplateArgumentsAsWritten;
2217 }
2218 return 0;
2219}
2220
Mike Stump11289f42009-09-09 15:08:12 +00002221void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002222FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2223 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002224 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002225 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002226 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002227 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2228 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002229 assert(TSK != TSK_Undeclared &&
2230 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002231 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002232 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002233 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002234 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2235 TemplateArgs,
2236 TemplateArgsAsWritten,
2237 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002238 TemplateOrSpecialization = Info;
Douglas Gregorce9978f2012-03-28 14:34:23 +00002239 Template->addSpecialization(Info, InsertPos);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002240}
2241
John McCallb9c78482010-04-08 09:05:18 +00002242void
2243FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2244 const UnresolvedSetImpl &Templates,
2245 const TemplateArgumentListInfo &TemplateArgs) {
2246 assert(TemplateOrSpecialization.isNull());
2247 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2248 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002249 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002250 void *Buffer = Context.Allocate(Size);
2251 DependentFunctionTemplateSpecializationInfo *Info =
2252 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2253 TemplateArgs);
2254 TemplateOrSpecialization = Info;
2255}
2256
2257DependentFunctionTemplateSpecializationInfo::
2258DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2259 const TemplateArgumentListInfo &TArgs)
2260 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2261
2262 d.NumTemplates = Ts.size();
2263 d.NumArgs = TArgs.size();
2264
2265 FunctionTemplateDecl **TsArray =
2266 const_cast<FunctionTemplateDecl**>(getTemplates());
2267 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2268 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2269
2270 TemplateArgumentLoc *ArgsArray =
2271 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2272 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2273 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2274}
2275
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002276TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002277 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002278 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002279 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002280 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002281 if (FTSInfo)
2282 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002283
Douglas Gregord801b062009-10-07 23:56:10 +00002284 MemberSpecializationInfo *MSInfo
2285 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2286 if (MSInfo)
2287 return MSInfo->getTemplateSpecializationKind();
2288
2289 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002290}
2291
Mike Stump11289f42009-09-09 15:08:12 +00002292void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002293FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2294 SourceLocation PointOfInstantiation) {
2295 if (FunctionTemplateSpecializationInfo *FTSInfo
2296 = TemplateOrSpecialization.dyn_cast<
2297 FunctionTemplateSpecializationInfo*>()) {
2298 FTSInfo->setTemplateSpecializationKind(TSK);
2299 if (TSK != TSK_ExplicitSpecialization &&
2300 PointOfInstantiation.isValid() &&
2301 FTSInfo->getPointOfInstantiation().isInvalid())
2302 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2303 } else if (MemberSpecializationInfo *MSInfo
2304 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2305 MSInfo->setTemplateSpecializationKind(TSK);
2306 if (TSK != TSK_ExplicitSpecialization &&
2307 PointOfInstantiation.isValid() &&
2308 MSInfo->getPointOfInstantiation().isInvalid())
2309 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2310 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002311 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002312}
2313
2314SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002315 if (FunctionTemplateSpecializationInfo *FTSInfo
2316 = TemplateOrSpecialization.dyn_cast<
2317 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002318 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002319 else if (MemberSpecializationInfo *MSInfo
2320 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002321 return MSInfo->getPointOfInstantiation();
2322
2323 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002324}
2325
Douglas Gregor6411b922009-09-11 20:15:17 +00002326bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002327 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002328 return true;
2329
2330 // If this function was instantiated from a member function of a
2331 // class template, check whether that member function was defined out-of-line.
2332 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2333 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002334 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002335 return Definition->isOutOfLine();
2336 }
2337
2338 // If this function was instantiated from a function template,
2339 // check whether that function template was defined out-of-line.
2340 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2341 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002342 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002343 return Definition->isOutOfLine();
2344 }
2345
2346 return false;
2347}
2348
Abramo Bagnaraea947882011-03-08 16:41:52 +00002349SourceRange FunctionDecl::getSourceRange() const {
2350 return SourceRange(getOuterLocStart(), EndRangeLoc);
2351}
2352
Anna Zaks28db7ce2012-01-18 02:45:01 +00002353unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002354 IdentifierInfo *FnInfo = getIdentifier();
2355
2356 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002357 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002358
2359 // Builtin handling.
2360 switch (getBuiltinID()) {
2361 case Builtin::BI__builtin_memset:
2362 case Builtin::BI__builtin___memset_chk:
2363 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002364 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002365
2366 case Builtin::BI__builtin_memcpy:
2367 case Builtin::BI__builtin___memcpy_chk:
2368 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002369 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002370
2371 case Builtin::BI__builtin_memmove:
2372 case Builtin::BI__builtin___memmove_chk:
2373 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002374 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002375
2376 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002377 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002378 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002379 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002380
2381 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002382 case Builtin::BImemcmp:
2383 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002384
2385 case Builtin::BI__builtin_strncpy:
2386 case Builtin::BI__builtin___strncpy_chk:
2387 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002388 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002389
2390 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002391 case Builtin::BIstrncmp:
2392 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002393
2394 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002395 case Builtin::BIstrncasecmp:
2396 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002397
2398 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002399 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002400 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002401 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002402
2403 case Builtin::BI__builtin_strndup:
2404 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002405 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002406
Anna Zaks314cd092012-02-01 19:08:57 +00002407 case Builtin::BI__builtin_strlen:
2408 case Builtin::BIstrlen:
2409 return Builtin::BIstrlen;
2410
Anna Zaks201d4892012-01-13 21:52:01 +00002411 default:
Eli Friedman839192f2012-01-15 01:23:58 +00002412 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002413 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002414 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002415 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002416 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002417 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002418 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002419 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002420 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002421 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002422 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002423 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002424 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002425 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002426 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002427 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002428 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002429 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002430 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002431 else if (FnInfo->isStr("strlen"))
2432 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002433 }
2434 break;
2435 }
Anna Zaks22122702012-01-17 00:37:07 +00002436 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002437}
2438
Chris Lattner59a25942008-03-31 00:36:02 +00002439//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002440// FieldDecl Implementation
2441//===----------------------------------------------------------------------===//
2442
Jay Foad39c79802011-01-12 09:06:06 +00002443FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002444 SourceLocation StartLoc, SourceLocation IdLoc,
2445 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002446 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2447 bool HasInit) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002448 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002449 BW, Mutable, HasInit);
Sebastian Redl833ef452010-01-26 22:01:41 +00002450}
2451
Douglas Gregor72172e92012-01-05 21:55:30 +00002452FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2453 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2454 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2455 0, QualType(), 0, 0, false, false);
2456}
2457
Sebastian Redl833ef452010-01-26 22:01:41 +00002458bool FieldDecl::isAnonymousStructOrUnion() const {
2459 if (!isImplicit() || getDeclName())
2460 return false;
2461
2462 if (const RecordType *Record = getType()->getAs<RecordType>())
2463 return Record->getDecl()->isAnonymousStructOrUnion();
2464
2465 return false;
2466}
2467
Richard Smithcaf33902011-10-10 18:28:20 +00002468unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2469 assert(isBitField() && "not a bitfield");
2470 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2471 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2472}
2473
John McCall4e819612011-01-20 07:57:12 +00002474unsigned FieldDecl::getFieldIndex() const {
2475 if (CachedFieldIndex) return CachedFieldIndex - 1;
2476
Richard Smithd62306a2011-11-10 06:34:14 +00002477 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002478 const RecordDecl *RD = getParent();
2479 const FieldDecl *LastFD = 0;
2480 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
Richard Smithd62306a2011-11-10 06:34:14 +00002481
2482 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2483 I != E; ++I, ++Index) {
2484 (*I)->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002485
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002486 if (IsMsStruct) {
2487 // Zero-length bitfields following non-bitfield members are ignored.
Richard Smithd62306a2011-11-10 06:34:14 +00002488 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
2489 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002490 continue;
2491 }
Richard Smithd62306a2011-11-10 06:34:14 +00002492 LastFD = (*I);
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002493 }
John McCall4e819612011-01-20 07:57:12 +00002494 }
2495
Richard Smithd62306a2011-11-10 06:34:14 +00002496 assert(CachedFieldIndex && "failed to find field in parent");
2497 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002498}
2499
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002500SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002501 if (const Expr *E = InitializerOrBitWidth.getPointer())
2502 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002503 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002504}
2505
Richard Smith938f40b2011-06-11 17:19:42 +00002506void FieldDecl::setInClassInitializer(Expr *Init) {
2507 assert(!InitializerOrBitWidth.getPointer() &&
2508 "bit width or initializer already set");
2509 InitializerOrBitWidth.setPointer(Init);
2510 InitializerOrBitWidth.setInt(0);
2511}
2512
Sebastian Redl833ef452010-01-26 22:01:41 +00002513//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002514// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002515//===----------------------------------------------------------------------===//
2516
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002517SourceLocation TagDecl::getOuterLocStart() const {
2518 return getTemplateOrInnerLocStart(this);
2519}
2520
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002521SourceRange TagDecl::getSourceRange() const {
2522 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002523 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002524}
2525
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002526TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002527 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002528}
2529
Richard Smithdda56e42011-04-15 14:24:37 +00002530void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2531 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002532 if (TypeForDecl)
John McCall424cec92011-01-19 06:33:43 +00002533 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002534 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002535}
2536
Douglas Gregordee1be82009-01-17 00:42:38 +00002537void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002538 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002539
2540 if (isa<CXXRecordDecl>(this)) {
2541 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2542 struct CXXRecordDecl::DefinitionData *Data =
2543 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002544 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2545 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002546 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002547}
2548
2549void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002550 assert((!isa<CXXRecordDecl>(this) ||
2551 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2552 "definition completed but not started");
2553
John McCallf937c022011-10-07 06:10:15 +00002554 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002555 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002556
2557 if (ASTMutationListener *L = getASTMutationListener())
2558 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002559}
2560
John McCallf937c022011-10-07 06:10:15 +00002561TagDecl *TagDecl::getDefinition() const {
2562 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002563 return const_cast<TagDecl *>(this);
Andrew Trickba266ee2010-10-19 21:54:32 +00002564 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2565 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002566
2567 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002568 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002569 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002570 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002572 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002573}
2574
Douglas Gregor14454802011-02-25 02:25:35 +00002575void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2576 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002577 // Make sure the extended qualifier info is allocated.
2578 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002579 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002580 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002581 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002582 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002583 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002584 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002585 if (getExtInfo()->NumTemplParamLists == 0) {
2586 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002587 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002588 }
2589 else
2590 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002591 }
2592 }
2593}
2594
Abramo Bagnara60804e12011-03-18 15:16:37 +00002595void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2596 unsigned NumTPLists,
2597 TemplateParameterList **TPLists) {
2598 assert(NumTPLists > 0);
2599 // Make sure the extended decl info is allocated.
2600 if (!hasExtInfo())
2601 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002602 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002603 // Set the template parameter lists info.
2604 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2605}
2606
Ted Kremenek21475702008-09-05 17:16:31 +00002607//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002608// EnumDecl Implementation
2609//===----------------------------------------------------------------------===//
2610
David Blaikie68e081d2011-12-20 02:48:34 +00002611void EnumDecl::anchor() { }
2612
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002613EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2614 SourceLocation StartLoc, SourceLocation IdLoc,
2615 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002616 EnumDecl *PrevDecl, bool IsScoped,
2617 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002618 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002619 IsScoped, IsScopedUsingClassTag, IsFixed);
Sebastian Redl833ef452010-01-26 22:01:41 +00002620 C.getTypeDeclType(Enum, PrevDecl);
2621 return Enum;
2622}
2623
Douglas Gregor72172e92012-01-05 21:55:30 +00002624EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2625 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2626 return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2627 false, false, false);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002628}
2629
Douglas Gregord5058122010-02-11 01:19:42 +00002630void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002631 QualType NewPromotionType,
2632 unsigned NumPositiveBits,
2633 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002634 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002635 if (!IntegerType)
2636 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002637 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002638 setNumPositiveBits(NumPositiveBits);
2639 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002640 TagDecl::completeDefinition();
2641}
2642
Richard Smith7d137e32012-03-23 03:33:32 +00002643TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2644 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2645 return MSI->getTemplateSpecializationKind();
2646
2647 return TSK_Undeclared;
2648}
2649
2650void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2651 SourceLocation PointOfInstantiation) {
2652 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2653 assert(MSI && "Not an instantiated member enumeration?");
2654 MSI->setTemplateSpecializationKind(TSK);
2655 if (TSK != TSK_ExplicitSpecialization &&
2656 PointOfInstantiation.isValid() &&
2657 MSI->getPointOfInstantiation().isInvalid())
2658 MSI->setPointOfInstantiation(PointOfInstantiation);
2659}
2660
Richard Smith4b38ded2012-03-14 23:13:10 +00002661EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2662 if (SpecializationInfo)
2663 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2664
2665 return 0;
2666}
2667
2668void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2669 TemplateSpecializationKind TSK) {
2670 assert(!SpecializationInfo && "Member enum is already a specialization");
2671 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2672}
2673
Sebastian Redl833ef452010-01-26 22:01:41 +00002674//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002675// RecordDecl Implementation
2676//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00002677
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002678RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2679 SourceLocation StartLoc, SourceLocation IdLoc,
2680 IdentifierInfo *Id, RecordDecl *PrevDecl)
2681 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00002682 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002683 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002684 HasObjectMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002685 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00002686 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00002687}
2688
Jay Foad39c79802011-01-12 09:06:06 +00002689RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002690 SourceLocation StartLoc, SourceLocation IdLoc,
2691 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2692 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2693 PrevDecl);
Ted Kremenek21475702008-09-05 17:16:31 +00002694 C.getTypeDeclType(R, PrevDecl);
2695 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00002696}
2697
Douglas Gregor72172e92012-01-05 21:55:30 +00002698RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2699 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
2700 return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2701 SourceLocation(), 0, 0);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002702}
2703
Douglas Gregordfcad112009-03-25 15:59:44 +00002704bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00002705 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00002706 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2707}
2708
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002709RecordDecl::field_iterator RecordDecl::field_begin() const {
2710 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2711 LoadFieldsFromExternalStorage();
2712
2713 return field_iterator(decl_iterator(FirstDecl));
2714}
2715
Douglas Gregorb11aad82011-02-19 18:51:44 +00002716/// completeDefinition - Notes that the definition of this type is now
2717/// complete.
2718void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00002719 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00002720 TagDecl::completeDefinition();
2721}
2722
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002723void RecordDecl::LoadFieldsFromExternalStorage() const {
2724 ExternalASTSource *Source = getASTContext().getExternalSource();
2725 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2726
2727 // Notify that we have a RecordDecl doing some initialization.
2728 ExternalASTSource::Deserializing TheFields(Source);
2729
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002730 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002731 LoadedFieldsFromExternalStorage = true;
2732 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2733 case ELR_Success:
2734 break;
2735
2736 case ELR_AlreadyLoaded:
2737 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002738 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002739 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002740
2741#ifndef NDEBUG
2742 // Check that all decls we got were FieldDecls.
2743 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2744 assert(isa<FieldDecl>(Decls[i]));
2745#endif
2746
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002747 if (Decls.empty())
2748 return;
2749
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00002750 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2751 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002752}
2753
Steve Naroff415d3d52008-10-08 17:01:13 +00002754//===----------------------------------------------------------------------===//
2755// BlockDecl Implementation
2756//===----------------------------------------------------------------------===//
2757
David Blaikie9c70e042011-09-21 18:16:56 +00002758void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00002759 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00002760
Steve Naroffc4b30e52009-03-13 16:56:44 +00002761 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002762 if (!NewParamInfo.empty()) {
2763 NumParams = NewParamInfo.size();
2764 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2765 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002766 }
2767}
2768
John McCall351762c2011-02-07 10:33:21 +00002769void BlockDecl::setCaptures(ASTContext &Context,
2770 const Capture *begin,
2771 const Capture *end,
2772 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00002773 CapturesCXXThis = capturesCXXThis;
2774
2775 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00002776 NumCaptures = 0;
2777 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00002778 return;
2779 }
2780
John McCall351762c2011-02-07 10:33:21 +00002781 NumCaptures = end - begin;
2782
2783 // Avoid new Capture[] because we don't want to provide a default
2784 // constructor.
2785 size_t allocationSize = NumCaptures * sizeof(Capture);
2786 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2787 memcpy(buffer, begin, allocationSize);
2788 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002789}
Sebastian Redl833ef452010-01-26 22:01:41 +00002790
John McCallce45f882011-06-15 22:51:16 +00002791bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2792 for (capture_const_iterator
2793 i = capture_begin(), e = capture_end(); i != e; ++i)
2794 // Only auto vars can be captured, so no redeclaration worries.
2795 if (i->getVariable() == variable)
2796 return true;
2797
2798 return false;
2799}
2800
Douglas Gregor70226da2010-12-21 16:27:07 +00002801SourceRange BlockDecl::getSourceRange() const {
2802 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2803}
Sebastian Redl833ef452010-01-26 22:01:41 +00002804
2805//===----------------------------------------------------------------------===//
2806// Other Decl Allocation/Deallocation Method Implementations
2807//===----------------------------------------------------------------------===//
2808
David Blaikie68e081d2011-12-20 02:48:34 +00002809void TranslationUnitDecl::anchor() { }
2810
Sebastian Redl833ef452010-01-26 22:01:41 +00002811TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2812 return new (C) TranslationUnitDecl(C);
2813}
2814
David Blaikie68e081d2011-12-20 02:48:34 +00002815void LabelDecl::anchor() { }
2816
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002817LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002818 SourceLocation IdentL, IdentifierInfo *II) {
2819 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2820}
2821
2822LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2823 SourceLocation IdentL, IdentifierInfo *II,
2824 SourceLocation GnuLabelL) {
2825 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2826 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002827}
2828
Douglas Gregor72172e92012-01-05 21:55:30 +00002829LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2830 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
2831 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00002832}
2833
David Blaikie68e081d2011-12-20 02:48:34 +00002834void ValueDecl::anchor() { }
2835
2836void ImplicitParamDecl::anchor() { }
2837
Sebastian Redl833ef452010-01-26 22:01:41 +00002838ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002839 SourceLocation IdLoc,
2840 IdentifierInfo *Id,
2841 QualType Type) {
2842 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00002843}
2844
Douglas Gregor72172e92012-01-05 21:55:30 +00002845ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
2846 unsigned ID) {
2847 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
2848 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
2849}
2850
Sebastian Redl833ef452010-01-26 22:01:41 +00002851FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002852 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002853 const DeclarationNameInfo &NameInfo,
2854 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002855 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00002856 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00002857 bool hasWrittenPrototype,
2858 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002859 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2860 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00002861 isInlineSpecified,
2862 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00002863 New->HasWrittenPrototype = hasWrittenPrototype;
2864 return New;
2865}
2866
Douglas Gregor72172e92012-01-05 21:55:30 +00002867FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2868 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
2869 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
2870 DeclarationNameInfo(), QualType(), 0,
2871 SC_None, SC_None, false, false);
2872}
2873
Sebastian Redl833ef452010-01-26 22:01:41 +00002874BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2875 return new (C) BlockDecl(DC, L);
2876}
2877
Douglas Gregor72172e92012-01-05 21:55:30 +00002878BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2879 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
2880 return new (Mem) BlockDecl(0, SourceLocation());
2881}
2882
Sebastian Redl833ef452010-01-26 22:01:41 +00002883EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2884 SourceLocation L,
2885 IdentifierInfo *Id, QualType T,
2886 Expr *E, const llvm::APSInt &V) {
2887 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2888}
2889
Douglas Gregor72172e92012-01-05 21:55:30 +00002890EnumConstantDecl *
2891EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2892 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
2893 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
2894 llvm::APSInt());
2895}
2896
David Blaikie68e081d2011-12-20 02:48:34 +00002897void IndirectFieldDecl::anchor() { }
2898
Benjamin Kramer39593702010-11-21 14:11:41 +00002899IndirectFieldDecl *
2900IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2901 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2902 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00002903 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2904}
2905
Douglas Gregor72172e92012-01-05 21:55:30 +00002906IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
2907 unsigned ID) {
2908 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
2909 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
2910 QualType(), 0, 0);
2911}
2912
Douglas Gregorbe996932010-09-01 20:41:53 +00002913SourceRange EnumConstantDecl::getSourceRange() const {
2914 SourceLocation End = getLocation();
2915 if (Init)
2916 End = Init->getLocEnd();
2917 return SourceRange(getLocation(), End);
2918}
2919
David Blaikie68e081d2011-12-20 02:48:34 +00002920void TypeDecl::anchor() { }
2921
Sebastian Redl833ef452010-01-26 22:01:41 +00002922TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00002923 SourceLocation StartLoc, SourceLocation IdLoc,
2924 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2925 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00002926}
2927
David Blaikie68e081d2011-12-20 02:48:34 +00002928void TypedefNameDecl::anchor() { }
2929
Douglas Gregor72172e92012-01-05 21:55:30 +00002930TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2931 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
2932 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2933}
2934
Richard Smithdda56e42011-04-15 14:24:37 +00002935TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2936 SourceLocation StartLoc,
2937 SourceLocation IdLoc, IdentifierInfo *Id,
2938 TypeSourceInfo *TInfo) {
2939 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2940}
2941
Douglas Gregor72172e92012-01-05 21:55:30 +00002942TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2943 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
2944 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2945}
2946
Abramo Bagnaraea947882011-03-08 16:41:52 +00002947SourceRange TypedefDecl::getSourceRange() const {
2948 SourceLocation RangeEnd = getLocation();
2949 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2950 if (typeIsPostfix(TInfo->getType()))
2951 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2952 }
2953 return SourceRange(getLocStart(), RangeEnd);
2954}
2955
Richard Smithdda56e42011-04-15 14:24:37 +00002956SourceRange TypeAliasDecl::getSourceRange() const {
2957 SourceLocation RangeEnd = getLocStart();
2958 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2959 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2960 return SourceRange(getLocStart(), RangeEnd);
2961}
2962
David Blaikie68e081d2011-12-20 02:48:34 +00002963void FileScopeAsmDecl::anchor() { }
2964
Sebastian Redl833ef452010-01-26 22:01:41 +00002965FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00002966 StringLiteral *Str,
2967 SourceLocation AsmLoc,
2968 SourceLocation RParenLoc) {
2969 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00002970}
Douglas Gregorba345522011-12-02 23:23:56 +00002971
Douglas Gregor72172e92012-01-05 21:55:30 +00002972FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
2973 unsigned ID) {
2974 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
2975 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
2976}
2977
Douglas Gregorba345522011-12-02 23:23:56 +00002978//===----------------------------------------------------------------------===//
2979// ImportDecl Implementation
2980//===----------------------------------------------------------------------===//
2981
2982/// \brief Retrieve the number of module identifiers needed to name the given
2983/// module.
2984static unsigned getNumModuleIdentifiers(Module *Mod) {
2985 unsigned Result = 1;
2986 while (Mod->Parent) {
2987 Mod = Mod->Parent;
2988 ++Result;
2989 }
2990 return Result;
2991}
2992
Douglas Gregor22d09742012-01-03 18:04:46 +00002993ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002994 Module *Imported,
2995 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00002996 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002997 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002998{
2999 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3000 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3001 memcpy(StoredLocs, IdentifierLocs.data(),
3002 IdentifierLocs.size() * sizeof(SourceLocation));
3003}
3004
Douglas Gregor22d09742012-01-03 18:04:46 +00003005ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003006 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00003007 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00003008 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00003009{
3010 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3011}
3012
3013ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003014 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00003015 ArrayRef<SourceLocation> IdentifierLocs) {
3016 void *Mem = C.Allocate(sizeof(ImportDecl) +
3017 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003018 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00003019}
3020
3021ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00003022 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00003023 Module *Imported,
3024 SourceLocation EndLoc) {
3025 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00003026 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00003027 Import->setImplicit();
3028 return Import;
3029}
3030
Douglas Gregor72172e92012-01-05 21:55:30 +00003031ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3032 unsigned NumLocations) {
3033 void *Mem = AllocateDeserializedDecl(C, ID,
3034 (sizeof(ImportDecl) +
3035 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00003036 return new (Mem) ImportDecl(EmptyShell());
3037}
3038
3039ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3040 if (!ImportedAndComplete.getInt())
3041 return ArrayRef<SourceLocation>();
3042
3043 const SourceLocation *StoredLocs
3044 = reinterpret_cast<const SourceLocation *>(this + 1);
3045 return ArrayRef<SourceLocation>(StoredLocs,
3046 getNumModuleIdentifiers(getImportedModule()));
3047}
3048
3049SourceRange ImportDecl::getSourceRange() const {
3050 if (!ImportedAndComplete.getInt())
3051 return SourceRange(getLocation(),
3052 *reinterpret_cast<const SourceLocation *>(this + 1));
3053
3054 return SourceRange(getLocation(), getIdentifierLocs().back());
3055}