blob: 76d8ec06bf880ece5155ebddb87596d00b7ecc8f [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"
Benjamin Kramer3307c5082012-02-04 12:31:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Abramo Bagnara6150c882010-05-11 21:36:43 +000029#include "clang/Basic/Specifiers.h"
Douglas Gregor1baf38f2011-03-26 12:10:19 +000030#include "clang/Basic/TargetInfo.h"
John McCall06f6fe8d2009-09-04 01:14:41 +000031#include "llvm/Support/ErrorHandling.h"
Ted Kremenekce20e8f2008-05-20 00:43:19 +000032
David Blaikie9c70e042011-09-21 18:16:56 +000033#include <algorithm>
34
Chris Lattner6d9a6852006-10-25 05:11:20 +000035using namespace clang;
Chris Lattnera11999d2006-10-15 22:34:45 +000036
Chris Lattner88f70d62008-03-15 05:43:15 +000037//===----------------------------------------------------------------------===//
Douglas Gregor6e6ad602009-01-20 01:17:11 +000038// NamedDecl Implementation
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000039//===----------------------------------------------------------------------===//
40
Douglas Gregor1baf38f2011-03-26 12:10:19 +000041static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
42 // If this declaration has an explicit visibility attribute, use it.
43 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
44 switch (A->getVisibility()) {
45 case VisibilityAttr::Default:
46 return DefaultVisibility;
47 case VisibilityAttr::Hidden:
48 return HiddenVisibility;
49 case VisibilityAttr::Protected:
50 return ProtectedVisibility;
51 }
John McCall457a04e2010-10-22 21:05:15 +000052 }
Douglas Gregor1baf38f2011-03-26 12:10:19 +000053
54 // If we're on Mac OS X, an 'availability' for Mac OS X attribute
55 // implies visibility(default).
Douglas Gregore8bbc122011-09-02 00:18:52 +000056 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +000057 for (specific_attr_iterator<AvailabilityAttr>
58 A = D->specific_attr_begin<AvailabilityAttr>(),
59 AEnd = D->specific_attr_end<AvailabilityAttr>();
60 A != AEnd; ++A)
61 if ((*A)->getPlatform()->getName().equals("macosx"))
62 return DefaultVisibility;
63 }
64
65 return llvm::Optional<Visibility>();
John McCall457a04e2010-10-22 21:05:15 +000066}
67
John McCallc273f242010-10-30 11:50:40 +000068typedef NamedDecl::LinkageInfo LinkageInfo;
John McCallc273f242010-10-30 11:50:40 +000069
Benjamin Kramer396dcf32010-11-05 19:56:37 +000070namespace {
John McCall07072662010-11-02 01:45:15 +000071/// Flags controlling the computation of linkage and visibility.
72struct LVFlags {
73 bool ConsiderGlobalVisibility;
74 bool ConsiderVisibilityAttributes;
John McCall8bc6d5b2011-03-04 10:39:25 +000075 bool ConsiderTemplateParameterTypes;
John McCall07072662010-11-02 01:45:15 +000076
77 LVFlags() : ConsiderGlobalVisibility(true),
John McCall8bc6d5b2011-03-04 10:39:25 +000078 ConsiderVisibilityAttributes(true),
79 ConsiderTemplateParameterTypes(true) {
John McCall07072662010-11-02 01:45:15 +000080 }
81
Douglas Gregorbf62d642010-12-06 18:36:25 +000082 /// \brief Returns a set of flags that is only useful for computing the
83 /// linkage, not the visibility, of a declaration.
84 static LVFlags CreateOnlyDeclLinkage() {
85 LVFlags F;
86 F.ConsiderGlobalVisibility = false;
87 F.ConsiderVisibilityAttributes = false;
John McCall8bc6d5b2011-03-04 10:39:25 +000088 F.ConsiderTemplateParameterTypes = false;
Douglas Gregorbf62d642010-12-06 18:36:25 +000089 return F;
90 }
91
John McCall07072662010-11-02 01:45:15 +000092 /// Returns a set of flags, otherwise based on these, which ignores
93 /// off all sources of visibility except template arguments.
94 LVFlags onlyTemplateVisibility() const {
95 LVFlags F = *this;
96 F.ConsiderGlobalVisibility = false;
97 F.ConsiderVisibilityAttributes = false;
John McCall8bc6d5b2011-03-04 10:39:25 +000098 F.ConsiderTemplateParameterTypes = false;
John McCall07072662010-11-02 01:45:15 +000099 return F;
100 }
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000101};
Benjamin Kramer396dcf32010-11-05 19:56:37 +0000102} // end anonymous namespace
John McCall07072662010-11-02 01:45:15 +0000103
Rafael Espindola2f869a32012-01-14 00:30:36 +0000104static LinkageInfo getLVForType(QualType T) {
105 std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
106 return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
107}
108
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000109/// \brief Get the most restrictive linkage for the types in the given
110/// template parameter list.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000111static LinkageInfo
John McCall457a04e2010-10-22 21:05:15 +0000112getLVForTemplateParameterList(const TemplateParameterList *Params) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000113 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000114 for (TemplateParameterList::const_iterator P = Params->begin(),
115 PEnd = Params->end();
116 P != PEnd; ++P) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000117 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
118 if (NTTP->isExpandedParameterPack()) {
119 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
120 QualType T = NTTP->getExpansionType(I);
121 if (!T->isDependentType())
Rafael Espindola2f869a32012-01-14 00:30:36 +0000122 LV.merge(getLVForType(T));
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000123 }
124 continue;
125 }
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000126
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000127 if (!NTTP->getType()->isDependentType()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000128 LV.merge(getLVForType(NTTP->getType()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000129 continue;
130 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000131 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000132
133 if (TemplateTemplateParmDecl *TTP
134 = dyn_cast<TemplateTemplateParmDecl>(*P)) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000135 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000136 }
137 }
138
John McCall457a04e2010-10-22 21:05:15 +0000139 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000140}
141
Douglas Gregorbf62d642010-12-06 18:36:25 +0000142/// getLVForDecl - Get the linkage and visibility for the given declaration.
143static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
144
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000145/// \brief Get the most restrictive linkage for the types and
146/// declarations in the given template argument list.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000147static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
148 unsigned NumArgs,
149 LVFlags &F) {
150 LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000151
152 for (unsigned I = 0; I != NumArgs; ++I) {
153 switch (Args[I].getKind()) {
154 case TemplateArgument::Null:
155 case TemplateArgument::Integral:
156 case TemplateArgument::Expression:
157 break;
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000158
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000159 case TemplateArgument::Type:
Rafael Espindola2f869a32012-01-14 00:30:36 +0000160 LV.merge(getLVForType(Args[I].getAsType()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000161 break;
162
163 case TemplateArgument::Declaration:
John McCall457a04e2010-10-22 21:05:15 +0000164 // The decl can validly be null as the representation of nullptr
165 // arguments, valid only in C++0x.
166 if (Decl *D = Args[I].getAsDecl()) {
Douglas Gregor91df6cf2010-12-06 18:50:56 +0000167 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
168 LV = merge(LV, getLVForDecl(ND, F));
John McCall457a04e2010-10-22 21:05:15 +0000169 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000170 break;
171
172 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000173 case TemplateArgument::TemplateExpansion:
Rafael Espindolaeeb9d9f2012-01-02 06:26:22 +0000174 if (TemplateDecl *Template
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000175 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
Rafael Espindola2f869a32012-01-14 00:30:36 +0000176 LV.merge(getLVForDecl(Template, F));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000177 break;
178
179 case TemplateArgument::Pack:
Rafael Espindola2f869a32012-01-14 00:30:36 +0000180 LV.merge(getLVForTemplateArgumentList(Args[I].pack_begin(),
181 Args[I].pack_size(),
182 F));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000183 break;
184 }
185 }
186
John McCall457a04e2010-10-22 21:05:15 +0000187 return LV;
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000188}
189
Rafael Espindola2f869a32012-01-14 00:30:36 +0000190static LinkageInfo
Douglas Gregorbf62d642010-12-06 18:36:25 +0000191getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
192 LVFlags &F) {
193 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
John McCall8823c652010-08-13 08:35:10 +0000194}
195
John McCallb8c604a2011-06-27 23:06:04 +0000196static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
197 const FunctionTemplateSpecializationInfo *spec) {
198 return !(spec->isExplicitSpecialization() &&
199 fn->hasAttr<VisibilityAttr>());
200}
201
202static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
203 return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
204}
205
John McCall07072662010-11-02 01:45:15 +0000206static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
Sebastian Redl50c68252010-08-31 00:36:30 +0000207 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
Douglas Gregorf73b2822009-11-25 22:24:25 +0000208 "Not a name having namespace scope");
209 ASTContext &Context = D->getASTContext();
210
211 // C++ [basic.link]p3:
212 // A name having namespace scope (3.3.6) has internal linkage if it
213 // is the name of
214 // - an object, reference, function or function template that is
215 // explicitly declared static; or,
216 // (This bullet corresponds to C99 6.2.2p3.)
217 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
218 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000219 if (Var->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000220 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000221
222 // - an object or reference that is explicitly declared const
223 // and neither explicitly declared extern nor previously
224 // declared to have external linkage; or
225 // (there is no equivalent in C99)
226 if (Context.getLangOptions().CPlusPlus &&
Eli Friedmanf873c2f2009-11-26 03:04:01 +0000227 Var->getType().isConstant(Context) &&
John McCall8e7d6562010-08-26 03:08:43 +0000228 Var->getStorageClass() != SC_Extern &&
229 Var->getStorageClass() != SC_PrivateExtern) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000230 bool FoundExtern = false;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000231 for (const VarDecl *PrevVar = Var->getPreviousDecl();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000232 PrevVar && !FoundExtern;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000233 PrevVar = PrevVar->getPreviousDecl())
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000234 if (isExternalLinkage(PrevVar->getLinkage()))
Douglas Gregorf73b2822009-11-25 22:24:25 +0000235 FoundExtern = true;
236
237 if (!FoundExtern)
John McCallc273f242010-10-30 11:50:40 +0000238 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000239 }
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000240 if (Var->getStorageClass() == SC_None) {
Douglas Gregorec9fd132012-01-14 16:38:05 +0000241 const VarDecl *PrevVar = Var->getPreviousDecl();
242 for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
Fariborz Jahanian8feee2d2011-06-16 20:14:50 +0000243 if (PrevVar->getStorageClass() == SC_PrivateExtern)
244 break;
245 if (PrevVar)
246 return PrevVar->getLinkageAndVisibility();
247 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000248 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000249 // C++ [temp]p4:
250 // A non-member function template can have internal linkage; any
251 // other template name shall have external linkage.
Douglas Gregorf73b2822009-11-25 22:24:25 +0000252 const FunctionDecl *Function = 0;
253 if (const FunctionTemplateDecl *FunTmpl
254 = dyn_cast<FunctionTemplateDecl>(D))
255 Function = FunTmpl->getTemplatedDecl();
256 else
257 Function = cast<FunctionDecl>(D);
258
259 // Explicitly declared static.
John McCall8e7d6562010-08-26 03:08:43 +0000260 if (Function->getStorageClass() == SC_Static)
John McCallc273f242010-10-30 11:50:40 +0000261 return LinkageInfo(InternalLinkage, DefaultVisibility, false);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000262 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
263 // - a data member of an anonymous union.
264 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
John McCallc273f242010-10-30 11:50:40 +0000265 return LinkageInfo::internal();
Douglas Gregorf73b2822009-11-25 22:24:25 +0000266 }
267
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000268 if (D->isInAnonymousNamespace()) {
269 const VarDecl *Var = dyn_cast<VarDecl>(D);
270 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
Eli Friedman839192f2012-01-15 01:23:58 +0000271 if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
272 (!Func || !Func->getDeclContext()->isExternCContext()))
Chandler Carruth9682a2fd2011-02-24 19:03:39 +0000273 return LinkageInfo::uniqueExternal();
274 }
John McCallb7139c42010-10-28 04:18:25 +0000275
John McCall457a04e2010-10-22 21:05:15 +0000276 // Set up the defaults.
277
278 // C99 6.2.2p5:
279 // If the declaration of an identifier for an object has file
280 // scope and no storage-class specifier, its linkage is
281 // external.
John McCallc273f242010-10-30 11:50:40 +0000282 LinkageInfo LV;
283
John McCall07072662010-11-02 01:45:15 +0000284 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000285 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
286 LV.setVisibility(*Vis, true);
John McCall07072662010-11-02 01:45:15 +0000287 F.ConsiderGlobalVisibility = false;
John McCall2faf32c2010-12-10 02:59:44 +0000288 } else {
289 // If we're declared in a namespace with a visibility attribute,
290 // use that namespace's visibility, but don't call it explicit.
291 for (const DeclContext *DC = D->getDeclContext();
292 !isa<TranslationUnitDecl>(DC);
293 DC = DC->getParent()) {
Rafael Espindola09593a32012-01-01 17:48:19 +0000294 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
295 if (!ND) continue;
296 if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
Rafael Espindola0f960a02012-01-01 18:06:40 +0000297 LV.setVisibility(*Vis, true);
John McCall2faf32c2010-12-10 02:59:44 +0000298 F.ConsiderGlobalVisibility = false;
299 break;
300 }
301 }
John McCall07072662010-11-02 01:45:15 +0000302 }
John McCallc273f242010-10-30 11:50:40 +0000303 }
John McCall457a04e2010-10-22 21:05:15 +0000304
Douglas Gregorf73b2822009-11-25 22:24:25 +0000305 // C++ [basic.link]p4:
John McCall457a04e2010-10-22 21:05:15 +0000306
Douglas Gregorf73b2822009-11-25 22:24:25 +0000307 // A name having namespace scope has external linkage if it is the
308 // name of
309 //
310 // - an object or reference, unless it has internal linkage; or
311 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
John McCall37bb6c92010-10-29 22:22:43 +0000312 // GCC applies the following optimization to variables and static
313 // data members, but not to functions:
314 //
John McCall457a04e2010-10-22 21:05:15 +0000315 // Modify the variable's LV by the LV of its type unless this is
316 // C or extern "C". This follows from [basic.link]p9:
317 // A type without linkage shall not be used as the type of a
318 // variable or function with external linkage unless
319 // - the entity has C language linkage, or
320 // - the entity is declared within an unnamed namespace, or
321 // - the entity is not used or is defined in the same
322 // translation unit.
323 // and [basic.link]p10:
324 // ...the types specified by all declarations referring to a
325 // given variable or function shall be identical...
326 // C does not have an equivalent rule.
327 //
John McCall5fe84122010-10-26 04:59:26 +0000328 // Ignore this if we've got an explicit attribute; the user
329 // probably knows what they're doing.
330 //
John McCall457a04e2010-10-22 21:05:15 +0000331 // Note that we don't want to make the variable non-external
332 // because of this, but unique-external linkage suits us.
Eli Friedman839192f2012-01-15 01:23:58 +0000333 if (Context.getLangOptions().CPlusPlus &&
334 !Var->getDeclContext()->isExternCContext()) {
Rafael Espindola2f869a32012-01-14 00:30:36 +0000335 LinkageInfo TypeLV = getLVForType(Var->getType());
336 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000337 return LinkageInfo::uniqueExternal();
338 if (!LV.visibilityExplicit())
Rafael Espindola2f869a32012-01-14 00:30:36 +0000339 LV.mergeVisibility(TypeLV.visibility(), TypeLV.visibilityExplicit());
John McCall37bb6c92010-10-29 22:22:43 +0000340 }
341
John McCall23032652010-11-02 18:38:13 +0000342 if (Var->getStorageClass() == SC_PrivateExtern)
343 LV.setVisibility(HiddenVisibility, true);
344
Douglas Gregorf73b2822009-11-25 22:24:25 +0000345 if (!Context.getLangOptions().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000346 (Var->getStorageClass() == SC_Extern ||
347 Var->getStorageClass() == SC_PrivateExtern)) {
John McCall457a04e2010-10-22 21:05:15 +0000348
Douglas Gregorf73b2822009-11-25 22:24:25 +0000349 // C99 6.2.2p4:
350 // For an identifier declared with the storage-class specifier
351 // extern in a scope in which a prior declaration of that
352 // identifier is visible, if the prior declaration specifies
353 // internal or external linkage, the linkage of the identifier
354 // at the later declaration is the same as the linkage
355 // specified at the prior declaration. If no prior declaration
356 // is visible, or if the prior declaration specifies no
357 // linkage, then the identifier has external linkage.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000358 if (const VarDecl *PrevVar = Var->getPreviousDecl()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000359 LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
John McCallc273f242010-10-30 11:50:40 +0000360 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
361 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000362 }
363 }
364
Douglas Gregorf73b2822009-11-25 22:24:25 +0000365 // - a function, unless it has internal linkage; or
John McCall457a04e2010-10-22 21:05:15 +0000366 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
John McCall2efaf112010-10-28 07:07:52 +0000367 // In theory, we can modify the function's LV by the LV of its
368 // type unless it has C linkage (see comment above about variables
369 // for justification). In practice, GCC doesn't do this, so it's
370 // just too painful to make work.
John McCall457a04e2010-10-22 21:05:15 +0000371
John McCall23032652010-11-02 18:38:13 +0000372 if (Function->getStorageClass() == SC_PrivateExtern)
373 LV.setVisibility(HiddenVisibility, true);
374
Douglas Gregorf73b2822009-11-25 22:24:25 +0000375 // C99 6.2.2p5:
376 // If the declaration of an identifier for a function has no
377 // storage-class specifier, its linkage is determined exactly
378 // as if it were declared with the storage-class specifier
379 // extern.
380 if (!Context.getLangOptions().CPlusPlus &&
John McCall8e7d6562010-08-26 03:08:43 +0000381 (Function->getStorageClass() == SC_Extern ||
382 Function->getStorageClass() == SC_PrivateExtern ||
383 Function->getStorageClass() == SC_None)) {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000384 // C99 6.2.2p4:
385 // For an identifier declared with the storage-class specifier
386 // extern in a scope in which a prior declaration of that
387 // identifier is visible, if the prior declaration specifies
388 // internal or external linkage, the linkage of the identifier
389 // at the later declaration is the same as the linkage
390 // specified at the prior declaration. If no prior declaration
391 // is visible, or if the prior declaration specifies no
392 // linkage, then the identifier has external linkage.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000393 if (const FunctionDecl *PrevFunc = Function->getPreviousDecl()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000394 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
John McCallc273f242010-10-30 11:50:40 +0000395 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
396 LV.mergeVisibility(PrevLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000397 }
398 }
399
John McCallf768aa72011-02-10 06:50:24 +0000400 // In C++, then if the type of the function uses a type with
401 // unique-external linkage, it's not legally usable from outside
402 // this translation unit. However, we should use the C linkage
403 // rules instead for extern "C" declarations.
Eli Friedman839192f2012-01-15 01:23:58 +0000404 if (Context.getLangOptions().CPlusPlus &&
405 !Function->getDeclContext()->isExternCContext() &&
John McCallf768aa72011-02-10 06:50:24 +0000406 Function->getType()->getLinkage() == UniqueExternalLinkage)
407 return LinkageInfo::uniqueExternal();
408
John McCallb8c604a2011-06-27 23:06:04 +0000409 // Consider LV from the template and the template arguments unless
410 // this is an explicit specialization with a visibility attribute.
411 if (FunctionTemplateSpecializationInfo *specInfo
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000412 = Function->getTemplateSpecializationInfo()) {
John McCallb8c604a2011-06-27 23:06:04 +0000413 if (shouldConsiderTemplateLV(Function, specInfo)) {
414 LV.merge(getLVForDecl(specInfo->getTemplate(),
415 F.onlyTemplateVisibility()));
416 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
417 LV.merge(getLVForTemplateArgumentList(templateArgs, F));
418 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000419 }
420
Douglas Gregorf73b2822009-11-25 22:24:25 +0000421 // - a named class (Clause 9), or an unnamed class defined in a
422 // typedef declaration in which the class has the typedef name
423 // for linkage purposes (7.1.3); or
424 // - a named enumeration (7.2), or an unnamed enumeration
425 // defined in a typedef declaration in which the enumeration
426 // has the typedef name for linkage purposes (7.1.3); or
John McCall457a04e2010-10-22 21:05:15 +0000427 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
428 // Unnamed tags have no linkage.
Richard Smithdda56e42011-04-15 14:24:37 +0000429 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
John McCallc273f242010-10-30 11:50:40 +0000430 return LinkageInfo::none();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000431
John McCall457a04e2010-10-22 21:05:15 +0000432 // If this is a class template specialization, consider the
433 // linkage of the template and template arguments.
John McCallb8c604a2011-06-27 23:06:04 +0000434 if (const ClassTemplateSpecializationDecl *spec
John McCall457a04e2010-10-22 21:05:15 +0000435 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
John McCallb8c604a2011-06-27 23:06:04 +0000436 if (shouldConsiderTemplateLV(spec)) {
437 // From the template.
438 LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
439 F.onlyTemplateVisibility()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000440
John McCallb8c604a2011-06-27 23:06:04 +0000441 // The arguments at which the template was instantiated.
442 const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
443 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
444 }
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000445 }
Douglas Gregorf73b2822009-11-25 22:24:25 +0000446
John McCall5fe84122010-10-26 04:59:26 +0000447 // Consider -fvisibility unless the type has C linkage.
John McCall07072662010-11-02 01:45:15 +0000448 if (F.ConsiderGlobalVisibility)
449 F.ConsiderGlobalVisibility =
John McCall5fe84122010-10-26 04:59:26 +0000450 (Context.getLangOptions().CPlusPlus &&
451 !Tag->getDeclContext()->isExternCContext());
John McCall457a04e2010-10-22 21:05:15 +0000452
Douglas Gregorf73b2822009-11-25 22:24:25 +0000453 // - an enumerator belonging to an enumeration with external linkage;
John McCall457a04e2010-10-22 21:05:15 +0000454 } else if (isa<EnumConstantDecl>(D)) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000455 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
John McCallc273f242010-10-30 11:50:40 +0000456 if (!isExternalLinkage(EnumLV.linkage()))
457 return LinkageInfo::none();
458 LV.merge(EnumLV);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000459
460 // - a template, unless it is a function template that has
461 // internal linkage (Clause 14);
John McCall8bc6d5b2011-03-04 10:39:25 +0000462 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
463 if (F.ConsiderTemplateParameterTypes)
464 LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000465
Douglas Gregorf73b2822009-11-25 22:24:25 +0000466 // - a namespace (7.3), unless it is declared within an unnamed
467 // namespace.
John McCall457a04e2010-10-22 21:05:15 +0000468 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
469 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000470
John McCall457a04e2010-10-22 21:05:15 +0000471 // By extension, we assign external linkage to Objective-C
472 // interfaces.
473 } else if (isa<ObjCInterfaceDecl>(D)) {
474 // fallout
475
476 // Everything not covered here has no linkage.
477 } else {
John McCallc273f242010-10-30 11:50:40 +0000478 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000479 }
480
481 // If we ended up with non-external linkage, visibility should
482 // always be default.
John McCallc273f242010-10-30 11:50:40 +0000483 if (LV.linkage() != ExternalLinkage)
484 return LinkageInfo(LV.linkage(), DefaultVisibility, false);
John McCall457a04e2010-10-22 21:05:15 +0000485
486 // If we didn't end up with hidden visibility, consider attributes
487 // and -fvisibility.
John McCall07072662010-11-02 01:45:15 +0000488 if (F.ConsiderGlobalVisibility)
John McCallc273f242010-10-30 11:50:40 +0000489 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
John McCall457a04e2010-10-22 21:05:15 +0000490
491 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000492}
493
John McCall07072662010-11-02 01:45:15 +0000494static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
John McCall457a04e2010-10-22 21:05:15 +0000495 // Only certain class members have linkage. Note that fields don't
496 // really have linkage, but it's convenient to say they do for the
497 // purposes of calculating linkage of pointer-to-data-member
498 // template arguments.
John McCall8823c652010-08-13 08:35:10 +0000499 if (!(isa<CXXMethodDecl>(D) ||
500 isa<VarDecl>(D) ||
John McCall457a04e2010-10-22 21:05:15 +0000501 isa<FieldDecl>(D) ||
John McCall8823c652010-08-13 08:35:10 +0000502 (isa<TagDecl>(D) &&
Richard Smithdda56e42011-04-15 14:24:37 +0000503 (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
John McCallc273f242010-10-30 11:50:40 +0000504 return LinkageInfo::none();
John McCall8823c652010-08-13 08:35:10 +0000505
John McCall07072662010-11-02 01:45:15 +0000506 LinkageInfo LV;
507
508 // The flags we're going to use to compute the class's visibility.
509 LVFlags ClassF = F;
510
511 // If we have an explicit visibility attribute, merge that in.
512 if (F.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000513 if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
514 LV.mergeVisibility(*Vis, true);
John McCall07072662010-11-02 01:45:15 +0000515
516 // Ignore global visibility later, but not this attribute.
517 F.ConsiderGlobalVisibility = false;
518
519 // Ignore both global visibility and attributes when computing our
520 // parent's visibility.
521 ClassF = F.onlyTemplateVisibility();
522 }
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
John McCall8823c652010-08-13 08:35:10 +0000535 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
John McCallf768aa72011-02-10 06:50:24 +0000536 // If the type of the function uses a type with unique-external
537 // linkage, it's not legally usable from outside this translation unit.
538 if (MD->getType()->getLinkage() == UniqueExternalLinkage)
539 return LinkageInfo::uniqueExternal();
540
John McCall37bb6c92010-10-29 22:22:43 +0000541 TemplateSpecializationKind TSK = TSK_Undeclared;
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)) {
548 LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F));
549 if (F.ConsiderTemplateParameterTypes)
550 LV.merge(getLVForTemplateParameterList(
551 spec->getTemplate()->getTemplateParameters()));
552 }
John McCall37bb6c92010-10-29 22:22:43 +0000553
John McCallb8c604a2011-06-27 23:06:04 +0000554 TSK = spec->getTemplateSpecializationKind();
John McCall37bb6c92010-10-29 22:22:43 +0000555 } else if (MemberSpecializationInfo *MSI =
556 MD->getMemberSpecializationInfo()) {
557 TSK = MSI->getTemplateSpecializationKind();
John McCall8823c652010-08-13 08:35:10 +0000558 }
559
John McCall37bb6c92010-10-29 22:22:43 +0000560 // If we're paying attention to global visibility, apply
561 // -finline-visibility-hidden if this is an inline method.
562 //
John McCallc273f242010-10-30 11:50:40 +0000563 // Note that ConsiderGlobalVisibility doesn't yet have information
564 // about whether containing classes have visibility attributes,
565 // and that's intentional.
566 if (TSK != TSK_ExplicitInstantiationDeclaration &&
Rafael Espindola0b790462011-12-27 21:15:28 +0000567 TSK != TSK_ExplicitInstantiationDefinition &&
John McCall07072662010-11-02 01:45:15 +0000568 F.ConsiderGlobalVisibility &&
John McCalle6e622e2010-11-01 01:29:57 +0000569 MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
570 // InlineVisibilityHidden only applies to definitions, and
571 // isInlined() only gives meaningful answers on definitions
572 // anyway.
573 const FunctionDecl *Def = 0;
574 if (MD->hasBody(Def) && Def->isInlined())
575 LV.setVisibility(HiddenVisibility);
576 }
John McCall457a04e2010-10-22 21:05:15 +0000577
John McCall37bb6c92010-10-29 22:22:43 +0000578 // Note that in contrast to basically every other situation, we
579 // *do* apply -fvisibility to method declarations.
580
581 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
John McCallb8c604a2011-06-27 23:06:04 +0000582 if (const ClassTemplateSpecializationDecl *spec
John McCall37bb6c92010-10-29 22:22:43 +0000583 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
John McCallb8c604a2011-06-27 23:06:04 +0000584 if (shouldConsiderTemplateLV(spec)) {
585 // Merge template argument/parameter information for member
586 // class template specializations.
587 LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
John McCall8bc6d5b2011-03-04 10:39:25 +0000588 if (F.ConsiderTemplateParameterTypes)
589 LV.merge(getLVForTemplateParameterList(
John McCallb8c604a2011-06-27 23:06:04 +0000590 spec->getSpecializedTemplate()->getTemplateParameters()));
591 }
John McCall37bb6c92010-10-29 22:22:43 +0000592 }
593
John McCall37bb6c92010-10-29 22:22:43 +0000594 // Static data members.
595 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCall36cd5cc2010-10-30 09:18:49 +0000596 // Modify the variable's linkage by its type, but ignore the
597 // type's visibility unless it's a definition.
Rafael Espindola2f869a32012-01-14 00:30:36 +0000598 LinkageInfo TypeLV = getLVForType(VD->getType());
599 if (TypeLV.linkage() != ExternalLinkage)
John McCallc273f242010-10-30 11:50:40 +0000600 LV.mergeLinkage(UniqueExternalLinkage);
601 if (!LV.visibilityExplicit())
Rafael Espindola2f869a32012-01-14 00:30:36 +0000602 LV.mergeVisibility(TypeLV.visibility(), TypeLV.visibilityExplicit());
John McCall37bb6c92010-10-29 22:22:43 +0000603 }
604
John McCall07072662010-11-02 01:45:15 +0000605 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
John McCall37bb6c92010-10-29 22:22:43 +0000606
607 // Apply -fvisibility if desired.
John McCall07072662010-11-02 01:45:15 +0000608 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
John McCallc273f242010-10-30 11:50:40 +0000609 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
John McCall8823c652010-08-13 08:35:10 +0000610 }
611
John McCall457a04e2010-10-22 21:05:15 +0000612 return LV;
John McCall8823c652010-08-13 08:35:10 +0000613}
614
John McCalld396b972011-02-08 19:01:05 +0000615static void clearLinkageForClass(const CXXRecordDecl *record) {
616 for (CXXRecordDecl::decl_iterator
617 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
618 Decl *child = *i;
619 if (isa<NamedDecl>(child))
620 cast<NamedDecl>(child)->ClearLinkageCache();
621 }
622}
623
David Blaikie68e081d2011-12-20 02:48:34 +0000624void NamedDecl::anchor() { }
625
John McCalld396b972011-02-08 19:01:05 +0000626void NamedDecl::ClearLinkageCache() {
627 // Note that we can't skip clearing the linkage of children just
628 // because the parent doesn't have cached linkage: we don't cache
629 // when computing linkage for parent contexts.
630
631 HasCachedLinkage = 0;
632
633 // If we're changing the linkage of a class, we need to reset the
634 // linkage of child declarations, too.
635 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
636 clearLinkageForClass(record);
637
John McCall83779672011-02-19 02:53:41 +0000638 if (ClassTemplateDecl *temp =
639 dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
John McCalld396b972011-02-08 19:01:05 +0000640 // Clear linkage for the template pattern.
641 CXXRecordDecl *record = temp->getTemplatedDecl();
642 record->HasCachedLinkage = 0;
643 clearLinkageForClass(record);
644
John McCall83779672011-02-19 02:53:41 +0000645 // We need to clear linkage for specializations, too.
646 for (ClassTemplateDecl::spec_iterator
647 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
648 i->ClearLinkageCache();
John McCalld396b972011-02-08 19:01:05 +0000649 }
John McCall83779672011-02-19 02:53:41 +0000650
651 // Clear cached linkage for function template decls, too.
652 if (FunctionTemplateDecl *temp =
John McCall8f9a4292011-03-22 06:58:49 +0000653 dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
654 temp->getTemplatedDecl()->ClearLinkageCache();
John McCall83779672011-02-19 02:53:41 +0000655 for (FunctionTemplateDecl::spec_iterator
656 i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
657 i->ClearLinkageCache();
John McCall8f9a4292011-03-22 06:58:49 +0000658 }
John McCall83779672011-02-19 02:53:41 +0000659
John McCalld396b972011-02-08 19:01:05 +0000660}
661
Douglas Gregorbf62d642010-12-06 18:36:25 +0000662Linkage NamedDecl::getLinkage() const {
663 if (HasCachedLinkage) {
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000664 assert(Linkage(CachedLinkage) ==
665 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000666 return Linkage(CachedLinkage);
667 }
668
669 CachedLinkage = getLVForDecl(this,
670 LVFlags::CreateOnlyDeclLinkage()).linkage();
671 HasCachedLinkage = 1;
672 return Linkage(CachedLinkage);
673}
674
John McCallc273f242010-10-30 11:50:40 +0000675LinkageInfo NamedDecl::getLinkageAndVisibility() const {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000676 LinkageInfo LI = getLVForDecl(this, LVFlags());
Benjamin Kramer87368ac2010-12-07 15:51:48 +0000677 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
Douglas Gregorbf62d642010-12-06 18:36:25 +0000678 HasCachedLinkage = 1;
679 CachedLinkage = LI.linkage();
680 return LI;
John McCall033caa52010-10-29 00:29:13 +0000681}
Ted Kremenek926d8602010-04-20 23:15:35 +0000682
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000683llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
684 // Use the most recent declaration of a variable.
685 if (const VarDecl *var = dyn_cast<VarDecl>(this))
Douglas Gregorec9fd132012-01-14 16:38:05 +0000686 return getVisibilityOf(var->getMostRecentDecl());
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000687
688 // Use the most recent declaration of a function, and also handle
689 // function template specializations.
690 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
691 if (llvm::Optional<Visibility> V
Douglas Gregorec9fd132012-01-14 16:38:05 +0000692 = getVisibilityOf(fn->getMostRecentDecl()))
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000693 return V;
694
695 // If the function is a specialization of a template with an
696 // explicit visibility attribute, use that.
697 if (FunctionTemplateSpecializationInfo *templateInfo
698 = fn->getTemplateSpecializationInfo())
699 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
700
701 return llvm::Optional<Visibility>();
702 }
703
704 // Otherwise, just check the declaration itself first.
705 if (llvm::Optional<Visibility> V = getVisibilityOf(this))
706 return V;
707
708 // If there wasn't explicit visibility there, and this is a
709 // specialization of a class template, check for visibility
710 // on the pattern.
711 if (const ClassTemplateSpecializationDecl *spec
712 = dyn_cast<ClassTemplateSpecializationDecl>(this))
713 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
714
715 return llvm::Optional<Visibility>();
716}
717
John McCall07072662010-11-02 01:45:15 +0000718static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000719 // Objective-C: treat all Objective-C declarations as having external
720 // linkage.
John McCall033caa52010-10-29 00:29:13 +0000721 switch (D->getKind()) {
Ted Kremenek926d8602010-04-20 23:15:35 +0000722 default:
723 break;
Argyrios Kyrtzidis79d04282011-12-01 01:28:21 +0000724 case Decl::ParmVar:
725 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000726 case Decl::TemplateTemplateParm: // count these as external
727 case Decl::NonTypeTemplateParm:
Ted Kremenek926d8602010-04-20 23:15:35 +0000728 case Decl::ObjCAtDefsField:
729 case Decl::ObjCCategory:
730 case Decl::ObjCCategoryImpl:
Ted Kremenek926d8602010-04-20 23:15:35 +0000731 case Decl::ObjCCompatibleAlias:
Ted Kremenek926d8602010-04-20 23:15:35 +0000732 case Decl::ObjCImplementation:
Ted Kremenek926d8602010-04-20 23:15:35 +0000733 case Decl::ObjCMethod:
734 case Decl::ObjCProperty:
735 case Decl::ObjCPropertyImpl:
736 case Decl::ObjCProtocol:
John McCallc273f242010-10-30 11:50:40 +0000737 return LinkageInfo::external();
Ted Kremenek926d8602010-04-20 23:15:35 +0000738 }
739
Douglas Gregorf73b2822009-11-25 22:24:25 +0000740 // Handle linkage for namespace-scope names.
John McCall033caa52010-10-29 00:29:13 +0000741 if (D->getDeclContext()->getRedeclContext()->isFileContext())
John McCall07072662010-11-02 01:45:15 +0000742 return getLVForNamespaceScopeDecl(D, Flags);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000743
744 // C++ [basic.link]p5:
745 // In addition, a member function, static data member, a named
746 // class or enumeration of class scope, or an unnamed class or
747 // enumeration defined in a class-scope typedef declaration such
748 // that the class or enumeration has the typedef name for linkage
749 // purposes (7.1.3), has external linkage if the name of the class
750 // has external linkage.
John McCall033caa52010-10-29 00:29:13 +0000751 if (D->getDeclContext()->isRecord())
John McCall07072662010-11-02 01:45:15 +0000752 return getLVForClassMember(D, Flags);
Douglas Gregorf73b2822009-11-25 22:24:25 +0000753
754 // C++ [basic.link]p6:
755 // The name of a function declared in block scope and the name of
756 // an object declared by a block scope extern declaration have
757 // linkage. If there is a visible declaration of an entity with
758 // linkage having the same name and type, ignoring entities
759 // declared outside the innermost enclosing namespace scope, the
760 // block scope declaration declares that same entity and receives
761 // the linkage of the previous declaration. If there is more than
762 // one such matching entity, the program is ill-formed. Otherwise,
763 // if no matching entity is found, the block scope entity receives
764 // external linkage.
John McCall033caa52010-10-29 00:29:13 +0000765 if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
766 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Eli Friedman839192f2012-01-15 01:23:58 +0000767 if (Function->isInAnonymousNamespace() &&
768 !Function->getDeclContext()->isExternCContext())
John McCallc273f242010-10-30 11:50:40 +0000769 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000770
John McCallc273f242010-10-30 11:50:40 +0000771 LinkageInfo LV;
Douglas Gregorbf62d642010-12-06 18:36:25 +0000772 if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000773 if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
774 LV.setVisibility(*Vis);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000775 }
776
Douglas Gregorec9fd132012-01-14 16:38:05 +0000777 if (const FunctionDecl *Prev = Function->getPreviousDecl()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000778 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallc273f242010-10-30 11:50:40 +0000779 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
780 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000781 }
782
783 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000784 }
785
John McCall033caa52010-10-29 00:29:13 +0000786 if (const VarDecl *Var = dyn_cast<VarDecl>(D))
John McCall8e7d6562010-08-26 03:08:43 +0000787 if (Var->getStorageClass() == SC_Extern ||
788 Var->getStorageClass() == SC_PrivateExtern) {
Eli Friedman839192f2012-01-15 01:23:58 +0000789 if (Var->isInAnonymousNamespace() &&
790 !Var->getDeclContext()->isExternCContext())
John McCallc273f242010-10-30 11:50:40 +0000791 return LinkageInfo::uniqueExternal();
Douglas Gregor7dc5c172010-02-03 09:33:45 +0000792
John McCallc273f242010-10-30 11:50:40 +0000793 LinkageInfo LV;
John McCall457a04e2010-10-22 21:05:15 +0000794 if (Var->getStorageClass() == SC_PrivateExtern)
John McCallc273f242010-10-30 11:50:40 +0000795 LV.setVisibility(HiddenVisibility);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000796 else if (Flags.ConsiderVisibilityAttributes) {
Douglas Gregor1baf38f2011-03-26 12:10:19 +0000797 if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
798 LV.setVisibility(*Vis);
Douglas Gregorbf62d642010-12-06 18:36:25 +0000799 }
800
Douglas Gregorec9fd132012-01-14 16:38:05 +0000801 if (const VarDecl *Prev = Var->getPreviousDecl()) {
Douglas Gregorbf62d642010-12-06 18:36:25 +0000802 LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
John McCallc273f242010-10-30 11:50:40 +0000803 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
804 LV.mergeVisibility(PrevLV);
John McCall457a04e2010-10-22 21:05:15 +0000805 }
806
807 return LV;
Douglas Gregorf73b2822009-11-25 22:24:25 +0000808 }
809 }
810
811 // C++ [basic.link]p6:
812 // Names not covered by these rules have no linkage.
John McCallc273f242010-10-30 11:50:40 +0000813 return LinkageInfo::none();
John McCall457a04e2010-10-22 21:05:15 +0000814}
Douglas Gregorf73b2822009-11-25 22:24:25 +0000815
Douglas Gregor2ada0482009-02-04 17:27:36 +0000816std::string NamedDecl::getQualifiedNameAsString() const {
Anders Carlsson2fb08242009-09-08 18:24:21 +0000817 return getQualifiedNameAsString(getASTContext().getLangOptions());
818}
819
820std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000821 const DeclContext *Ctx = getDeclContext();
822
823 if (Ctx->isFunctionOrMethod())
824 return getNameAsString();
825
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000826 typedef SmallVector<const DeclContext *, 8> ContextsTy;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000827 ContextsTy Contexts;
828
829 // Collect contexts.
830 while (Ctx && isa<NamedDecl>(Ctx)) {
831 Contexts.push_back(Ctx);
832 Ctx = Ctx->getParent();
833 };
834
835 std::string QualName;
836 llvm::raw_string_ostream OS(QualName);
837
838 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
839 I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +0000840 if (const ClassTemplateSpecializationDecl *Spec
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000841 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
Douglas Gregor85673582009-05-18 17:01:57 +0000842 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
843 std::string TemplateArgsStr
844 = TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor1ccc8412010-11-07 23:05:16 +0000845 TemplateArgs.data(),
846 TemplateArgs.size(),
Anders Carlsson2fb08242009-09-08 18:24:21 +0000847 P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000848 OS << Spec->getName() << TemplateArgsStr;
849 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
Sam Weinig07d211e2009-12-24 23:15:03 +0000850 if (ND->isAnonymousNamespace())
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000851 OS << "<anonymous namespace>";
Sam Weinig07d211e2009-12-24 23:15:03 +0000852 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000853 OS << *ND;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000854 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
855 if (!RD->getIdentifier())
856 OS << "<anonymous " << RD->getKindName() << '>';
857 else
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000858 OS << *RD;
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000859 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
Sam Weinigb999f682009-12-28 03:19:38 +0000860 const FunctionProtoType *FT = 0;
861 if (FD->hasWrittenPrototype())
862 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
863
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000864 OS << *FD << '(';
Sam Weinigb999f682009-12-28 03:19:38 +0000865 if (FT) {
Sam Weinigb999f682009-12-28 03:19:38 +0000866 unsigned NumParams = FD->getNumParams();
867 for (unsigned i = 0; i < NumParams; ++i) {
868 if (i)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000869 OS << ", ";
Sam Weinigb999f682009-12-28 03:19:38 +0000870 std::string Param;
871 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000872 OS << Param;
Sam Weinigb999f682009-12-28 03:19:38 +0000873 }
874
875 if (FT->isVariadic()) {
876 if (NumParams > 0)
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000877 OS << ", ";
878 OS << "...";
Sam Weinigb999f682009-12-28 03:19:38 +0000879 }
880 }
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000881 OS << ')';
882 } else {
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000883 OS << *cast<NamedDecl>(*I);
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000884 }
885 OS << "::";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000886 }
887
John McCalla2a3f7d2010-03-16 21:48:18 +0000888 if (getDeclName())
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000889 OS << *this;
John McCalla2a3f7d2010-03-16 21:48:18 +0000890 else
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000891 OS << "<anonymous>";
Douglas Gregor2ada0482009-02-04 17:27:36 +0000892
Benjamin Kramerd76b6982010-04-28 14:33:51 +0000893 return OS.str();
Douglas Gregor2ada0482009-02-04 17:27:36 +0000894}
895
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000896bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000897 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
898
Douglas Gregor889ceb72009-02-03 19:21:40 +0000899 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
900 // We want to keep it, unless it nominates same namespace.
901 if (getKind() == Decl::UsingDirective) {
Douglas Gregor12441b32011-02-25 16:33:46 +0000902 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
903 ->getOriginalNamespace() ==
904 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
905 ->getOriginalNamespace();
Douglas Gregor889ceb72009-02-03 19:21:40 +0000906 }
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000908 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
909 // For function declarations, we keep track of redeclarations.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000910 return FD->getPreviousDecl() == OldD;
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000911
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000912 // For function templates, the underlying function declarations are linked.
913 if (const FunctionTemplateDecl *FunctionTemplate
914 = dyn_cast<FunctionTemplateDecl>(this))
915 if (const FunctionTemplateDecl *OldFunctionTemplate
916 = dyn_cast<FunctionTemplateDecl>(OldD))
917 return FunctionTemplate->getTemplatedDecl()
918 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000919
Steve Naroffc4173fa2009-02-22 19:35:57 +0000920 // For method declarations, we keep track of redeclarations.
921 if (isa<ObjCMethodDecl>(this))
922 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000923
John McCall9f3059a2009-10-09 21:13:30 +0000924 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
925 return true;
926
John McCall3f746822009-11-17 05:59:44 +0000927 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
928 return cast<UsingShadowDecl>(this)->getTargetDecl() ==
929 cast<UsingShadowDecl>(OldD)->getTargetDecl();
930
Douglas Gregora9d87bc2011-02-25 00:36:19 +0000931 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
932 ASTContext &Context = getASTContext();
933 return Context.getCanonicalNestedNameSpecifier(
934 cast<UsingDecl>(this)->getQualifier()) ==
935 Context.getCanonicalNestedNameSpecifier(
936 cast<UsingDecl>(OldD)->getQualifier());
937 }
Argyrios Kyrtzidis4b520072010-11-04 08:48:52 +0000938
Douglas Gregorb59643b2012-01-03 23:26:26 +0000939 // A typedef of an Objective-C class type can replace an Objective-C class
940 // declaration or definition, and vice versa.
941 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
942 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
943 return true;
944
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000945 // For non-function declarations, if the declarations are of the
946 // same kind then this must be a redeclaration, or semantic analysis
947 // would not have given us the new declaration.
948 return this->getKind() == OldD->getKind();
949}
950
Douglas Gregoreddf4332009-02-24 20:03:32 +0000951bool NamedDecl::hasLinkage() const {
Douglas Gregorf73b2822009-11-25 22:24:25 +0000952 return getLinkage() != NoLinkage;
Douglas Gregoreddf4332009-02-24 20:03:32 +0000953}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000954
Anders Carlsson6915bf62009-06-26 06:29:23 +0000955NamedDecl *NamedDecl::getUnderlyingDecl() {
956 NamedDecl *ND = this;
957 while (true) {
John McCall3f746822009-11-17 05:59:44 +0000958 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
Anders Carlsson6915bf62009-06-26 06:29:23 +0000959 ND = UD->getTargetDecl();
960 else if (ObjCCompatibleAliasDecl *AD
961 = dyn_cast<ObjCCompatibleAliasDecl>(ND))
962 return AD->getClassInterface();
963 else
964 return ND;
965 }
966}
967
John McCalla8ae2222010-04-06 21:38:20 +0000968bool NamedDecl::isCXXInstanceMember() const {
969 assert(isCXXClassMember() &&
970 "checking whether non-member is instance member");
971
972 const NamedDecl *D = this;
973 if (isa<UsingShadowDecl>(D))
974 D = cast<UsingShadowDecl>(D)->getTargetDecl();
975
Francois Pichet783dd6e2010-11-21 06:08:52 +0000976 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
John McCalla8ae2222010-04-06 21:38:20 +0000977 return true;
978 if (isa<CXXMethodDecl>(D))
979 return cast<CXXMethodDecl>(D)->isInstance();
980 if (isa<FunctionTemplateDecl>(D))
981 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
982 ->getTemplatedDecl())->isInstance();
983 return false;
984}
985
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +0000986//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000987// DeclaratorDecl Implementation
988//===----------------------------------------------------------------------===//
989
Douglas Gregorec9c6ae2010-07-06 18:42:40 +0000990template <typename DeclT>
991static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
992 if (decl->getNumTemplateParameterLists() > 0)
993 return decl->getTemplateParameterList(0)->getTemplateLoc();
994 else
995 return decl->getInnerLocStart();
996}
997
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000998SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
John McCallf7bcc812010-05-28 23:32:21 +0000999 TypeSourceInfo *TSI = getTypeSourceInfo();
1000 if (TSI) return TSI->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001001 return SourceLocation();
1002}
1003
Douglas Gregor14454802011-02-25 02:25:35 +00001004void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1005 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00001006 // Make sure the extended decl info is allocated.
1007 if (!hasExtInfo()) {
1008 // Save (non-extended) type source info pointer.
1009 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1010 // Allocate external info struct.
1011 DeclInfo = new (getASTContext()) ExtInfo;
1012 // Restore savedTInfo into (extended) decl info.
1013 getExtInfo()->TInfo = savedTInfo;
1014 }
1015 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00001016 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00001017 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00001018 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00001019 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00001020 if (getExtInfo()->NumTemplParamLists == 0) {
1021 // Save type source info pointer.
1022 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1023 // Deallocate the extended decl info.
1024 getASTContext().Deallocate(getExtInfo());
1025 // Restore savedTInfo into (non-extended) decl info.
1026 DeclInfo = savedTInfo;
1027 }
1028 else
1029 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00001030 }
1031 }
1032}
1033
Abramo Bagnara60804e12011-03-18 15:16:37 +00001034void
1035DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1036 unsigned NumTPLists,
1037 TemplateParameterList **TPLists) {
1038 assert(NumTPLists > 0);
1039 // Make sure the extended decl info is allocated.
1040 if (!hasExtInfo()) {
1041 // Save (non-extended) type source info pointer.
1042 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1043 // Allocate external info struct.
1044 DeclInfo = new (getASTContext()) ExtInfo;
1045 // Restore savedTInfo into (extended) decl info.
1046 getExtInfo()->TInfo = savedTInfo;
1047 }
1048 // Set the template parameter lists info.
1049 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1050}
1051
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001052SourceLocation DeclaratorDecl::getOuterLocStart() const {
1053 return getTemplateOrInnerLocStart(this);
1054}
1055
Abramo Bagnaraea947882011-03-08 16:41:52 +00001056namespace {
1057
1058// Helper function: returns true if QT is or contains a type
1059// having a postfix component.
1060bool typeIsPostfix(clang::QualType QT) {
1061 while (true) {
1062 const Type* T = QT.getTypePtr();
1063 switch (T->getTypeClass()) {
1064 default:
1065 return false;
1066 case Type::Pointer:
1067 QT = cast<PointerType>(T)->getPointeeType();
1068 break;
1069 case Type::BlockPointer:
1070 QT = cast<BlockPointerType>(T)->getPointeeType();
1071 break;
1072 case Type::MemberPointer:
1073 QT = cast<MemberPointerType>(T)->getPointeeType();
1074 break;
1075 case Type::LValueReference:
1076 case Type::RValueReference:
1077 QT = cast<ReferenceType>(T)->getPointeeType();
1078 break;
1079 case Type::PackExpansion:
1080 QT = cast<PackExpansionType>(T)->getPattern();
1081 break;
1082 case Type::Paren:
1083 case Type::ConstantArray:
1084 case Type::DependentSizedArray:
1085 case Type::IncompleteArray:
1086 case Type::VariableArray:
1087 case Type::FunctionProto:
1088 case Type::FunctionNoProto:
1089 return true;
1090 }
1091 }
1092}
1093
1094} // namespace
1095
1096SourceRange DeclaratorDecl::getSourceRange() const {
1097 SourceLocation RangeEnd = getLocation();
1098 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1099 if (typeIsPostfix(TInfo->getType()))
1100 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1101 }
1102 return SourceRange(getOuterLocStart(), RangeEnd);
1103}
1104
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001105void
Douglas Gregor20527e22010-06-15 17:44:38 +00001106QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1107 unsigned NumTPLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001108 TemplateParameterList **TPLists) {
1109 assert((NumTPLists == 0 || TPLists != 0) &&
1110 "Empty array of template parameters with positive size!");
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001111
1112 // Free previous template parameters (if any).
1113 if (NumTemplParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001114 Context.Deallocate(TemplParamLists);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001115 TemplParamLists = 0;
1116 NumTemplParamLists = 0;
1117 }
1118 // Set info on matched template parameter lists (if any).
1119 if (NumTPLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00001120 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00001121 NumTemplParamLists = NumTPLists;
1122 for (unsigned i = NumTPLists; i-- > 0; )
1123 TemplParamLists[i] = TPLists[i];
1124 }
1125}
1126
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +00001127//===----------------------------------------------------------------------===//
Nuno Lopes394ec982008-12-17 23:39:55 +00001128// VarDecl Implementation
1129//===----------------------------------------------------------------------===//
1130
Sebastian Redl833ef452010-01-26 22:01:41 +00001131const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1132 switch (SC) {
Peter Collingbourne2dbb7082011-09-19 21:14:35 +00001133 case SC_None: break;
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001134 case SC_Auto: return "auto";
1135 case SC_Extern: return "extern";
1136 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1137 case SC_PrivateExtern: return "__private_extern__";
1138 case SC_Register: return "register";
1139 case SC_Static: return "static";
Sebastian Redl833ef452010-01-26 22:01:41 +00001140 }
1141
Peter Collingbourne9a8f1532011-09-20 12:40:26 +00001142 llvm_unreachable("Invalid storage class");
Sebastian Redl833ef452010-01-26 22:01:41 +00001143}
1144
Abramo Bagnaradff19302011-03-08 08:55:46 +00001145VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1146 SourceLocation StartL, SourceLocation IdL,
John McCallbcd03502009-12-07 02:54:59 +00001147 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001148 StorageClass S, StorageClass SCAsWritten) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001149 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
Nuno Lopes394ec982008-12-17 23:39:55 +00001150}
1151
Douglas Gregor72172e92012-01-05 21:55:30 +00001152VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1153 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1154 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1155 QualType(), 0, SC_None, SC_None);
1156}
1157
Douglas Gregorbf62d642010-12-06 18:36:25 +00001158void VarDecl::setStorageClass(StorageClass SC) {
1159 assert(isLegalForVariable(SC));
1160 if (getStorageClass() != SC)
1161 ClearLinkageCache();
1162
John McCallbeaa11c2011-05-01 02:13:58 +00001163 VarDeclBits.SClass = SC;
Douglas Gregorbf62d642010-12-06 18:36:25 +00001164}
1165
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001166SourceRange VarDecl::getSourceRange() const {
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001167 if (getInit())
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00001168 return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00001169 return DeclaratorDecl::getSourceRange();
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001170}
1171
Sebastian Redl833ef452010-01-26 22:01:41 +00001172bool VarDecl::isExternC() const {
Eli Friedman839192f2012-01-15 01:23:58 +00001173 if (getLinkage() != ExternalLinkage)
Chandler Carruth4322a282011-02-25 00:05:02 +00001174 return false;
1175
Eli Friedman839192f2012-01-15 01:23:58 +00001176 const DeclContext *DC = getDeclContext();
1177 if (DC->isRecord())
1178 return false;
Sebastian Redl833ef452010-01-26 22:01:41 +00001179
Eli Friedman839192f2012-01-15 01:23:58 +00001180 ASTContext &Context = getASTContext();
1181 if (!Context.getLangOptions().CPlusPlus)
1182 return true;
1183 return DC->isExternCContext();
Sebastian Redl833ef452010-01-26 22:01:41 +00001184}
1185
1186VarDecl *VarDecl::getCanonicalDecl() {
1187 return getFirstDeclaration();
1188}
1189
Sebastian Redl35351a92010-01-31 22:27:38 +00001190VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
1191 // C++ [basic.def]p2:
1192 // A declaration is a definition unless [...] it contains the 'extern'
1193 // specifier or a linkage-specification and neither an initializer [...],
1194 // it declares a static data member in a class declaration [...].
1195 // C++ [temp.expl.spec]p15:
1196 // An explicit specialization of a static data member of a template is a
1197 // definition if the declaration includes an initializer; otherwise, it is
1198 // a declaration.
1199 if (isStaticDataMember()) {
1200 if (isOutOfLine() && (hasInit() ||
1201 getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1202 return Definition;
1203 else
1204 return DeclarationOnly;
1205 }
1206 // C99 6.7p5:
1207 // A definition of an identifier is a declaration for that identifier that
1208 // [...] causes storage to be reserved for that object.
1209 // Note: that applies for all non-file-scope objects.
1210 // C99 6.9.2p1:
1211 // If the declaration of an identifier for an object has file scope and an
1212 // initializer, the declaration is an external definition for the identifier
1213 if (hasInit())
1214 return Definition;
1215 // AST for 'extern "C" int foo;' is annotated with 'extern'.
1216 if (hasExternalStorage())
1217 return DeclarationOnly;
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001218
John McCall8e7d6562010-08-26 03:08:43 +00001219 if (getStorageClassAsWritten() == SC_Extern ||
1220 getStorageClassAsWritten() == SC_PrivateExtern) {
Douglas Gregorec9fd132012-01-14 16:38:05 +00001221 for (const VarDecl *PrevVar = getPreviousDecl();
1222 PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
Fariborz Jahaniancc99b3c2010-06-21 16:08:37 +00001223 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1224 return DeclarationOnly;
1225 }
1226 }
Sebastian Redl35351a92010-01-31 22:27:38 +00001227 // C99 6.9.2p2:
1228 // A declaration of an object that has file scope without an initializer,
1229 // and without a storage class specifier or the scs 'static', constitutes
1230 // a tentative definition.
1231 // No such thing in C++.
1232 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
1233 return TentativeDefinition;
1234
1235 // What's left is (in C, block-scope) declarations without initializers or
1236 // external storage. These are definitions.
1237 return Definition;
1238}
1239
Sebastian Redl35351a92010-01-31 22:27:38 +00001240VarDecl *VarDecl::getActingDefinition() {
1241 DefinitionKind Kind = isThisDeclarationADefinition();
1242 if (Kind != TentativeDefinition)
1243 return 0;
1244
Chris Lattner48eb14d2010-06-14 18:31:46 +00001245 VarDecl *LastTentative = 0;
Sebastian Redl35351a92010-01-31 22:27:38 +00001246 VarDecl *First = getFirstDeclaration();
1247 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1248 I != E; ++I) {
1249 Kind = (*I)->isThisDeclarationADefinition();
1250 if (Kind == Definition)
1251 return 0;
1252 else if (Kind == TentativeDefinition)
1253 LastTentative = *I;
1254 }
1255 return LastTentative;
1256}
1257
1258bool VarDecl::isTentativeDefinitionNow() const {
1259 DefinitionKind Kind = isThisDeclarationADefinition();
1260 if (Kind != TentativeDefinition)
1261 return false;
1262
1263 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1264 if ((*I)->isThisDeclarationADefinition() == Definition)
1265 return false;
1266 }
Sebastian Redl5ca79842010-02-01 20:16:42 +00001267 return true;
Sebastian Redl35351a92010-01-31 22:27:38 +00001268}
1269
Sebastian Redl5ca79842010-02-01 20:16:42 +00001270VarDecl *VarDecl::getDefinition() {
Sebastian Redlccdb5ff2010-02-02 17:55:12 +00001271 VarDecl *First = getFirstDeclaration();
1272 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1273 I != E; ++I) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001274 if ((*I)->isThisDeclarationADefinition() == Definition)
1275 return *I;
1276 }
1277 return 0;
1278}
1279
John McCall37bb6c92010-10-29 22:22:43 +00001280VarDecl::DefinitionKind VarDecl::hasDefinition() const {
1281 DefinitionKind Kind = DeclarationOnly;
1282
1283 const VarDecl *First = getFirstDeclaration();
1284 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1285 I != E; ++I)
1286 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
1287
1288 return Kind;
1289}
1290
Sebastian Redl5ca79842010-02-01 20:16:42 +00001291const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
Sebastian Redl833ef452010-01-26 22:01:41 +00001292 redecl_iterator I = redecls_begin(), E = redecls_end();
1293 while (I != E && !I->getInit())
1294 ++I;
1295
1296 if (I != E) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001297 D = *I;
Sebastian Redl833ef452010-01-26 22:01:41 +00001298 return I->getInit();
1299 }
1300 return 0;
1301}
1302
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001303bool VarDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00001304 if (Decl::isOutOfLine())
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001305 return true;
Chandler Carruthf50ef6e2010-02-21 07:08:09 +00001306
1307 if (!isStaticDataMember())
1308 return false;
1309
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001310 // If this static data member was instantiated from a static data member of
1311 // a class template, check whether that static data member was defined
1312 // out-of-line.
1313 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1314 return VD->isOutOfLine();
1315
1316 return false;
1317}
1318
Douglas Gregor1d957a32009-10-27 18:42:08 +00001319VarDecl *VarDecl::getOutOfLineDefinition() {
1320 if (!isStaticDataMember())
1321 return 0;
1322
1323 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1324 RD != RDEnd; ++RD) {
1325 if (RD->getLexicalDeclContext()->isFileContext())
1326 return *RD;
1327 }
1328
1329 return 0;
1330}
1331
Douglas Gregord5058122010-02-11 01:19:42 +00001332void VarDecl::setInit(Expr *I) {
Sebastian Redl833ef452010-01-26 22:01:41 +00001333 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1334 Eval->~EvaluatedStmt();
Douglas Gregord5058122010-02-11 01:19:42 +00001335 getASTContext().Deallocate(Eval);
Sebastian Redl833ef452010-01-26 22:01:41 +00001336 }
1337
1338 Init = I;
1339}
1340
Richard Smith242ad892011-12-21 02:55:12 +00001341bool VarDecl::isUsableInConstantExpressions() const {
1342 const LangOptions &Lang = getASTContext().getLangOptions();
1343
1344 // Only const variables can be used in constant expressions in C++. C++98 does
1345 // not require the variable to be non-volatile, but we consider this to be a
1346 // defect.
1347 if (!Lang.CPlusPlus ||
1348 !getType().isConstQualified() || getType().isVolatileQualified())
1349 return false;
1350
1351 // In C++, const, non-volatile variables of integral or enumeration types
1352 // can be used in constant expressions.
1353 if (getType()->isIntegralOrEnumerationType())
1354 return true;
1355
1356 // Additionally, in C++11, non-volatile constexpr variables and references can
1357 // be used in constant expressions.
1358 return Lang.CPlusPlus0x && (isConstexpr() || getType()->isReferenceType());
1359}
1360
Richard Smithd0b4dd62011-12-19 06:19:21 +00001361/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1362/// form, which contains extra information on the evaluated value of the
1363/// initializer.
1364EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1365 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1366 if (!Eval) {
1367 Stmt *S = Init.get<Stmt *>();
1368 Eval = new (getASTContext()) EvaluatedStmt;
1369 Eval->Value = S;
1370 Init = Eval;
1371 }
1372 return Eval;
1373}
1374
Richard Smithdafff942012-01-14 04:30:29 +00001375APValue *VarDecl::evaluateValue() const {
1376 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1377 return evaluateValue(Notes);
1378}
1379
1380APValue *VarDecl::evaluateValue(
1381 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithd0b4dd62011-12-19 06:19:21 +00001382 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1383
1384 // We only produce notes indicating why an initializer is non-constant the
1385 // first time it is evaluated. FIXME: The notes won't always be emitted the
1386 // first time we try evaluation, so might not be produced at all.
1387 if (Eval->WasEvaluated)
Richard Smithdafff942012-01-14 04:30:29 +00001388 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001389
1390 const Expr *Init = cast<Expr>(Eval->Value);
1391 assert(!Init->isValueDependent());
1392
1393 if (Eval->IsEvaluating) {
1394 // FIXME: Produce a diagnostic for self-initialization.
1395 Eval->CheckedICE = true;
1396 Eval->IsICE = false;
Richard Smithdafff942012-01-14 04:30:29 +00001397 return 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001398 }
1399
1400 Eval->IsEvaluating = true;
1401
1402 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1403 this, Notes);
1404
1405 // Ensure the result is an uninitialized APValue if evaluation fails.
1406 if (!Result)
1407 Eval->Evaluated = APValue();
1408
1409 Eval->IsEvaluating = false;
1410 Eval->WasEvaluated = true;
1411
1412 // In C++11, we have determined whether the initializer was a constant
1413 // expression as a side-effect.
1414 if (getASTContext().getLangOptions().CPlusPlus0x && !Eval->CheckedICE) {
1415 Eval->CheckedICE = true;
Eli Friedman8f66cdf2012-02-06 21:50:18 +00001416 Eval->IsICE = Result && Notes.empty();
Richard Smithd0b4dd62011-12-19 06:19:21 +00001417 }
1418
Richard Smithdafff942012-01-14 04:30:29 +00001419 return Result ? &Eval->Evaluated : 0;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001420}
1421
1422bool VarDecl::checkInitIsICE() const {
John McCalla59dc2f2012-01-05 00:13:19 +00001423 // Initializers of weak variables are never ICEs.
1424 if (isWeak())
1425 return false;
1426
Richard Smithd0b4dd62011-12-19 06:19:21 +00001427 EvaluatedStmt *Eval = ensureEvaluatedStmt();
1428 if (Eval->CheckedICE)
1429 // We have already checked whether this subexpression is an
1430 // integral constant expression.
1431 return Eval->IsICE;
1432
1433 const Expr *Init = cast<Expr>(Eval->Value);
1434 assert(!Init->isValueDependent());
1435
1436 // In C++11, evaluate the initializer to check whether it's a constant
1437 // expression.
1438 if (getASTContext().getLangOptions().CPlusPlus0x) {
1439 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1440 evaluateValue(Notes);
1441 return Eval->IsICE;
1442 }
1443
1444 // It's an ICE whether or not the definition we found is
1445 // out-of-line. See DR 721 and the discussion in Clang PR
1446 // 6206 for details.
1447
1448 if (Eval->CheckingICE)
1449 return false;
1450 Eval->CheckingICE = true;
1451
1452 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1453 Eval->CheckingICE = false;
1454 Eval->CheckedICE = true;
1455 return Eval->IsICE;
1456}
1457
Douglas Gregorfe314812011-06-21 17:03:29 +00001458bool VarDecl::extendsLifetimeOfTemporary() const {
Douglas Gregord410c082011-06-21 18:20:46 +00001459 assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
Douglas Gregorfe314812011-06-21 17:03:29 +00001460
1461 const Expr *E = getInit();
1462 if (!E)
1463 return false;
1464
1465 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1466 E = Cleanups->getSubExpr();
1467
1468 return isa<MaterializeTemporaryExpr>(E);
1469}
1470
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001471VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001472 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001473 return cast<VarDecl>(MSI->getInstantiatedFrom());
1474
1475 return 0;
1476}
1477
Douglas Gregor3c74d412009-10-14 20:14:33 +00001478TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
Sebastian Redl35351a92010-01-31 22:27:38 +00001479 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
Douglas Gregor86d142a2009-10-08 07:24:58 +00001480 return MSI->getTemplateSpecializationKind();
1481
1482 return TSK_Undeclared;
1483}
1484
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00001485MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001486 return getASTContext().getInstantiatedFromStaticDataMember(this);
1487}
1488
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001489void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1490 SourceLocation PointOfInstantiation) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00001491 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00001492 assert(MSI && "Not an instantiated static data member?");
1493 MSI->setTemplateSpecializationKind(TSK);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00001494 if (TSK != TSK_ExplicitSpecialization &&
1495 PointOfInstantiation.isValid() &&
1496 MSI->getPointOfInstantiation().isInvalid())
1497 MSI->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001498}
1499
Sebastian Redl833ef452010-01-26 22:01:41 +00001500//===----------------------------------------------------------------------===//
1501// ParmVarDecl Implementation
1502//===----------------------------------------------------------------------===//
Douglas Gregor0760fa12009-03-10 23:43:53 +00001503
Sebastian Redl833ef452010-01-26 22:01:41 +00001504ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001505 SourceLocation StartLoc,
1506 SourceLocation IdLoc, IdentifierInfo *Id,
Sebastian Redl833ef452010-01-26 22:01:41 +00001507 QualType T, TypeSourceInfo *TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001508 StorageClass S, StorageClass SCAsWritten,
1509 Expr *DefArg) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00001510 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001511 S, SCAsWritten, DefArg);
Douglas Gregor0760fa12009-03-10 23:43:53 +00001512}
1513
Douglas Gregor72172e92012-01-05 21:55:30 +00001514ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1515 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1516 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1517 0, QualType(), 0, SC_None, SC_None, 0);
1518}
1519
Argyrios Kyrtzidis4c6efa622011-07-30 17:23:26 +00001520SourceRange ParmVarDecl::getSourceRange() const {
1521 if (!hasInheritedDefaultArg()) {
1522 SourceRange ArgRange = getDefaultArgRange();
1523 if (ArgRange.isValid())
1524 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1525 }
1526
1527 return DeclaratorDecl::getSourceRange();
1528}
1529
Sebastian Redl833ef452010-01-26 22:01:41 +00001530Expr *ParmVarDecl::getDefaultArg() {
1531 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1532 assert(!hasUninstantiatedDefaultArg() &&
1533 "Default argument is not yet instantiated!");
1534
1535 Expr *Arg = getInit();
John McCall5d413782010-12-06 08:20:24 +00001536 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
Sebastian Redl833ef452010-01-26 22:01:41 +00001537 return E->getSubExpr();
Douglas Gregor0760fa12009-03-10 23:43:53 +00001538
Sebastian Redl833ef452010-01-26 22:01:41 +00001539 return Arg;
1540}
1541
Sebastian Redl833ef452010-01-26 22:01:41 +00001542SourceRange ParmVarDecl::getDefaultArgRange() const {
1543 if (const Expr *E = getInit())
1544 return E->getSourceRange();
1545
1546 if (hasUninstantiatedDefaultArg())
1547 return getUninstantiatedDefaultArg()->getSourceRange();
1548
1549 return SourceRange();
Argyrios Kyrtzidis02dd4f92009-07-05 22:21:56 +00001550}
1551
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001552bool ParmVarDecl::isParameterPack() const {
1553 return isa<PackExpansionType>(getType());
1554}
1555
Ted Kremenek540017e2011-10-06 05:00:56 +00001556void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1557 getASTContext().setParameterIndex(this, parameterIndex);
1558 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1559}
1560
1561unsigned ParmVarDecl::getParameterIndexLarge() const {
1562 return getASTContext().getParameterIndex(this);
1563}
1564
Nuno Lopes394ec982008-12-17 23:39:55 +00001565//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00001566// FunctionDecl Implementation
1567//===----------------------------------------------------------------------===//
1568
Douglas Gregorb11aad82011-02-19 18:51:44 +00001569void FunctionDecl::getNameForDiagnostic(std::string &S,
1570 const PrintingPolicy &Policy,
1571 bool Qualified) const {
1572 NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1573 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1574 if (TemplateArgs)
1575 S += TemplateSpecializationType::PrintTemplateArgumentList(
1576 TemplateArgs->data(),
1577 TemplateArgs->size(),
1578 Policy);
1579
1580}
1581
Ted Kremenek186a0742010-04-29 16:49:01 +00001582bool FunctionDecl::isVariadic() const {
1583 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1584 return FT->isVariadic();
1585 return false;
1586}
1587
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001588bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1589 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Francois Pichet1c229c02011-04-22 22:18:13 +00001590 if (I->Body || I->IsLateTemplateParsed) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001591 Definition = *I;
1592 return true;
1593 }
1594 }
1595
1596 return false;
1597}
1598
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001599bool FunctionDecl::hasTrivialBody() const
1600{
1601 Stmt *S = getBody();
1602 if (!S) {
1603 // Since we don't have a body for this function, we don't know if it's
1604 // trivial or not.
1605 return false;
1606 }
1607
1608 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1609 return true;
1610 return false;
1611}
1612
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001613bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1614 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00001615 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001616 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1617 return true;
1618 }
1619 }
1620
1621 return false;
1622}
1623
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001624Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
Argyrios Kyrtzidis1506d9b2009-07-14 03:20:21 +00001625 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1626 if (I->Body) {
1627 Definition = *I;
1628 return I->Body.get(getASTContext().getExternalSource());
Francois Pichet1c229c02011-04-22 22:18:13 +00001629 } else if (I->IsLateTemplateParsed) {
1630 Definition = *I;
1631 return 0;
Douglas Gregor89f238c2008-04-21 02:02:58 +00001632 }
1633 }
1634
1635 return 0;
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001636}
1637
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001638void FunctionDecl::setBody(Stmt *B) {
1639 Body = B;
Douglas Gregor027ba502010-12-06 17:49:01 +00001640 if (B)
Argyrios Kyrtzidisa3aeb5a2009-06-20 08:09:14 +00001641 EndRangeLoc = B->getLocEnd();
1642}
1643
Douglas Gregor7d9120c2010-09-28 21:55:22 +00001644void FunctionDecl::setPure(bool P) {
1645 IsPure = P;
1646 if (P)
1647 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1648 Parent->markedVirtualFunctionPure();
1649}
1650
Douglas Gregor16618f22009-09-12 00:17:51 +00001651bool FunctionDecl::isMain() const {
John McCall53ffd372011-05-15 17:49:20 +00001652 const TranslationUnitDecl *tunit =
1653 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1654 return tunit &&
Alexis Huntf9933e82011-05-15 20:59:31 +00001655 !tunit->getASTContext().getLangOptions().Freestanding &&
John McCall53ffd372011-05-15 17:49:20 +00001656 getIdentifier() &&
1657 getIdentifier()->isStr("main");
1658}
1659
1660bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1661 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1662 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1663 getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1664 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1665 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1666
1667 if (isa<CXXRecordDecl>(getDeclContext())) return false;
1668 assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1669
1670 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1671 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1672
1673 ASTContext &Context =
1674 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1675 ->getASTContext();
1676
1677 // The result type and first argument type are constant across all
1678 // these operators. The second argument must be exactly void*.
1679 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
Douglas Gregore62c0a42009-02-24 01:23:02 +00001680}
1681
Douglas Gregor16618f22009-09-12 00:17:51 +00001682bool FunctionDecl::isExternC() const {
Eli Friedman839192f2012-01-15 01:23:58 +00001683 if (getLinkage() != ExternalLinkage)
1684 return false;
1685
1686 if (getAttr<OverloadableAttr>())
1687 return false;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001688
Chandler Carruth4322a282011-02-25 00:05:02 +00001689 const DeclContext *DC = getDeclContext();
1690 if (DC->isRecord())
1691 return false;
1692
Eli Friedman839192f2012-01-15 01:23:58 +00001693 ASTContext &Context = getASTContext();
1694 if (!Context.getLangOptions().CPlusPlus)
1695 return true;
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001696
Eli Friedman839192f2012-01-15 01:23:58 +00001697 return isMain() || DC->isExternCContext();
Douglas Gregor5a80bd12009-03-02 00:19:53 +00001698}
1699
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001700bool FunctionDecl::isGlobal() const {
1701 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1702 return Method->isStatic();
1703
John McCall8e7d6562010-08-26 03:08:43 +00001704 if (getStorageClass() == SC_Static)
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001705 return false;
1706
Mike Stump11289f42009-09-09 15:08:12 +00001707 for (const DeclContext *DC = getDeclContext();
Douglas Gregorf1b876d2009-03-31 16:35:03 +00001708 DC->isNamespace();
1709 DC = DC->getParent()) {
1710 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1711 if (!Namespace->getDeclName())
1712 return false;
1713 break;
1714 }
1715 }
1716
1717 return true;
1718}
1719
Sebastian Redl833ef452010-01-26 22:01:41 +00001720void
1721FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1722 redeclarable_base::setPreviousDeclaration(PrevDecl);
1723
1724 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1725 FunctionTemplateDecl *PrevFunTmpl
1726 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1727 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1728 FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1729 }
Douglas Gregorff76cb92010-12-09 16:59:22 +00001730
Axel Naumannfbc7b982011-11-08 18:21:06 +00001731 if (PrevDecl && PrevDecl->IsInline)
Douglas Gregorff76cb92010-12-09 16:59:22 +00001732 IsInline = true;
Sebastian Redl833ef452010-01-26 22:01:41 +00001733}
1734
1735const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1736 return getFirstDeclaration();
1737}
1738
1739FunctionDecl *FunctionDecl::getCanonicalDecl() {
1740 return getFirstDeclaration();
1741}
1742
Douglas Gregorbf62d642010-12-06 18:36:25 +00001743void FunctionDecl::setStorageClass(StorageClass SC) {
1744 assert(isLegalForFunction(SC));
1745 if (getStorageClass() != SC)
1746 ClearLinkageCache();
1747
1748 SClass = SC;
1749}
1750
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001751/// \brief Returns a value indicating whether this function
1752/// corresponds to a builtin function.
1753///
1754/// The function corresponds to a built-in function if it is
1755/// declared at translation scope or within an extern "C" block and
1756/// its name matches with the name of a builtin. The returned value
1757/// will be 0 for functions that do not correspond to a builtin, a
Mike Stump11289f42009-09-09 15:08:12 +00001758/// value of type \c Builtin::ID if in the target-independent range
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001759/// \c [1,Builtin::First), or a target-specific builtin value.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001760unsigned FunctionDecl::getBuiltinID() const {
1761 ASTContext &Context = getASTContext();
Douglas Gregore711f702009-02-14 18:57:46 +00001762 if (!getIdentifier() || !getIdentifier()->getBuiltinID())
1763 return 0;
1764
1765 unsigned BuiltinID = getIdentifier()->getBuiltinID();
1766 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1767 return BuiltinID;
1768
1769 // This function has the name of a known C library
1770 // function. Determine whether it actually refers to the C library
1771 // function or whether it just has the same name.
1772
Douglas Gregora908e7f2009-02-17 03:23:10 +00001773 // If this is a static function, it's not a builtin.
John McCall8e7d6562010-08-26 03:08:43 +00001774 if (getStorageClass() == SC_Static)
Douglas Gregora908e7f2009-02-17 03:23:10 +00001775 return 0;
1776
Douglas Gregore711f702009-02-14 18:57:46 +00001777 // If this function is at translation-unit scope and we're not in
1778 // C++, it refers to the C library function.
1779 if (!Context.getLangOptions().CPlusPlus &&
1780 getDeclContext()->isTranslationUnit())
1781 return BuiltinID;
1782
1783 // If the function is in an extern "C" linkage specification and is
1784 // not marked "overloadable", it's the real function.
1785 if (isa<LinkageSpecDecl>(getDeclContext()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001786 cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
Douglas Gregore711f702009-02-14 18:57:46 +00001787 == LinkageSpecDecl::lang_c &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001788 !getAttr<OverloadableAttr>())
Douglas Gregore711f702009-02-14 18:57:46 +00001789 return BuiltinID;
1790
1791 // Not a builtin
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001792 return 0;
1793}
1794
1795
Chris Lattner47c0d002009-04-25 06:03:53 +00001796/// getNumParams - Return the number of parameters this function must have
Bob Wilsonb39017a2011-01-10 18:23:55 +00001797/// based on its FunctionType. This is the length of the ParamInfo array
Chris Lattner47c0d002009-04-25 06:03:53 +00001798/// after it has been created.
1799unsigned FunctionDecl::getNumParams() const {
John McCall9dd450b2009-09-21 23:43:11 +00001800 const FunctionType *FT = getType()->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001801 if (isa<FunctionNoProtoType>(FT))
Chris Lattner88f70d62008-03-15 05:43:15 +00001802 return 0;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001803 return cast<FunctionProtoType>(FT)->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +00001804
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001805}
1806
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00001807void FunctionDecl::setParams(ASTContext &C,
David Blaikie9c70e042011-09-21 18:16:56 +00001808 llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001809 assert(ParamInfo == 0 && "Already has param info!");
David Blaikie9c70e042011-09-21 18:16:56 +00001810 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +00001811
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001812 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00001813 if (!NewParamInfo.empty()) {
1814 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1815 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Chris Lattner8f5bf2f2007-01-21 19:04:10 +00001816 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00001817}
Chris Lattner41943152007-01-25 04:52:46 +00001818
Chris Lattner58258242008-04-10 02:22:51 +00001819/// getMinRequiredArguments - Returns the minimum number of arguments
1820/// needed to call this function. This may be fewer than the number of
1821/// function parameters, if some of the parameters have default
Douglas Gregor7825bf32011-01-06 22:09:01 +00001822/// arguments (in C++) or the last parameter is a parameter pack.
Chris Lattner58258242008-04-10 02:22:51 +00001823unsigned FunctionDecl::getMinRequiredArguments() const {
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001824 if (!getASTContext().getLangOptions().CPlusPlus)
1825 return getNumParams();
1826
Douglas Gregor7825bf32011-01-06 22:09:01 +00001827 unsigned NumRequiredArgs = getNumParams();
1828
1829 // If the last parameter is a parameter pack, we don't need an argument for
1830 // it.
1831 if (NumRequiredArgs > 0 &&
1832 getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1833 --NumRequiredArgs;
1834
1835 // If this parameter has a default argument, we don't need an argument for
1836 // it.
1837 while (NumRequiredArgs > 0 &&
1838 getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
Chris Lattner58258242008-04-10 02:22:51 +00001839 --NumRequiredArgs;
1840
Douglas Gregor0dd423e2011-01-11 01:52:23 +00001841 // We might have parameter packs before the end. These can't be deduced,
1842 // but they can still handle multiple arguments.
1843 unsigned ArgIdx = NumRequiredArgs;
1844 while (ArgIdx > 0) {
1845 if (getParamDecl(ArgIdx - 1)->isParameterPack())
1846 NumRequiredArgs = ArgIdx;
1847
1848 --ArgIdx;
1849 }
1850
Chris Lattner58258242008-04-10 02:22:51 +00001851 return NumRequiredArgs;
1852}
1853
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001854bool FunctionDecl::isInlined() const {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001855 if (IsInline)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001856 return true;
Anders Carlssoncfb65d72009-12-04 22:35:50 +00001857
1858 if (isa<CXXMethodDecl>(this)) {
1859 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1860 return true;
1861 }
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001862
1863 switch (getTemplateSpecializationKind()) {
1864 case TSK_Undeclared:
1865 case TSK_ExplicitSpecialization:
1866 return false;
1867
1868 case TSK_ImplicitInstantiation:
1869 case TSK_ExplicitInstantiationDeclaration:
1870 case TSK_ExplicitInstantiationDefinition:
1871 // Handle below.
1872 break;
1873 }
1874
1875 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001876 bool HasPattern = false;
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001877 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001878 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001879
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001880 if (HasPattern && PatternDecl)
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001881 return PatternDecl->isInlined();
1882
1883 return false;
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001884}
1885
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001886/// \brief For a function declaration in C or C++, determine whether this
1887/// declaration causes the definition to be externally visible.
1888///
1889/// Determines whether this is the first non-inline redeclaration of an inline
1890/// function in a language where "inline" does not normally require an
1891/// externally visible definition.
1892bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1893 assert(!doesThisDeclarationHaveABody() &&
1894 "Must have a declaration without a body.");
1895
1896 ASTContext &Context = getASTContext();
1897
1898 // In C99 mode, a function may have an inline definition (causing it to
1899 // be deferred) then redeclared later. As a special case, "extern inline"
1900 // is not required to produce an external symbol.
1901 if (Context.getLangOptions().GNUInline || !Context.getLangOptions().C99 ||
1902 Context.getLangOptions().CPlusPlus)
1903 return false;
1904 if (getLinkage() != ExternalLinkage || isInlineSpecified())
1905 return false;
Nick Lewyckyba4cc012011-07-18 07:11:55 +00001906 const FunctionDecl *Definition = 0;
1907 if (hasBody(Definition))
1908 return Definition->isInlined() &&
1909 Definition->isInlineDefinitionExternallyVisible();
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001910 return false;
1911}
1912
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001913/// \brief For an inline function definition in C or C++, determine whether the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001914/// definition will be externally visible.
1915///
1916/// Inline function definitions are always available for inlining optimizations.
1917/// However, depending on the language dialect, declaration specifiers, and
1918/// attributes, the definition of an inline function may or may not be
1919/// "externally" visible to other translation units in the program.
1920///
1921/// In C99, inline definitions are not externally visible by default. However,
Mike Stump13c66702010-01-06 02:05:39 +00001922/// if even one of the global-scope declarations is marked "extern inline", the
Douglas Gregor299d76e2009-09-13 07:46:26 +00001923/// inline definition becomes externally visible (C99 6.7.4p6).
1924///
1925/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
1926/// definition, we use the GNU semantics for inline, which are nearly the
1927/// opposite of C99 semantics. In particular, "inline" by itself will create
1928/// an externally visible symbol, but "extern inline" will not create an
1929/// externally visible symbol.
1930bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001931 assert(doesThisDeclarationHaveABody() && "Must have the function definition");
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001932 assert(isInlined() && "Function must be inline");
Douglas Gregorb7e5c842009-10-27 23:26:40 +00001933 ASTContext &Context = getASTContext();
Douglas Gregor299d76e2009-09-13 07:46:26 +00001934
Rafael Espindolafb2af642011-06-02 16:13:27 +00001935 if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001936 // If it's not the case that both 'inline' and 'extern' are
1937 // specified on the definition, then this inline definition is
1938 // externally visible.
1939 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
1940 return true;
1941
1942 // If any declaration is 'inline' but not 'extern', then this definition
1943 // is externally visible.
Douglas Gregor299d76e2009-09-13 07:46:26 +00001944 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1945 Redecl != RedeclEnd;
1946 ++Redecl) {
Douglas Gregorff76cb92010-12-09 16:59:22 +00001947 if (Redecl->isInlineSpecified() &&
1948 Redecl->getStorageClassAsWritten() != SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00001949 return true;
Douglas Gregorff76cb92010-12-09 16:59:22 +00001950 }
Douglas Gregor299d76e2009-09-13 07:46:26 +00001951
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001952 return false;
Douglas Gregor299d76e2009-09-13 07:46:26 +00001953 }
1954
1955 // C99 6.7.4p6:
1956 // [...] If all of the file scope declarations for a function in a
1957 // translation unit include the inline function specifier without extern,
1958 // then the definition in that translation unit is an inline definition.
1959 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
1960 Redecl != RedeclEnd;
1961 ++Redecl) {
1962 // Only consider file-scope declarations in this test.
1963 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1964 continue;
Eli Friedman94ab9302011-10-11 22:09:24 +00001965
1966 // Only consider explicit declarations; the presence of a builtin for a
1967 // libcall shouldn't affect whether a definition is externally visible.
1968 if (Redecl->isImplicit())
1969 continue;
1970
John McCall8e7d6562010-08-26 03:08:43 +00001971 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
Douglas Gregor299d76e2009-09-13 07:46:26 +00001972 return true; // Not an inline definition
1973 }
1974
1975 // C99 6.7.4p6:
1976 // An inline definition does not provide an external definition for the
1977 // function, and does not forbid an external definition in another
1978 // translation unit.
Douglas Gregor76fe50c2009-04-28 06:37:30 +00001979 return false;
1980}
1981
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001982/// getOverloadedOperator - Which C++ overloaded operator this
1983/// function represents, if any.
1984OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
Douglas Gregor163c5852008-11-18 14:39:36 +00001985 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
1986 return getDeclName().getCXXOverloadedOperator();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001987 else
1988 return OO_None;
1989}
1990
Alexis Huntc88db062010-01-13 09:01:02 +00001991/// getLiteralIdentifier - The literal suffix identifier this function
1992/// represents, if any.
1993const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
1994 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
1995 return getDeclName().getCXXLiteralIdentifier();
1996 else
1997 return 0;
1998}
1999
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002000FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2001 if (TemplateOrSpecialization.isNull())
2002 return TK_NonTemplate;
2003 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2004 return TK_FunctionTemplate;
2005 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2006 return TK_MemberSpecialization;
2007 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2008 return TK_FunctionTemplateSpecialization;
2009 if (TemplateOrSpecialization.is
2010 <DependentFunctionTemplateSpecializationInfo*>())
2011 return TK_DependentFunctionTemplateSpecialization;
2012
David Blaikie83d382b2011-09-23 05:06:16 +00002013 llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
Argyrios Kyrtzidiscb6f3462010-06-22 09:54:51 +00002014}
2015
Douglas Gregord801b062009-10-07 23:56:10 +00002016FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
Douglas Gregor06db9f52009-10-12 20:18:28 +00002017 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
Douglas Gregord801b062009-10-07 23:56:10 +00002018 return cast<FunctionDecl>(Info->getInstantiatedFrom());
2019
2020 return 0;
2021}
2022
Douglas Gregor06db9f52009-10-12 20:18:28 +00002023MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2024 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2025}
2026
Douglas Gregord801b062009-10-07 23:56:10 +00002027void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002028FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2029 FunctionDecl *FD,
Douglas Gregord801b062009-10-07 23:56:10 +00002030 TemplateSpecializationKind TSK) {
2031 assert(TemplateOrSpecialization.isNull() &&
2032 "Member function is already a specialization");
2033 MemberSpecializationInfo *Info
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002034 = new (C) MemberSpecializationInfo(FD, TSK);
Douglas Gregord801b062009-10-07 23:56:10 +00002035 TemplateOrSpecialization = Info;
2036}
2037
Douglas Gregorafca3b42009-10-27 20:53:28 +00002038bool FunctionDecl::isImplicitlyInstantiable() const {
Douglas Gregor69f6a362010-05-17 17:34:56 +00002039 // If the function is invalid, it can't be implicitly instantiated.
2040 if (isInvalidDecl())
Douglas Gregorafca3b42009-10-27 20:53:28 +00002041 return false;
2042
2043 switch (getTemplateSpecializationKind()) {
2044 case TSK_Undeclared:
Douglas Gregorafca3b42009-10-27 20:53:28 +00002045 case TSK_ExplicitInstantiationDefinition:
2046 return false;
2047
2048 case TSK_ImplicitInstantiation:
2049 return true;
2050
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002051 // It is possible to instantiate TSK_ExplicitSpecialization kind
2052 // if the FunctionDecl has a class scope specialization pattern.
2053 case TSK_ExplicitSpecialization:
2054 return getClassScopeSpecializationPattern() != 0;
2055
Douglas Gregorafca3b42009-10-27 20:53:28 +00002056 case TSK_ExplicitInstantiationDeclaration:
2057 // Handled below.
2058 break;
2059 }
2060
2061 // Find the actual template from which we will instantiate.
2062 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002063 bool HasPattern = false;
Douglas Gregorafca3b42009-10-27 20:53:28 +00002064 if (PatternDecl)
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002065 HasPattern = PatternDecl->hasBody(PatternDecl);
Douglas Gregorafca3b42009-10-27 20:53:28 +00002066
2067 // C++0x [temp.explicit]p9:
2068 // Except for inline functions, other explicit instantiation declarations
2069 // have the effect of suppressing the implicit instantiation of the entity
2070 // to which they refer.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002071 if (!HasPattern || !PatternDecl)
Douglas Gregorafca3b42009-10-27 20:53:28 +00002072 return true;
2073
Douglas Gregor583dcaf2009-10-27 21:11:48 +00002074 return PatternDecl->isInlined();
Ted Kremenek85825ae2011-12-01 00:59:17 +00002075}
2076
2077bool FunctionDecl::isTemplateInstantiation() const {
2078 switch (getTemplateSpecializationKind()) {
2079 case TSK_Undeclared:
2080 case TSK_ExplicitSpecialization:
2081 return false;
2082 case TSK_ImplicitInstantiation:
2083 case TSK_ExplicitInstantiationDeclaration:
2084 case TSK_ExplicitInstantiationDefinition:
2085 return true;
2086 }
2087 llvm_unreachable("All TSK values handled.");
2088}
Douglas Gregorafca3b42009-10-27 20:53:28 +00002089
2090FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002091 // Handle class scope explicit specialization special case.
2092 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2093 return getClassScopeSpecializationPattern();
2094
Douglas Gregorafca3b42009-10-27 20:53:28 +00002095 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2096 while (Primary->getInstantiatedFromMemberTemplate()) {
2097 // If we have hit a point where the user provided a specialization of
2098 // this template, we're done looking.
2099 if (Primary->isMemberSpecialization())
2100 break;
2101
2102 Primary = Primary->getInstantiatedFromMemberTemplate();
2103 }
2104
2105 return Primary->getTemplatedDecl();
2106 }
2107
2108 return getInstantiatedFromMemberFunction();
2109}
2110
Douglas Gregor70d83e22009-06-29 17:30:29 +00002111FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
Mike Stump11289f42009-09-09 15:08:12 +00002112 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002113 = TemplateOrSpecialization
2114 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregore8925db2009-06-29 22:39:32 +00002115 return Info->Template.getPointer();
Douglas Gregor70d83e22009-06-29 17:30:29 +00002116 }
2117 return 0;
2118}
2119
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002120FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2121 return getASTContext().getClassScopeSpecializationPattern(this);
2122}
2123
Douglas Gregor70d83e22009-06-29 17:30:29 +00002124const TemplateArgumentList *
2125FunctionDecl::getTemplateSpecializationArgs() const {
Mike Stump11289f42009-09-09 15:08:12 +00002126 if (FunctionTemplateSpecializationInfo *Info
Douglas Gregorcf915552009-10-13 16:30:37 +00002127 = TemplateOrSpecialization
2128 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002129 return Info->TemplateArguments;
2130 }
2131 return 0;
2132}
2133
Argyrios Kyrtzidise9a24432011-09-22 20:07:09 +00002134const ASTTemplateArgumentListInfo *
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002135FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2136 if (FunctionTemplateSpecializationInfo *Info
2137 = TemplateOrSpecialization
2138 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2139 return Info->TemplateArgumentsAsWritten;
2140 }
2141 return 0;
2142}
2143
Mike Stump11289f42009-09-09 15:08:12 +00002144void
Argyrios Kyrtzidisf4bc0d82010-09-08 19:31:22 +00002145FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2146 FunctionTemplateDecl *Template,
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002147 const TemplateArgumentList *TemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002148 void *InsertPos,
Abramo Bagnara02ccd282010-05-20 15:32:11 +00002149 TemplateSpecializationKind TSK,
Argyrios Kyrtzidis927d8e02010-07-05 10:37:55 +00002150 const TemplateArgumentListInfo *TemplateArgsAsWritten,
2151 SourceLocation PointOfInstantiation) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002152 assert(TSK != TSK_Undeclared &&
2153 "Must specify the type of function template specialization");
Mike Stump11289f42009-09-09 15:08:12 +00002154 FunctionTemplateSpecializationInfo *Info
Douglas Gregor70d83e22009-06-29 17:30:29 +00002155 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002156 if (!Info)
Argyrios Kyrtzidise262a952010-09-09 11:28:23 +00002157 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2158 TemplateArgs,
2159 TemplateArgsAsWritten,
2160 PointOfInstantiation);
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002161 TemplateOrSpecialization = Info;
Mike Stump11289f42009-09-09 15:08:12 +00002162
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002163 // Insert this function template specialization into the set of known
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002164 // function template specializations.
2165 if (InsertPos)
Sebastian Redl9ab988f2011-04-14 14:07:59 +00002166 Template->addSpecialization(Info, InsertPos);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002167 else {
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002168 // Try to insert the new node. If there is an existing node, leave it, the
2169 // set will contain the canonical decls while
2170 // FunctionTemplateDecl::findSpecialization will return
2171 // the most recent redeclarations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002172 FunctionTemplateSpecializationInfo *Existing
2173 = Template->getSpecializations().GetOrInsertNode(Info);
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00002174 (void)Existing;
2175 assert((!Existing || Existing->Function->isCanonicalDecl()) &&
2176 "Set is supposed to only contain canonical decls");
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00002177 }
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00002178}
2179
John McCallb9c78482010-04-08 09:05:18 +00002180void
2181FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2182 const UnresolvedSetImpl &Templates,
2183 const TemplateArgumentListInfo &TemplateArgs) {
2184 assert(TemplateOrSpecialization.isNull());
2185 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2186 Size += Templates.size() * sizeof(FunctionTemplateDecl*);
John McCall900d9802010-04-13 22:18:28 +00002187 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
John McCallb9c78482010-04-08 09:05:18 +00002188 void *Buffer = Context.Allocate(Size);
2189 DependentFunctionTemplateSpecializationInfo *Info =
2190 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2191 TemplateArgs);
2192 TemplateOrSpecialization = Info;
2193}
2194
2195DependentFunctionTemplateSpecializationInfo::
2196DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2197 const TemplateArgumentListInfo &TArgs)
2198 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2199
2200 d.NumTemplates = Ts.size();
2201 d.NumArgs = TArgs.size();
2202
2203 FunctionTemplateDecl **TsArray =
2204 const_cast<FunctionTemplateDecl**>(getTemplates());
2205 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2206 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2207
2208 TemplateArgumentLoc *ArgsArray =
2209 const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2210 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2211 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2212}
2213
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002214TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
Mike Stump11289f42009-09-09 15:08:12 +00002215 // For a function template specialization, query the specialization
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002216 // information object.
Douglas Gregord801b062009-10-07 23:56:10 +00002217 FunctionTemplateSpecializationInfo *FTSInfo
Douglas Gregore8925db2009-06-29 22:39:32 +00002218 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
Douglas Gregord801b062009-10-07 23:56:10 +00002219 if (FTSInfo)
2220 return FTSInfo->getTemplateSpecializationKind();
Mike Stump11289f42009-09-09 15:08:12 +00002221
Douglas Gregord801b062009-10-07 23:56:10 +00002222 MemberSpecializationInfo *MSInfo
2223 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2224 if (MSInfo)
2225 return MSInfo->getTemplateSpecializationKind();
2226
2227 return TSK_Undeclared;
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002228}
2229
Mike Stump11289f42009-09-09 15:08:12 +00002230void
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002231FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2232 SourceLocation PointOfInstantiation) {
2233 if (FunctionTemplateSpecializationInfo *FTSInfo
2234 = TemplateOrSpecialization.dyn_cast<
2235 FunctionTemplateSpecializationInfo*>()) {
2236 FTSInfo->setTemplateSpecializationKind(TSK);
2237 if (TSK != TSK_ExplicitSpecialization &&
2238 PointOfInstantiation.isValid() &&
2239 FTSInfo->getPointOfInstantiation().isInvalid())
2240 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2241 } else if (MemberSpecializationInfo *MSInfo
2242 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2243 MSInfo->setTemplateSpecializationKind(TSK);
2244 if (TSK != TSK_ExplicitSpecialization &&
2245 PointOfInstantiation.isValid() &&
2246 MSInfo->getPointOfInstantiation().isInvalid())
2247 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2248 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002249 llvm_unreachable("Function cannot have a template specialization kind");
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002250}
2251
2252SourceLocation FunctionDecl::getPointOfInstantiation() const {
Douglas Gregord801b062009-10-07 23:56:10 +00002253 if (FunctionTemplateSpecializationInfo *FTSInfo
2254 = TemplateOrSpecialization.dyn_cast<
2255 FunctionTemplateSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002256 return FTSInfo->getPointOfInstantiation();
Douglas Gregord801b062009-10-07 23:56:10 +00002257 else if (MemberSpecializationInfo *MSInfo
2258 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00002259 return MSInfo->getPointOfInstantiation();
2260
2261 return SourceLocation();
Douglas Gregore8925db2009-06-29 22:39:32 +00002262}
2263
Douglas Gregor6411b922009-09-11 20:15:17 +00002264bool FunctionDecl::isOutOfLine() const {
Douglas Gregorb11aad82011-02-19 18:51:44 +00002265 if (Decl::isOutOfLine())
Douglas Gregor6411b922009-09-11 20:15:17 +00002266 return true;
2267
2268 // If this function was instantiated from a member function of a
2269 // class template, check whether that member function was defined out-of-line.
2270 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2271 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002272 if (FD->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002273 return Definition->isOutOfLine();
2274 }
2275
2276 // If this function was instantiated from a function template,
2277 // check whether that function template was defined out-of-line.
2278 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2279 const FunctionDecl *Definition;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002280 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
Douglas Gregor6411b922009-09-11 20:15:17 +00002281 return Definition->isOutOfLine();
2282 }
2283
2284 return false;
2285}
2286
Abramo Bagnaraea947882011-03-08 16:41:52 +00002287SourceRange FunctionDecl::getSourceRange() const {
2288 return SourceRange(getOuterLocStart(), EndRangeLoc);
2289}
2290
Anna Zaks28db7ce2012-01-18 02:45:01 +00002291unsigned FunctionDecl::getMemoryFunctionKind() const {
Anna Zaks201d4892012-01-13 21:52:01 +00002292 IdentifierInfo *FnInfo = getIdentifier();
2293
2294 if (!FnInfo)
Anna Zaks22122702012-01-17 00:37:07 +00002295 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002296
2297 // Builtin handling.
2298 switch (getBuiltinID()) {
2299 case Builtin::BI__builtin_memset:
2300 case Builtin::BI__builtin___memset_chk:
2301 case Builtin::BImemset:
Anna Zaks22122702012-01-17 00:37:07 +00002302 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002303
2304 case Builtin::BI__builtin_memcpy:
2305 case Builtin::BI__builtin___memcpy_chk:
2306 case Builtin::BImemcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002307 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002308
2309 case Builtin::BI__builtin_memmove:
2310 case Builtin::BI__builtin___memmove_chk:
2311 case Builtin::BImemmove:
Anna Zaks22122702012-01-17 00:37:07 +00002312 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002313
2314 case Builtin::BIstrlcpy:
Anna Zaks22122702012-01-17 00:37:07 +00002315 return Builtin::BIstrlcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002316 case Builtin::BIstrlcat:
Anna Zaks22122702012-01-17 00:37:07 +00002317 return Builtin::BIstrlcat;
Anna Zaks201d4892012-01-13 21:52:01 +00002318
2319 case Builtin::BI__builtin_memcmp:
Anna Zaks22122702012-01-17 00:37:07 +00002320 case Builtin::BImemcmp:
2321 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002322
2323 case Builtin::BI__builtin_strncpy:
2324 case Builtin::BI__builtin___strncpy_chk:
2325 case Builtin::BIstrncpy:
Anna Zaks22122702012-01-17 00:37:07 +00002326 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002327
2328 case Builtin::BI__builtin_strncmp:
Anna Zaks22122702012-01-17 00:37:07 +00002329 case Builtin::BIstrncmp:
2330 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002331
2332 case Builtin::BI__builtin_strncasecmp:
Anna Zaks22122702012-01-17 00:37:07 +00002333 case Builtin::BIstrncasecmp:
2334 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002335
2336 case Builtin::BI__builtin_strncat:
Anna Zaks314cd092012-02-01 19:08:57 +00002337 case Builtin::BI__builtin___strncat_chk:
Anna Zaks201d4892012-01-13 21:52:01 +00002338 case Builtin::BIstrncat:
Anna Zaks22122702012-01-17 00:37:07 +00002339 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002340
2341 case Builtin::BI__builtin_strndup:
2342 case Builtin::BIstrndup:
Anna Zaks22122702012-01-17 00:37:07 +00002343 return Builtin::BIstrndup;
Anna Zaks201d4892012-01-13 21:52:01 +00002344
Anna Zaks314cd092012-02-01 19:08:57 +00002345 case Builtin::BI__builtin_strlen:
2346 case Builtin::BIstrlen:
2347 return Builtin::BIstrlen;
2348
Anna Zaks201d4892012-01-13 21:52:01 +00002349 default:
Eli Friedman839192f2012-01-15 01:23:58 +00002350 if (isExternC()) {
Anna Zaks201d4892012-01-13 21:52:01 +00002351 if (FnInfo->isStr("memset"))
Anna Zaks22122702012-01-17 00:37:07 +00002352 return Builtin::BImemset;
Anna Zaks201d4892012-01-13 21:52:01 +00002353 else if (FnInfo->isStr("memcpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002354 return Builtin::BImemcpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002355 else if (FnInfo->isStr("memmove"))
Anna Zaks22122702012-01-17 00:37:07 +00002356 return Builtin::BImemmove;
Anna Zaks201d4892012-01-13 21:52:01 +00002357 else if (FnInfo->isStr("memcmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002358 return Builtin::BImemcmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002359 else if (FnInfo->isStr("strncpy"))
Anna Zaks22122702012-01-17 00:37:07 +00002360 return Builtin::BIstrncpy;
Anna Zaks201d4892012-01-13 21:52:01 +00002361 else if (FnInfo->isStr("strncmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002362 return Builtin::BIstrncmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002363 else if (FnInfo->isStr("strncasecmp"))
Anna Zaks22122702012-01-17 00:37:07 +00002364 return Builtin::BIstrncasecmp;
Anna Zaks201d4892012-01-13 21:52:01 +00002365 else if (FnInfo->isStr("strncat"))
Anna Zaks22122702012-01-17 00:37:07 +00002366 return Builtin::BIstrncat;
Anna Zaks201d4892012-01-13 21:52:01 +00002367 else if (FnInfo->isStr("strndup"))
Anna Zaks22122702012-01-17 00:37:07 +00002368 return Builtin::BIstrndup;
Anna Zaks314cd092012-02-01 19:08:57 +00002369 else if (FnInfo->isStr("strlen"))
2370 return Builtin::BIstrlen;
Anna Zaks201d4892012-01-13 21:52:01 +00002371 }
2372 break;
2373 }
Anna Zaks22122702012-01-17 00:37:07 +00002374 return 0;
Anna Zaks201d4892012-01-13 21:52:01 +00002375}
2376
Chris Lattner59a25942008-03-31 00:36:02 +00002377//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002378// FieldDecl Implementation
2379//===----------------------------------------------------------------------===//
2380
Jay Foad39c79802011-01-12 09:06:06 +00002381FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002382 SourceLocation StartLoc, SourceLocation IdLoc,
2383 IdentifierInfo *Id, QualType T,
Richard Smith938f40b2011-06-11 17:19:42 +00002384 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2385 bool HasInit) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002386 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
Richard Smith938f40b2011-06-11 17:19:42 +00002387 BW, Mutable, HasInit);
Sebastian Redl833ef452010-01-26 22:01:41 +00002388}
2389
Douglas Gregor72172e92012-01-05 21:55:30 +00002390FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2391 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2392 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2393 0, QualType(), 0, 0, false, false);
2394}
2395
Sebastian Redl833ef452010-01-26 22:01:41 +00002396bool FieldDecl::isAnonymousStructOrUnion() const {
2397 if (!isImplicit() || getDeclName())
2398 return false;
2399
2400 if (const RecordType *Record = getType()->getAs<RecordType>())
2401 return Record->getDecl()->isAnonymousStructOrUnion();
2402
2403 return false;
2404}
2405
Richard Smithcaf33902011-10-10 18:28:20 +00002406unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2407 assert(isBitField() && "not a bitfield");
2408 Expr *BitWidth = InitializerOrBitWidth.getPointer();
2409 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2410}
2411
John McCall4e819612011-01-20 07:57:12 +00002412unsigned FieldDecl::getFieldIndex() const {
2413 if (CachedFieldIndex) return CachedFieldIndex - 1;
2414
Richard Smithd62306a2011-11-10 06:34:14 +00002415 unsigned Index = 0;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002416 const RecordDecl *RD = getParent();
2417 const FieldDecl *LastFD = 0;
2418 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
Richard Smithd62306a2011-11-10 06:34:14 +00002419
2420 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2421 I != E; ++I, ++Index) {
2422 (*I)->CachedFieldIndex = Index + 1;
John McCall4e819612011-01-20 07:57:12 +00002423
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002424 if (IsMsStruct) {
2425 // Zero-length bitfields following non-bitfield members are ignored.
Richard Smithd62306a2011-11-10 06:34:14 +00002426 if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
2427 --Index;
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002428 continue;
2429 }
Richard Smithd62306a2011-11-10 06:34:14 +00002430 LastFD = (*I);
Fariborz Jahanian8409bce42011-04-28 22:49:46 +00002431 }
John McCall4e819612011-01-20 07:57:12 +00002432 }
2433
Richard Smithd62306a2011-11-10 06:34:14 +00002434 assert(CachedFieldIndex && "failed to find field in parent");
2435 return CachedFieldIndex - 1;
John McCall4e819612011-01-20 07:57:12 +00002436}
2437
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002438SourceRange FieldDecl::getSourceRange() const {
Abramo Bagnaraff371ac2011-08-05 08:02:55 +00002439 if (const Expr *E = InitializerOrBitWidth.getPointer())
2440 return SourceRange(getInnerLocStart(), E->getLocEnd());
Abramo Bagnaraea947882011-03-08 16:41:52 +00002441 return DeclaratorDecl::getSourceRange();
Abramo Bagnara20c9e242011-03-08 11:07:11 +00002442}
2443
Richard Smith938f40b2011-06-11 17:19:42 +00002444void FieldDecl::setInClassInitializer(Expr *Init) {
2445 assert(!InitializerOrBitWidth.getPointer() &&
2446 "bit width or initializer already set");
2447 InitializerOrBitWidth.setPointer(Init);
2448 InitializerOrBitWidth.setInt(0);
2449}
2450
Sebastian Redl833ef452010-01-26 22:01:41 +00002451//===----------------------------------------------------------------------===//
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002452// TagDecl Implementation
Ted Kremenek21475702008-09-05 17:16:31 +00002453//===----------------------------------------------------------------------===//
2454
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002455SourceLocation TagDecl::getOuterLocStart() const {
2456 return getTemplateOrInnerLocStart(this);
2457}
2458
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002459SourceRange TagDecl::getSourceRange() const {
2460 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
Douglas Gregorec9c6ae2010-07-06 18:42:40 +00002461 return SourceRange(getOuterLocStart(), E);
Argyrios Kyrtzidis575fa052009-07-14 03:17:17 +00002462}
2463
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002464TagDecl* TagDecl::getCanonicalDecl() {
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002465 return getFirstDeclaration();
Argyrios Kyrtzidis5614aef2009-07-18 00:34:07 +00002466}
2467
Richard Smithdda56e42011-04-15 14:24:37 +00002468void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2469 TypedefNameDeclOrQualifier = TDD;
Douglas Gregora72a4e32010-05-19 18:39:18 +00002470 if (TypeForDecl)
John McCall424cec92011-01-19 06:33:43 +00002471 const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
Douglas Gregorbf62d642010-12-06 18:36:25 +00002472 ClearLinkageCache();
Douglas Gregora72a4e32010-05-19 18:39:18 +00002473}
2474
Douglas Gregordee1be82009-01-17 00:42:38 +00002475void TagDecl::startDefinition() {
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002476 IsBeingDefined = true;
John McCall67da35c2010-02-04 22:26:26 +00002477
2478 if (isa<CXXRecordDecl>(this)) {
2479 CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2480 struct CXXRecordDecl::DefinitionData *Data =
2481 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
John McCall93cc7322010-03-26 21:56:38 +00002482 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2483 cast<CXXRecordDecl>(*I)->DefinitionData = Data;
John McCall67da35c2010-02-04 22:26:26 +00002484 }
Douglas Gregordee1be82009-01-17 00:42:38 +00002485}
2486
2487void TagDecl::completeDefinition() {
John McCallae580fe2010-02-05 01:33:36 +00002488 assert((!isa<CXXRecordDecl>(this) ||
2489 cast<CXXRecordDecl>(this)->hasDefinition()) &&
2490 "definition completed but not started");
2491
John McCallf937c022011-10-07 06:10:15 +00002492 IsCompleteDefinition = true;
Sebastian Redl9d8854e2010-08-02 18:27:05 +00002493 IsBeingDefined = false;
Argyrios Kyrtzidisd170d842010-10-24 17:26:50 +00002494
2495 if (ASTMutationListener *L = getASTMutationListener())
2496 L->CompletedTagDefinition(this);
Douglas Gregordee1be82009-01-17 00:42:38 +00002497}
2498
John McCallf937c022011-10-07 06:10:15 +00002499TagDecl *TagDecl::getDefinition() const {
2500 if (isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002501 return const_cast<TagDecl *>(this);
Andrew Trickba266ee2010-10-19 21:54:32 +00002502 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2503 return CXXRD->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002504
2505 for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002506 R != REnd; ++R)
John McCallf937c022011-10-07 06:10:15 +00002507 if (R->isCompleteDefinition())
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002508 return *R;
Mike Stump11289f42009-09-09 15:08:12 +00002509
Douglas Gregorb6b8f9e2009-07-29 23:36:44 +00002510 return 0;
Ted Kremenek21475702008-09-05 17:16:31 +00002511}
2512
Douglas Gregor14454802011-02-25 02:25:35 +00002513void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2514 if (QualifierLoc) {
John McCall3e11ebe2010-03-15 10:12:16 +00002515 // Make sure the extended qualifier info is allocated.
2516 if (!hasExtInfo())
Richard Smithdda56e42011-04-15 14:24:37 +00002517 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
John McCall3e11ebe2010-03-15 10:12:16 +00002518 // Set qualifier info.
Douglas Gregor14454802011-02-25 02:25:35 +00002519 getExtInfo()->QualifierLoc = QualifierLoc;
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002520 } else {
John McCall3e11ebe2010-03-15 10:12:16 +00002521 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
John McCall3e11ebe2010-03-15 10:12:16 +00002522 if (hasExtInfo()) {
Abramo Bagnara60804e12011-03-18 15:16:37 +00002523 if (getExtInfo()->NumTemplParamLists == 0) {
2524 getASTContext().Deallocate(getExtInfo());
Richard Smithdda56e42011-04-15 14:24:37 +00002525 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002526 }
2527 else
2528 getExtInfo()->QualifierLoc = QualifierLoc;
John McCall3e11ebe2010-03-15 10:12:16 +00002529 }
2530 }
2531}
2532
Abramo Bagnara60804e12011-03-18 15:16:37 +00002533void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2534 unsigned NumTPLists,
2535 TemplateParameterList **TPLists) {
2536 assert(NumTPLists > 0);
2537 // Make sure the extended decl info is allocated.
2538 if (!hasExtInfo())
2539 // Allocate external info struct.
Richard Smithdda56e42011-04-15 14:24:37 +00002540 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
Abramo Bagnara60804e12011-03-18 15:16:37 +00002541 // Set the template parameter lists info.
2542 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2543}
2544
Ted Kremenek21475702008-09-05 17:16:31 +00002545//===----------------------------------------------------------------------===//
Sebastian Redl833ef452010-01-26 22:01:41 +00002546// EnumDecl Implementation
2547//===----------------------------------------------------------------------===//
2548
David Blaikie68e081d2011-12-20 02:48:34 +00002549void EnumDecl::anchor() { }
2550
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002551EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2552 SourceLocation StartLoc, SourceLocation IdLoc,
2553 IdentifierInfo *Id,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002554 EnumDecl *PrevDecl, bool IsScoped,
2555 bool IsScopedUsingClassTag, bool IsFixed) {
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002556 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
Abramo Bagnara0e05e242010-12-03 18:54:17 +00002557 IsScoped, IsScopedUsingClassTag, IsFixed);
Sebastian Redl833ef452010-01-26 22:01:41 +00002558 C.getTypeDeclType(Enum, PrevDecl);
2559 return Enum;
2560}
2561
Douglas Gregor72172e92012-01-05 21:55:30 +00002562EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2563 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2564 return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2565 false, false, false);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002566}
2567
Douglas Gregord5058122010-02-11 01:19:42 +00002568void EnumDecl::completeDefinition(QualType NewType,
John McCall9aa35be2010-05-06 08:49:23 +00002569 QualType NewPromotionType,
2570 unsigned NumPositiveBits,
2571 unsigned NumNegativeBits) {
John McCallf937c022011-10-07 06:10:15 +00002572 assert(!isCompleteDefinition() && "Cannot redefine enums!");
Douglas Gregor0bf31402010-10-08 23:50:27 +00002573 if (!IntegerType)
2574 IntegerType = NewType.getTypePtr();
Sebastian Redl833ef452010-01-26 22:01:41 +00002575 PromotionType = NewPromotionType;
John McCall9aa35be2010-05-06 08:49:23 +00002576 setNumPositiveBits(NumPositiveBits);
2577 setNumNegativeBits(NumNegativeBits);
Sebastian Redl833ef452010-01-26 22:01:41 +00002578 TagDecl::completeDefinition();
2579}
2580
2581//===----------------------------------------------------------------------===//
Chris Lattner59a25942008-03-31 00:36:02 +00002582// RecordDecl Implementation
2583//===----------------------------------------------------------------------===//
Chris Lattner41943152007-01-25 04:52:46 +00002584
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002585RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2586 SourceLocation StartLoc, SourceLocation IdLoc,
2587 IdentifierInfo *Id, RecordDecl *PrevDecl)
2588 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
Ted Kremenek52baf502008-09-02 21:12:32 +00002589 HasFlexibleArrayMember = false;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002590 AnonymousStructOrUnion = false;
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +00002591 HasObjectMember = false;
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002592 LoadedFieldsFromExternalStorage = false;
Ted Kremenek52baf502008-09-02 21:12:32 +00002593 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
Ted Kremenek52baf502008-09-02 21:12:32 +00002594}
2595
Jay Foad39c79802011-01-12 09:06:06 +00002596RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002597 SourceLocation StartLoc, SourceLocation IdLoc,
2598 IdentifierInfo *Id, RecordDecl* PrevDecl) {
2599 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2600 PrevDecl);
Ted Kremenek21475702008-09-05 17:16:31 +00002601 C.getTypeDeclType(R, PrevDecl);
2602 return R;
Ted Kremenek52baf502008-09-02 21:12:32 +00002603}
2604
Douglas Gregor72172e92012-01-05 21:55:30 +00002605RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2606 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
2607 return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2608 SourceLocation(), 0, 0);
Argyrios Kyrtzidis39f0e302010-07-02 11:54:55 +00002609}
2610
Douglas Gregordfcad112009-03-25 15:59:44 +00002611bool RecordDecl::isInjectedClassName() const {
Mike Stump11289f42009-09-09 15:08:12 +00002612 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
Douglas Gregordfcad112009-03-25 15:59:44 +00002613 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2614}
2615
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002616RecordDecl::field_iterator RecordDecl::field_begin() const {
2617 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2618 LoadFieldsFromExternalStorage();
2619
2620 return field_iterator(decl_iterator(FirstDecl));
2621}
2622
Douglas Gregorb11aad82011-02-19 18:51:44 +00002623/// completeDefinition - Notes that the definition of this type is now
2624/// complete.
2625void RecordDecl::completeDefinition() {
John McCallf937c022011-10-07 06:10:15 +00002626 assert(!isCompleteDefinition() && "Cannot redefine record!");
Douglas Gregorb11aad82011-02-19 18:51:44 +00002627 TagDecl::completeDefinition();
2628}
2629
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002630void RecordDecl::LoadFieldsFromExternalStorage() const {
2631 ExternalASTSource *Source = getASTContext().getExternalSource();
2632 assert(hasExternalLexicalStorage() && Source && "No external storage?");
2633
2634 // Notify that we have a RecordDecl doing some initialization.
2635 ExternalASTSource::Deserializing TheFields(Source);
2636
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002637 SmallVector<Decl*, 64> Decls;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002638 LoadedFieldsFromExternalStorage = true;
2639 switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2640 case ELR_Success:
2641 break;
2642
2643 case ELR_AlreadyLoaded:
2644 case ELR_Failure:
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002645 return;
Douglas Gregor3d0adb32011-07-15 21:46:17 +00002646 }
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002647
2648#ifndef NDEBUG
2649 // Check that all decls we got were FieldDecls.
2650 for (unsigned i=0, e=Decls.size(); i != e; ++i)
2651 assert(isa<FieldDecl>(Decls[i]));
2652#endif
2653
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002654 if (Decls.empty())
2655 return;
2656
Argyrios Kyrtzidis094da732011-10-07 21:55:43 +00002657 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2658 /*FieldsAlreadyLoaded=*/false);
Argyrios Kyrtzidis0e88a562010-10-14 20:14:34 +00002659}
2660
Steve Naroff415d3d52008-10-08 17:01:13 +00002661//===----------------------------------------------------------------------===//
2662// BlockDecl Implementation
2663//===----------------------------------------------------------------------===//
2664
David Blaikie9c70e042011-09-21 18:16:56 +00002665void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
Steve Naroffc4b30e52009-03-13 16:56:44 +00002666 assert(ParamInfo == 0 && "Already has param info!");
Mike Stump11289f42009-09-09 15:08:12 +00002667
Steve Naroffc4b30e52009-03-13 16:56:44 +00002668 // Zero params -> null pointer.
David Blaikie9c70e042011-09-21 18:16:56 +00002669 if (!NewParamInfo.empty()) {
2670 NumParams = NewParamInfo.size();
2671 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2672 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002673 }
2674}
2675
John McCall351762c2011-02-07 10:33:21 +00002676void BlockDecl::setCaptures(ASTContext &Context,
2677 const Capture *begin,
2678 const Capture *end,
2679 bool capturesCXXThis) {
John McCallc63de662011-02-02 13:00:07 +00002680 CapturesCXXThis = capturesCXXThis;
2681
2682 if (begin == end) {
John McCall351762c2011-02-07 10:33:21 +00002683 NumCaptures = 0;
2684 Captures = 0;
John McCallc63de662011-02-02 13:00:07 +00002685 return;
2686 }
2687
John McCall351762c2011-02-07 10:33:21 +00002688 NumCaptures = end - begin;
2689
2690 // Avoid new Capture[] because we don't want to provide a default
2691 // constructor.
2692 size_t allocationSize = NumCaptures * sizeof(Capture);
2693 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2694 memcpy(buffer, begin, allocationSize);
2695 Captures = static_cast<Capture*>(buffer);
Steve Naroffc4b30e52009-03-13 16:56:44 +00002696}
Sebastian Redl833ef452010-01-26 22:01:41 +00002697
John McCallce45f882011-06-15 22:51:16 +00002698bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2699 for (capture_const_iterator
2700 i = capture_begin(), e = capture_end(); i != e; ++i)
2701 // Only auto vars can be captured, so no redeclaration worries.
2702 if (i->getVariable() == variable)
2703 return true;
2704
2705 return false;
2706}
2707
Douglas Gregor70226da2010-12-21 16:27:07 +00002708SourceRange BlockDecl::getSourceRange() const {
2709 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2710}
Sebastian Redl833ef452010-01-26 22:01:41 +00002711
2712//===----------------------------------------------------------------------===//
2713// Other Decl Allocation/Deallocation Method Implementations
2714//===----------------------------------------------------------------------===//
2715
David Blaikie68e081d2011-12-20 02:48:34 +00002716void TranslationUnitDecl::anchor() { }
2717
Sebastian Redl833ef452010-01-26 22:01:41 +00002718TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2719 return new (C) TranslationUnitDecl(C);
2720}
2721
David Blaikie68e081d2011-12-20 02:48:34 +00002722void LabelDecl::anchor() { }
2723
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002724LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara1c3af962011-03-05 18:21:20 +00002725 SourceLocation IdentL, IdentifierInfo *II) {
2726 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2727}
2728
2729LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2730 SourceLocation IdentL, IdentifierInfo *II,
2731 SourceLocation GnuLabelL) {
2732 assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2733 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
Chris Lattnerc8e630e2011-02-17 07:39:24 +00002734}
2735
Douglas Gregor72172e92012-01-05 21:55:30 +00002736LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2737 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
2738 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
Douglas Gregor417e87c2010-10-27 19:49:05 +00002739}
2740
David Blaikie68e081d2011-12-20 02:48:34 +00002741void ValueDecl::anchor() { }
2742
2743void ImplicitParamDecl::anchor() { }
2744
Sebastian Redl833ef452010-01-26 22:01:41 +00002745ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002746 SourceLocation IdLoc,
2747 IdentifierInfo *Id,
2748 QualType Type) {
2749 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
Sebastian Redl833ef452010-01-26 22:01:41 +00002750}
2751
Douglas Gregor72172e92012-01-05 21:55:30 +00002752ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
2753 unsigned ID) {
2754 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
2755 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
2756}
2757
Sebastian Redl833ef452010-01-26 22:01:41 +00002758FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002759 SourceLocation StartLoc,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002760 const DeclarationNameInfo &NameInfo,
2761 QualType T, TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002762 StorageClass SC, StorageClass SCAsWritten,
Douglas Gregorff76cb92010-12-09 16:59:22 +00002763 bool isInlineSpecified,
Richard Smitha77a0a62011-08-15 21:04:07 +00002764 bool hasWrittenPrototype,
2765 bool isConstexprSpecified) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00002766 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2767 T, TInfo, SC, SCAsWritten,
Richard Smitha77a0a62011-08-15 21:04:07 +00002768 isInlineSpecified,
2769 isConstexprSpecified);
Sebastian Redl833ef452010-01-26 22:01:41 +00002770 New->HasWrittenPrototype = hasWrittenPrototype;
2771 return New;
2772}
2773
Douglas Gregor72172e92012-01-05 21:55:30 +00002774FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2775 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
2776 return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
2777 DeclarationNameInfo(), QualType(), 0,
2778 SC_None, SC_None, false, false);
2779}
2780
Sebastian Redl833ef452010-01-26 22:01:41 +00002781BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2782 return new (C) BlockDecl(DC, L);
2783}
2784
Douglas Gregor72172e92012-01-05 21:55:30 +00002785BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2786 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
2787 return new (Mem) BlockDecl(0, SourceLocation());
2788}
2789
Sebastian Redl833ef452010-01-26 22:01:41 +00002790EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2791 SourceLocation L,
2792 IdentifierInfo *Id, QualType T,
2793 Expr *E, const llvm::APSInt &V) {
2794 return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2795}
2796
Douglas Gregor72172e92012-01-05 21:55:30 +00002797EnumConstantDecl *
2798EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2799 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
2800 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
2801 llvm::APSInt());
2802}
2803
David Blaikie68e081d2011-12-20 02:48:34 +00002804void IndirectFieldDecl::anchor() { }
2805
Benjamin Kramer39593702010-11-21 14:11:41 +00002806IndirectFieldDecl *
2807IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2808 IdentifierInfo *Id, QualType T, NamedDecl **CH,
2809 unsigned CHS) {
Francois Pichet783dd6e2010-11-21 06:08:52 +00002810 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2811}
2812
Douglas Gregor72172e92012-01-05 21:55:30 +00002813IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
2814 unsigned ID) {
2815 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
2816 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
2817 QualType(), 0, 0);
2818}
2819
Douglas Gregorbe996932010-09-01 20:41:53 +00002820SourceRange EnumConstantDecl::getSourceRange() const {
2821 SourceLocation End = getLocation();
2822 if (Init)
2823 End = Init->getLocEnd();
2824 return SourceRange(getLocation(), End);
2825}
2826
David Blaikie68e081d2011-12-20 02:48:34 +00002827void TypeDecl::anchor() { }
2828
Sebastian Redl833ef452010-01-26 22:01:41 +00002829TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00002830 SourceLocation StartLoc, SourceLocation IdLoc,
2831 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2832 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
Sebastian Redl833ef452010-01-26 22:01:41 +00002833}
2834
David Blaikie68e081d2011-12-20 02:48:34 +00002835void TypedefNameDecl::anchor() { }
2836
Douglas Gregor72172e92012-01-05 21:55:30 +00002837TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2838 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
2839 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2840}
2841
Richard Smithdda56e42011-04-15 14:24:37 +00002842TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2843 SourceLocation StartLoc,
2844 SourceLocation IdLoc, IdentifierInfo *Id,
2845 TypeSourceInfo *TInfo) {
2846 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2847}
2848
Douglas Gregor72172e92012-01-05 21:55:30 +00002849TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2850 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
2851 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2852}
2853
Abramo Bagnaraea947882011-03-08 16:41:52 +00002854SourceRange TypedefDecl::getSourceRange() const {
2855 SourceLocation RangeEnd = getLocation();
2856 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2857 if (typeIsPostfix(TInfo->getType()))
2858 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2859 }
2860 return SourceRange(getLocStart(), RangeEnd);
2861}
2862
Richard Smithdda56e42011-04-15 14:24:37 +00002863SourceRange TypeAliasDecl::getSourceRange() const {
2864 SourceLocation RangeEnd = getLocStart();
2865 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2866 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2867 return SourceRange(getLocStart(), RangeEnd);
2868}
2869
David Blaikie68e081d2011-12-20 02:48:34 +00002870void FileScopeAsmDecl::anchor() { }
2871
Sebastian Redl833ef452010-01-26 22:01:41 +00002872FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
Abramo Bagnara348823a2011-03-03 14:20:18 +00002873 StringLiteral *Str,
2874 SourceLocation AsmLoc,
2875 SourceLocation RParenLoc) {
2876 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
Sebastian Redl833ef452010-01-26 22:01:41 +00002877}
Douglas Gregorba345522011-12-02 23:23:56 +00002878
Douglas Gregor72172e92012-01-05 21:55:30 +00002879FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
2880 unsigned ID) {
2881 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
2882 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
2883}
2884
Douglas Gregorba345522011-12-02 23:23:56 +00002885//===----------------------------------------------------------------------===//
2886// ImportDecl Implementation
2887//===----------------------------------------------------------------------===//
2888
2889/// \brief Retrieve the number of module identifiers needed to name the given
2890/// module.
2891static unsigned getNumModuleIdentifiers(Module *Mod) {
2892 unsigned Result = 1;
2893 while (Mod->Parent) {
2894 Mod = Mod->Parent;
2895 ++Result;
2896 }
2897 return Result;
2898}
2899
Douglas Gregor22d09742012-01-03 18:04:46 +00002900ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002901 Module *Imported,
2902 ArrayRef<SourceLocation> IdentifierLocs)
Douglas Gregor22d09742012-01-03 18:04:46 +00002903 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002904 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002905{
2906 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
2907 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
2908 memcpy(StoredLocs, IdentifierLocs.data(),
2909 IdentifierLocs.size() * sizeof(SourceLocation));
2910}
2911
Douglas Gregor22d09742012-01-03 18:04:46 +00002912ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002913 Module *Imported, SourceLocation EndLoc)
Douglas Gregor22d09742012-01-03 18:04:46 +00002914 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
Douglas Gregor0f2a3602011-12-03 00:30:27 +00002915 NextLocalImport()
Douglas Gregorba345522011-12-02 23:23:56 +00002916{
2917 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
2918}
2919
2920ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00002921 SourceLocation StartLoc, Module *Imported,
Douglas Gregorba345522011-12-02 23:23:56 +00002922 ArrayRef<SourceLocation> IdentifierLocs) {
2923 void *Mem = C.Allocate(sizeof(ImportDecl) +
2924 IdentifierLocs.size() * sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00002925 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
Douglas Gregorba345522011-12-02 23:23:56 +00002926}
2927
2928ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
Douglas Gregor22d09742012-01-03 18:04:46 +00002929 SourceLocation StartLoc,
Douglas Gregorba345522011-12-02 23:23:56 +00002930 Module *Imported,
2931 SourceLocation EndLoc) {
2932 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
Douglas Gregor22d09742012-01-03 18:04:46 +00002933 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
Douglas Gregorba345522011-12-02 23:23:56 +00002934 Import->setImplicit();
2935 return Import;
2936}
2937
Douglas Gregor72172e92012-01-05 21:55:30 +00002938ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
2939 unsigned NumLocations) {
2940 void *Mem = AllocateDeserializedDecl(C, ID,
2941 (sizeof(ImportDecl) +
2942 NumLocations * sizeof(SourceLocation)));
Douglas Gregorba345522011-12-02 23:23:56 +00002943 return new (Mem) ImportDecl(EmptyShell());
2944}
2945
2946ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
2947 if (!ImportedAndComplete.getInt())
2948 return ArrayRef<SourceLocation>();
2949
2950 const SourceLocation *StoredLocs
2951 = reinterpret_cast<const SourceLocation *>(this + 1);
2952 return ArrayRef<SourceLocation>(StoredLocs,
2953 getNumModuleIdentifiers(getImportedModule()));
2954}
2955
2956SourceRange ImportDecl::getSourceRange() const {
2957 if (!ImportedAndComplete.getInt())
2958 return SourceRange(getLocation(),
2959 *reinterpret_cast<const SourceLocation *>(this + 1));
2960
2961 return SourceRange(getLocation(), getIdentifierLocs().back());
2962}
Benjamin Kramer3307c5082012-02-04 12:31:12 +00002963
2964const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
2965 const NamedDecl* ND) {
2966 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
2967 DiagnosticsEngine::ak_nameddecl);
2968 return DB;
2969}
2970
2971const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &PD,
2972 const NamedDecl* ND) {
2973 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
2974 DiagnosticsEngine::ak_nameddecl);
2975 return PD;
2976}