clang API Documentation

Decl.cpp
Go to the documentation of this file.
00001 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the Decl subclasses.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/Decl.h"
00015 #include "clang/AST/DeclCXX.h"
00016 #include "clang/AST/DeclObjC.h"
00017 #include "clang/AST/DeclTemplate.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/TypeLoc.h"
00020 #include "clang/AST/Stmt.h"
00021 #include "clang/AST/Expr.h"
00022 #include "clang/AST/ExprCXX.h"
00023 #include "clang/AST/PrettyPrinter.h"
00024 #include "clang/AST/ASTMutationListener.h"
00025 #include "clang/Basic/Builtins.h"
00026 #include "clang/Basic/IdentifierTable.h"
00027 #include "clang/Basic/Module.h"
00028 #include "clang/Basic/Specifiers.h"
00029 #include "clang/Basic/TargetInfo.h"
00030 #include "llvm/Support/ErrorHandling.h"
00031 
00032 #include <algorithm>
00033 
00034 using namespace clang;
00035 
00036 //===----------------------------------------------------------------------===//
00037 // NamedDecl Implementation
00038 //===----------------------------------------------------------------------===//
00039 
00040 static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
00041   // If this declaration has an explicit visibility attribute, use it.
00042   if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
00043     switch (A->getVisibility()) {
00044     case VisibilityAttr::Default:
00045       return DefaultVisibility;
00046     case VisibilityAttr::Hidden:
00047       return HiddenVisibility;
00048     case VisibilityAttr::Protected:
00049       return ProtectedVisibility;
00050     }
00051   }
00052 
00053   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
00054   // implies visibility(default).
00055   if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
00056     for (specific_attr_iterator<AvailabilityAttr> 
00057               A = D->specific_attr_begin<AvailabilityAttr>(),
00058            AEnd = D->specific_attr_end<AvailabilityAttr>();
00059          A != AEnd; ++A)
00060       if ((*A)->getPlatform()->getName().equals("macosx"))
00061         return DefaultVisibility;
00062   }
00063 
00064   return llvm::Optional<Visibility>();
00065 }
00066 
00067 typedef NamedDecl::LinkageInfo LinkageInfo;
00068 
00069 static LinkageInfo getLVForType(QualType T) {
00070   std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
00071   return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
00072 }
00073 
00074 /// \brief Get the most restrictive linkage for the types in the given
00075 /// template parameter list.
00076 static LinkageInfo
00077 getLVForTemplateParameterList(const TemplateParameterList *Params) {
00078   LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
00079   for (TemplateParameterList::const_iterator P = Params->begin(),
00080                                           PEnd = Params->end();
00081        P != PEnd; ++P) {
00082     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
00083       if (NTTP->isExpandedParameterPack()) {
00084         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
00085           QualType T = NTTP->getExpansionType(I);
00086           if (!T->isDependentType())
00087             LV.merge(getLVForType(T));
00088         }
00089         continue;
00090       }
00091 
00092       if (!NTTP->getType()->isDependentType()) {
00093         LV.merge(getLVForType(NTTP->getType()));
00094         continue;
00095       }
00096     }
00097 
00098     if (TemplateTemplateParmDecl *TTP
00099                                    = dyn_cast<TemplateTemplateParmDecl>(*P)) {
00100       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
00101     }
00102   }
00103 
00104   return LV;
00105 }
00106 
00107 /// getLVForDecl - Get the linkage and visibility for the given declaration.
00108 static LinkageInfo getLVForDecl(const NamedDecl *D, bool OnlyTemplate);
00109 
00110 /// \brief Get the most restrictive linkage for the types and
00111 /// declarations in the given template argument list.
00112 static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
00113                                                 unsigned NumArgs,
00114                                                 bool OnlyTemplate) {
00115   LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
00116 
00117   for (unsigned I = 0; I != NumArgs; ++I) {
00118     switch (Args[I].getKind()) {
00119     case TemplateArgument::Null:
00120     case TemplateArgument::Integral:
00121     case TemplateArgument::Expression:
00122       break;
00123 
00124     case TemplateArgument::Type:
00125       LV.mergeWithMin(getLVForType(Args[I].getAsType()));
00126       break;
00127 
00128     case TemplateArgument::Declaration:
00129       // The decl can validly be null as the representation of nullptr
00130       // arguments, valid only in C++0x.
00131       if (Decl *D = Args[I].getAsDecl()) {
00132         if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
00133           LV.mergeWithMin(getLVForDecl(ND, OnlyTemplate));
00134       }
00135       break;
00136 
00137     case TemplateArgument::Template:
00138     case TemplateArgument::TemplateExpansion:
00139       if (TemplateDecl *Template
00140                 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
00141         LV.mergeWithMin(getLVForDecl(Template, OnlyTemplate));
00142       break;
00143 
00144     case TemplateArgument::Pack:
00145       LV.mergeWithMin(getLVForTemplateArgumentList(Args[I].pack_begin(),
00146                                                    Args[I].pack_size(),
00147                                                    OnlyTemplate));
00148       break;
00149     }
00150   }
00151 
00152   return LV;
00153 }
00154 
00155 static LinkageInfo
00156 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
00157                              bool OnlyTemplate) {
00158   return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), OnlyTemplate);
00159 }
00160 
00161 static bool shouldConsiderTemplateLV(const FunctionDecl *fn) {
00162   return !fn->hasAttr<VisibilityAttr>();
00163 }
00164 
00165 static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
00166   return !d->hasAttr<VisibilityAttr>();
00167 }
00168 
00169 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
00170                                               bool OnlyTemplate) {
00171   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
00172          "Not a name having namespace scope");
00173   ASTContext &Context = D->getASTContext();
00174 
00175   // C++ [basic.link]p3:
00176   //   A name having namespace scope (3.3.6) has internal linkage if it
00177   //   is the name of
00178   //     - an object, reference, function or function template that is
00179   //       explicitly declared static; or,
00180   // (This bullet corresponds to C99 6.2.2p3.)
00181   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
00182     // Explicitly declared static.
00183     if (Var->getStorageClass() == SC_Static)
00184       return LinkageInfo::internal();
00185 
00186     // - an object or reference that is explicitly declared const
00187     //   and neither explicitly declared extern nor previously
00188     //   declared to have external linkage; or
00189     // (there is no equivalent in C99)
00190     if (Context.getLangOpts().CPlusPlus &&
00191         Var->getType().isConstant(Context) && 
00192         Var->getStorageClass() != SC_Extern &&
00193         Var->getStorageClass() != SC_PrivateExtern) {
00194       bool FoundExtern = false;
00195       for (const VarDecl *PrevVar = Var->getPreviousDecl();
00196            PrevVar && !FoundExtern; 
00197            PrevVar = PrevVar->getPreviousDecl())
00198         if (isExternalLinkage(PrevVar->getLinkage()))
00199           FoundExtern = true;
00200       
00201       if (!FoundExtern)
00202         return LinkageInfo::internal();
00203     }
00204     if (Var->getStorageClass() == SC_None) {
00205       const VarDecl *PrevVar = Var->getPreviousDecl();
00206       for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
00207         if (PrevVar->getStorageClass() == SC_PrivateExtern)
00208           break;
00209         if (PrevVar)
00210           return PrevVar->getLinkageAndVisibility();
00211     }
00212   } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
00213     // C++ [temp]p4:
00214     //   A non-member function template can have internal linkage; any
00215     //   other template name shall have external linkage.
00216     const FunctionDecl *Function = 0;
00217     if (const FunctionTemplateDecl *FunTmpl
00218                                         = dyn_cast<FunctionTemplateDecl>(D))
00219       Function = FunTmpl->getTemplatedDecl();
00220     else
00221       Function = cast<FunctionDecl>(D);
00222 
00223     // Explicitly declared static.
00224     if (Function->getStorageClass() == SC_Static)
00225       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
00226   } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
00227     //   - a data member of an anonymous union.
00228     if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
00229       return LinkageInfo::internal();
00230   }
00231 
00232   if (D->isInAnonymousNamespace()) {
00233     const VarDecl *Var = dyn_cast<VarDecl>(D);
00234     const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
00235     if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
00236         (!Func || !Func->getDeclContext()->isExternCContext()))
00237       return LinkageInfo::uniqueExternal();
00238   }
00239 
00240   // Set up the defaults.
00241 
00242   // C99 6.2.2p5:
00243   //   If the declaration of an identifier for an object has file
00244   //   scope and no storage-class specifier, its linkage is
00245   //   external.
00246   LinkageInfo LV;
00247 
00248   if (!OnlyTemplate) {
00249     if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
00250       LV.mergeVisibility(*Vis, true);
00251     } else {
00252       // If we're declared in a namespace with a visibility attribute,
00253       // use that namespace's visibility, but don't call it explicit.
00254       for (const DeclContext *DC = D->getDeclContext();
00255            !isa<TranslationUnitDecl>(DC);
00256            DC = DC->getParent()) {
00257         const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
00258         if (!ND) continue;
00259         if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
00260           LV.mergeVisibility(*Vis, true);
00261           break;
00262         }
00263       }
00264     }
00265   }
00266 
00267   if (!OnlyTemplate)
00268     LV.mergeVisibility(Context.getLangOpts().getVisibilityMode());
00269 
00270   // C++ [basic.link]p4:
00271 
00272   //   A name having namespace scope has external linkage if it is the
00273   //   name of
00274   //
00275   //     - an object or reference, unless it has internal linkage; or
00276   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
00277     // GCC applies the following optimization to variables and static
00278     // data members, but not to functions:
00279     //
00280     // Modify the variable's LV by the LV of its type unless this is
00281     // C or extern "C".  This follows from [basic.link]p9:
00282     //   A type without linkage shall not be used as the type of a
00283     //   variable or function with external linkage unless
00284     //    - the entity has C language linkage, or
00285     //    - the entity is declared within an unnamed namespace, or
00286     //    - the entity is not used or is defined in the same
00287     //      translation unit.
00288     // and [basic.link]p10:
00289     //   ...the types specified by all declarations referring to a
00290     //   given variable or function shall be identical...
00291     // C does not have an equivalent rule.
00292     //
00293     // Ignore this if we've got an explicit attribute;  the user
00294     // probably knows what they're doing.
00295     //
00296     // Note that we don't want to make the variable non-external
00297     // because of this, but unique-external linkage suits us.
00298     if (Context.getLangOpts().CPlusPlus &&
00299         !Var->getDeclContext()->isExternCContext()) {
00300       LinkageInfo TypeLV = getLVForType(Var->getType());
00301       if (TypeLV.linkage() != ExternalLinkage)
00302         return LinkageInfo::uniqueExternal();
00303       LV.mergeVisibility(TypeLV);
00304     }
00305 
00306     if (Var->getStorageClass() == SC_PrivateExtern)
00307       LV.mergeVisibility(HiddenVisibility, true);
00308 
00309     if (!Context.getLangOpts().CPlusPlus &&
00310         (Var->getStorageClass() == SC_Extern ||
00311          Var->getStorageClass() == SC_PrivateExtern)) {
00312 
00313       // C99 6.2.2p4:
00314       //   For an identifier declared with the storage-class specifier
00315       //   extern in a scope in which a prior declaration of that
00316       //   identifier is visible, if the prior declaration specifies
00317       //   internal or external linkage, the linkage of the identifier
00318       //   at the later declaration is the same as the linkage
00319       //   specified at the prior declaration. If no prior declaration
00320       //   is visible, or if the prior declaration specifies no
00321       //   linkage, then the identifier has external linkage.
00322       if (const VarDecl *PrevVar = Var->getPreviousDecl()) {
00323         LinkageInfo PrevLV = getLVForDecl(PrevVar, OnlyTemplate);
00324         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
00325         LV.mergeVisibility(PrevLV);
00326       }
00327     }
00328 
00329   //     - a function, unless it has internal linkage; or
00330   } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
00331     // In theory, we can modify the function's LV by the LV of its
00332     // type unless it has C linkage (see comment above about variables
00333     // for justification).  In practice, GCC doesn't do this, so it's
00334     // just too painful to make work.
00335 
00336     if (Function->getStorageClass() == SC_PrivateExtern)
00337       LV.mergeVisibility(HiddenVisibility, true);
00338 
00339     // C99 6.2.2p5:
00340     //   If the declaration of an identifier for a function has no
00341     //   storage-class specifier, its linkage is determined exactly
00342     //   as if it were declared with the storage-class specifier
00343     //   extern.
00344     if (!Context.getLangOpts().CPlusPlus &&
00345         (Function->getStorageClass() == SC_Extern ||
00346          Function->getStorageClass() == SC_PrivateExtern ||
00347          Function->getStorageClass() == SC_None)) {
00348       // C99 6.2.2p4:
00349       //   For an identifier declared with the storage-class specifier
00350       //   extern in a scope in which a prior declaration of that
00351       //   identifier is visible, if the prior declaration specifies
00352       //   internal or external linkage, the linkage of the identifier
00353       //   at the later declaration is the same as the linkage
00354       //   specified at the prior declaration. If no prior declaration
00355       //   is visible, or if the prior declaration specifies no
00356       //   linkage, then the identifier has external linkage.
00357       if (const FunctionDecl *PrevFunc = Function->getPreviousDecl()) {
00358         LinkageInfo PrevLV = getLVForDecl(PrevFunc, OnlyTemplate);
00359         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
00360         LV.mergeVisibility(PrevLV);
00361       }
00362     }
00363 
00364     // In C++, then if the type of the function uses a type with
00365     // unique-external linkage, it's not legally usable from outside
00366     // this translation unit.  However, we should use the C linkage
00367     // rules instead for extern "C" declarations.
00368     if (Context.getLangOpts().CPlusPlus &&
00369         !Function->getDeclContext()->isExternCContext() &&
00370         Function->getType()->getLinkage() == UniqueExternalLinkage)
00371       return LinkageInfo::uniqueExternal();
00372 
00373     // Consider LV from the template and the template arguments unless
00374     // this is an explicit specialization with a visibility attribute.
00375     if (FunctionTemplateSpecializationInfo *specInfo
00376                                = Function->getTemplateSpecializationInfo()) {
00377       if (shouldConsiderTemplateLV(Function)) {
00378         LV.merge(getLVForDecl(specInfo->getTemplate(),
00379                               true));
00380         const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
00381         LV.mergeWithMin(getLVForTemplateArgumentList(templateArgs,
00382                                                      OnlyTemplate));
00383       }
00384     }
00385 
00386   //     - a named class (Clause 9), or an unnamed class defined in a
00387   //       typedef declaration in which the class has the typedef name
00388   //       for linkage purposes (7.1.3); or
00389   //     - a named enumeration (7.2), or an unnamed enumeration
00390   //       defined in a typedef declaration in which the enumeration
00391   //       has the typedef name for linkage purposes (7.1.3); or
00392   } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
00393     // Unnamed tags have no linkage.
00394     if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
00395       return LinkageInfo::none();
00396 
00397     // If this is a class template specialization, consider the
00398     // linkage of the template and template arguments.
00399     if (const ClassTemplateSpecializationDecl *spec
00400           = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
00401       if (shouldConsiderTemplateLV(spec)) {
00402         // From the template.
00403         LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
00404                               true));
00405 
00406         // The arguments at which the template was instantiated.
00407         const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
00408         LV.mergeWithMin(getLVForTemplateArgumentList(TemplateArgs,
00409                                                      OnlyTemplate));
00410       }
00411     }
00412 
00413   //     - an enumerator belonging to an enumeration with external linkage;
00414   } else if (isa<EnumConstantDecl>(D)) {
00415     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
00416                                       OnlyTemplate);
00417     if (!isExternalLinkage(EnumLV.linkage()))
00418       return LinkageInfo::none();
00419     LV.merge(EnumLV);
00420 
00421   //     - a template, unless it is a function template that has
00422   //       internal linkage (Clause 14);
00423   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
00424     LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
00425   //     - a namespace (7.3), unless it is declared within an unnamed
00426   //       namespace.
00427   } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
00428     return LV;
00429 
00430   // By extension, we assign external linkage to Objective-C
00431   // interfaces.
00432   } else if (isa<ObjCInterfaceDecl>(D)) {
00433     // fallout
00434 
00435   // Everything not covered here has no linkage.
00436   } else {
00437     return LinkageInfo::none();
00438   }
00439 
00440   // If we ended up with non-external linkage, visibility should
00441   // always be default.
00442   if (LV.linkage() != ExternalLinkage)
00443     return LinkageInfo(LV.linkage(), DefaultVisibility, false);
00444 
00445   return LV;
00446 }
00447 
00448 static LinkageInfo getLVForClassMember(const NamedDecl *D, bool OnlyTemplate) {
00449   // Only certain class members have linkage.  Note that fields don't
00450   // really have linkage, but it's convenient to say they do for the
00451   // purposes of calculating linkage of pointer-to-data-member
00452   // template arguments.
00453   if (!(isa<CXXMethodDecl>(D) ||
00454         isa<VarDecl>(D) ||
00455         isa<FieldDecl>(D) ||
00456         (isa<TagDecl>(D) &&
00457          (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
00458     return LinkageInfo::none();
00459 
00460   LinkageInfo LV;
00461 
00462   // If we have an explicit visibility attribute, merge that in.
00463   if (!OnlyTemplate) {
00464     if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility())
00465       LV.mergeVisibility(*Vis, true);
00466   }
00467 
00468   // If this class member has an explicit visibility attribute, the only
00469   // thing that can change its visibility is the template arguments, so
00470   // only look for them when processing the the class.
00471   bool ClassOnlyTemplate =  LV.visibilityExplicit() ? true : OnlyTemplate;
00472 
00473   // If we're paying attention to global visibility, apply
00474   // -finline-visibility-hidden if this is an inline method.
00475   //
00476   // Note that we do this before merging information about
00477   // the class visibility.
00478   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
00479     TemplateSpecializationKind TSK = TSK_Undeclared;
00480     if (FunctionTemplateSpecializationInfo *spec
00481         = MD->getTemplateSpecializationInfo()) {
00482       TSK = spec->getTemplateSpecializationKind();
00483     } else if (MemberSpecializationInfo *MSI =
00484                MD->getMemberSpecializationInfo()) {
00485       TSK = MSI->getTemplateSpecializationKind();
00486     }
00487 
00488     const FunctionDecl *Def = 0;
00489     // InlineVisibilityHidden only applies to definitions, and
00490     // isInlined() only gives meaningful answers on definitions
00491     // anyway.
00492     if (TSK != TSK_ExplicitInstantiationDeclaration &&
00493         TSK != TSK_ExplicitInstantiationDefinition &&
00494         !OnlyTemplate &&
00495         !LV.visibilityExplicit() &&
00496         MD->getASTContext().getLangOpts().InlineVisibilityHidden &&
00497         MD->hasBody(Def) && Def->isInlined())
00498       LV.mergeVisibility(HiddenVisibility, true);
00499   }
00500 
00501   // If this member has an visibility attribute, ClassF will exclude
00502   // attributes on the class or command line options, keeping only information
00503   // about the template instantiation. If the member has no visibility
00504   // attributes, mergeWithMin behaves like merge, so in both cases mergeWithMin
00505   // produces the desired result.
00506   LV.mergeWithMin(getLVForDecl(cast<RecordDecl>(D->getDeclContext()),
00507                                ClassOnlyTemplate));
00508   if (!isExternalLinkage(LV.linkage()))
00509     return LinkageInfo::none();
00510 
00511   // If the class already has unique-external linkage, we can't improve.
00512   if (LV.linkage() == UniqueExternalLinkage)
00513     return LinkageInfo::uniqueExternal();
00514 
00515   if (!OnlyTemplate)
00516     LV.mergeVisibility(D->getASTContext().getLangOpts().getVisibilityMode());
00517 
00518   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
00519     // If the type of the function uses a type with unique-external
00520     // linkage, it's not legally usable from outside this translation unit.
00521     if (MD->getType()->getLinkage() == UniqueExternalLinkage)
00522       return LinkageInfo::uniqueExternal();
00523 
00524     // If this is a method template specialization, use the linkage for
00525     // the template parameters and arguments.
00526     if (FunctionTemplateSpecializationInfo *spec
00527            = MD->getTemplateSpecializationInfo()) {
00528       if (shouldConsiderTemplateLV(MD)) {
00529         LV.mergeWithMin(getLVForTemplateArgumentList(*spec->TemplateArguments,
00530                                                      OnlyTemplate));
00531         if (!OnlyTemplate)
00532           LV.merge(getLVForTemplateParameterList(
00533                               spec->getTemplate()->getTemplateParameters()));
00534       }
00535     }
00536 
00537     // Note that in contrast to basically every other situation, we
00538     // *do* apply -fvisibility to method declarations.
00539 
00540   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
00541     if (const ClassTemplateSpecializationDecl *spec
00542         = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
00543       if (shouldConsiderTemplateLV(spec)) {
00544         // Merge template argument/parameter information for member
00545         // class template specializations.
00546         LV.mergeWithMin(getLVForTemplateArgumentList(spec->getTemplateArgs(),
00547                                                      OnlyTemplate));
00548       if (!OnlyTemplate)
00549         LV.merge(getLVForTemplateParameterList(
00550                     spec->getSpecializedTemplate()->getTemplateParameters()));
00551       }
00552     }
00553 
00554   // Static data members.
00555   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00556     // Modify the variable's linkage by its type, but ignore the
00557     // type's visibility unless it's a definition.
00558     LinkageInfo TypeLV = getLVForType(VD->getType());
00559     if (TypeLV.linkage() != ExternalLinkage)
00560       LV.mergeLinkage(UniqueExternalLinkage);
00561     LV.mergeVisibility(TypeLV);
00562   }
00563 
00564   return LV;
00565 }
00566 
00567 static void clearLinkageForClass(const CXXRecordDecl *record) {
00568   for (CXXRecordDecl::decl_iterator
00569          i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
00570     Decl *child = *i;
00571     if (isa<NamedDecl>(child))
00572       cast<NamedDecl>(child)->ClearLinkageCache();
00573   }
00574 }
00575 
00576 void NamedDecl::anchor() { }
00577 
00578 void NamedDecl::ClearLinkageCache() {
00579   // Note that we can't skip clearing the linkage of children just
00580   // because the parent doesn't have cached linkage:  we don't cache
00581   // when computing linkage for parent contexts.
00582 
00583   HasCachedLinkage = 0;
00584 
00585   // If we're changing the linkage of a class, we need to reset the
00586   // linkage of child declarations, too.
00587   if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
00588     clearLinkageForClass(record);
00589 
00590   if (ClassTemplateDecl *temp =
00591         dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
00592     // Clear linkage for the template pattern.
00593     CXXRecordDecl *record = temp->getTemplatedDecl();
00594     record->HasCachedLinkage = 0;
00595     clearLinkageForClass(record);
00596 
00597     // We need to clear linkage for specializations, too.
00598     for (ClassTemplateDecl::spec_iterator
00599            i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
00600       i->ClearLinkageCache();
00601   }
00602 
00603   // Clear cached linkage for function template decls, too.
00604   if (FunctionTemplateDecl *temp =
00605         dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
00606     temp->getTemplatedDecl()->ClearLinkageCache();
00607     for (FunctionTemplateDecl::spec_iterator
00608            i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
00609       i->ClearLinkageCache();
00610   }
00611     
00612 }
00613 
00614 Linkage NamedDecl::getLinkage() const {
00615   if (HasCachedLinkage) {
00616     assert(Linkage(CachedLinkage) ==
00617              getLVForDecl(this, true).linkage());
00618     return Linkage(CachedLinkage);
00619   }
00620 
00621   CachedLinkage = getLVForDecl(this, true).linkage();
00622   HasCachedLinkage = 1;
00623   return Linkage(CachedLinkage);
00624 }
00625 
00626 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
00627   LinkageInfo LI = getLVForDecl(this, false);
00628   assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
00629   HasCachedLinkage = 1;
00630   CachedLinkage = LI.linkage();
00631   return LI;
00632 }
00633 
00634 llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
00635   // Use the most recent declaration of a variable.
00636   if (const VarDecl *Var = dyn_cast<VarDecl>(this)) {
00637     if (llvm::Optional<Visibility> V =
00638         getVisibilityOf(Var->getMostRecentDecl()))
00639       return V;
00640 
00641     if (Var->isStaticDataMember()) {
00642       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
00643       if (InstantiatedFrom)
00644         return getVisibilityOf(InstantiatedFrom);
00645     }
00646 
00647     return llvm::Optional<Visibility>();
00648   }
00649   // Use the most recent declaration of a function, and also handle
00650   // function template specializations.
00651   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
00652     if (llvm::Optional<Visibility> V
00653                             = getVisibilityOf(fn->getMostRecentDecl())) 
00654       return V;
00655 
00656     // If the function is a specialization of a template with an
00657     // explicit visibility attribute, use that.
00658     if (FunctionTemplateSpecializationInfo *templateInfo
00659           = fn->getTemplateSpecializationInfo())
00660       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
00661 
00662     // If the function is a member of a specialization of a class template
00663     // and the corresponding decl has explicit visibility, use that.
00664     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
00665     if (InstantiatedFrom)
00666       return getVisibilityOf(InstantiatedFrom);
00667 
00668     return llvm::Optional<Visibility>();
00669   }
00670 
00671   // Otherwise, just check the declaration itself first.
00672   if (llvm::Optional<Visibility> V = getVisibilityOf(this))
00673     return V;
00674 
00675   // If there wasn't explicit visibility there, and this is a
00676   // specialization of a class template, check for visibility
00677   // on the pattern.
00678   if (const ClassTemplateSpecializationDecl *spec
00679         = dyn_cast<ClassTemplateSpecializationDecl>(this))
00680     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
00681 
00682   // If this is a member class of a specialization of a class template
00683   // and the corresponding decl has explicit visibility, use that.
00684   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
00685     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
00686     if (InstantiatedFrom)
00687       return getVisibilityOf(InstantiatedFrom);
00688   }
00689 
00690   return llvm::Optional<Visibility>();
00691 }
00692 
00693 static LinkageInfo getLVForDecl(const NamedDecl *D, bool OnlyTemplate) {
00694   // Objective-C: treat all Objective-C declarations as having external
00695   // linkage.
00696   switch (D->getKind()) {
00697     default:
00698       break;
00699     case Decl::ParmVar:
00700       return LinkageInfo::none();
00701     case Decl::TemplateTemplateParm: // count these as external
00702     case Decl::NonTypeTemplateParm:
00703     case Decl::ObjCAtDefsField:
00704     case Decl::ObjCCategory:
00705     case Decl::ObjCCategoryImpl:
00706     case Decl::ObjCCompatibleAlias:
00707     case Decl::ObjCImplementation:
00708     case Decl::ObjCMethod:
00709     case Decl::ObjCProperty:
00710     case Decl::ObjCPropertyImpl:
00711     case Decl::ObjCProtocol:
00712       return LinkageInfo::external();
00713       
00714     case Decl::CXXRecord: {
00715       const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
00716       if (Record->isLambda()) {
00717         if (!Record->getLambdaManglingNumber()) {
00718           // This lambda has no mangling number, so it's internal.
00719           return LinkageInfo::internal();
00720         }
00721         
00722         // This lambda has its linkage/visibility determined by its owner.
00723         const DeclContext *DC = D->getDeclContext()->getRedeclContext();
00724         if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
00725           if (isa<ParmVarDecl>(ContextDecl))
00726             DC = ContextDecl->getDeclContext()->getRedeclContext();
00727           else
00728             return getLVForDecl(cast<NamedDecl>(ContextDecl),
00729                                 OnlyTemplate);
00730         }
00731 
00732         if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
00733           return getLVForDecl(ND, OnlyTemplate);
00734         
00735         return LinkageInfo::external();
00736       }
00737       
00738       break;
00739     }
00740   }
00741 
00742   // Handle linkage for namespace-scope names.
00743   if (D->getDeclContext()->getRedeclContext()->isFileContext())
00744     return getLVForNamespaceScopeDecl(D, OnlyTemplate);
00745   
00746   // C++ [basic.link]p5:
00747   //   In addition, a member function, static data member, a named
00748   //   class or enumeration of class scope, or an unnamed class or
00749   //   enumeration defined in a class-scope typedef declaration such
00750   //   that the class or enumeration has the typedef name for linkage
00751   //   purposes (7.1.3), has external linkage if the name of the class
00752   //   has external linkage.
00753   if (D->getDeclContext()->isRecord())
00754     return getLVForClassMember(D, OnlyTemplate);
00755 
00756   // C++ [basic.link]p6:
00757   //   The name of a function declared in block scope and the name of
00758   //   an object declared by a block scope extern declaration have
00759   //   linkage. If there is a visible declaration of an entity with
00760   //   linkage having the same name and type, ignoring entities
00761   //   declared outside the innermost enclosing namespace scope, the
00762   //   block scope declaration declares that same entity and receives
00763   //   the linkage of the previous declaration. If there is more than
00764   //   one such matching entity, the program is ill-formed. Otherwise,
00765   //   if no matching entity is found, the block scope entity receives
00766   //   external linkage.
00767   if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
00768     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
00769       if (Function->isInAnonymousNamespace() &&
00770           !Function->getDeclContext()->isExternCContext())
00771         return LinkageInfo::uniqueExternal();
00772 
00773       LinkageInfo LV;
00774       if (!OnlyTemplate) {
00775         if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
00776           LV.mergeVisibility(*Vis, true);
00777       }
00778       
00779       if (const FunctionDecl *Prev = Function->getPreviousDecl()) {
00780         LinkageInfo PrevLV = getLVForDecl(Prev, OnlyTemplate);
00781         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
00782         LV.mergeVisibility(PrevLV);
00783       }
00784 
00785       return LV;
00786     }
00787 
00788     if (const VarDecl *Var = dyn_cast<VarDecl>(D))
00789       if (Var->getStorageClass() == SC_Extern ||
00790           Var->getStorageClass() == SC_PrivateExtern) {
00791         if (Var->isInAnonymousNamespace() &&
00792             !Var->getDeclContext()->isExternCContext())
00793           return LinkageInfo::uniqueExternal();
00794 
00795         LinkageInfo LV;
00796         if (Var->getStorageClass() == SC_PrivateExtern)
00797           LV.mergeVisibility(HiddenVisibility, true);
00798         else if (!OnlyTemplate) {
00799           if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
00800             LV.mergeVisibility(*Vis, true);
00801         }
00802         
00803         if (const VarDecl *Prev = Var->getPreviousDecl()) {
00804           LinkageInfo PrevLV = getLVForDecl(Prev, OnlyTemplate);
00805           if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
00806           LV.mergeVisibility(PrevLV);
00807         }
00808 
00809         return LV;
00810       }
00811   }
00812 
00813   // C++ [basic.link]p6:
00814   //   Names not covered by these rules have no linkage.
00815   return LinkageInfo::none();
00816 }
00817 
00818 std::string NamedDecl::getQualifiedNameAsString() const {
00819   return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
00820 }
00821 
00822 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
00823   const DeclContext *Ctx = getDeclContext();
00824 
00825   if (Ctx->isFunctionOrMethod())
00826     return getNameAsString();
00827 
00828   typedef SmallVector<const DeclContext *, 8> ContextsTy;
00829   ContextsTy Contexts;
00830 
00831   // Collect contexts.
00832   while (Ctx && isa<NamedDecl>(Ctx)) {
00833     Contexts.push_back(Ctx);
00834     Ctx = Ctx->getParent();
00835   };
00836 
00837   std::string QualName;
00838   llvm::raw_string_ostream OS(QualName);
00839 
00840   for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
00841        I != E; ++I) {
00842     if (const ClassTemplateSpecializationDecl *Spec
00843           = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
00844       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
00845       std::string TemplateArgsStr
00846         = TemplateSpecializationType::PrintTemplateArgumentList(
00847                                            TemplateArgs.data(),
00848                                            TemplateArgs.size(),
00849                                            P);
00850       OS << Spec->getName() << TemplateArgsStr;
00851     } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
00852       if (ND->isAnonymousNamespace())
00853         OS << "<anonymous namespace>";
00854       else
00855         OS << *ND;
00856     } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
00857       if (!RD->getIdentifier())
00858         OS << "<anonymous " << RD->getKindName() << '>';
00859       else
00860         OS << *RD;
00861     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
00862       const FunctionProtoType *FT = 0;
00863       if (FD->hasWrittenPrototype())
00864         FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
00865 
00866       OS << *FD << '(';
00867       if (FT) {
00868         unsigned NumParams = FD->getNumParams();
00869         for (unsigned i = 0; i < NumParams; ++i) {
00870           if (i)
00871             OS << ", ";
00872           OS << FD->getParamDecl(i)->getType().stream(P);
00873         }
00874 
00875         if (FT->isVariadic()) {
00876           if (NumParams > 0)
00877             OS << ", ";
00878           OS << "...";
00879         }
00880       }
00881       OS << ')';
00882     } else {
00883       OS << *cast<NamedDecl>(*I);
00884     }
00885     OS << "::";
00886   }
00887 
00888   if (getDeclName())
00889     OS << *this;
00890   else
00891     OS << "<anonymous>";
00892 
00893   return OS.str();
00894 }
00895 
00896 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
00897   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
00898 
00899   // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
00900   // We want to keep it, unless it nominates same namespace.
00901   if (getKind() == Decl::UsingDirective) {
00902     return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
00903              ->getOriginalNamespace() ==
00904            cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
00905              ->getOriginalNamespace();
00906   }
00907 
00908   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
00909     // For function declarations, we keep track of redeclarations.
00910     return FD->getPreviousDecl() == OldD;
00911 
00912   // For function templates, the underlying function declarations are linked.
00913   if (const FunctionTemplateDecl *FunctionTemplate
00914         = dyn_cast<FunctionTemplateDecl>(this))
00915     if (const FunctionTemplateDecl *OldFunctionTemplate
00916           = dyn_cast<FunctionTemplateDecl>(OldD))
00917       return FunctionTemplate->getTemplatedDecl()
00918                ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
00919 
00920   // For method declarations, we keep track of redeclarations.
00921   if (isa<ObjCMethodDecl>(this))
00922     return false;
00923 
00924   if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
00925     return true;
00926 
00927   if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
00928     return cast<UsingShadowDecl>(this)->getTargetDecl() ==
00929            cast<UsingShadowDecl>(OldD)->getTargetDecl();
00930 
00931   if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
00932     ASTContext &Context = getASTContext();
00933     return Context.getCanonicalNestedNameSpecifier(
00934                                      cast<UsingDecl>(this)->getQualifier()) ==
00935            Context.getCanonicalNestedNameSpecifier(
00936                                         cast<UsingDecl>(OldD)->getQualifier());
00937   }
00938 
00939   // A typedef of an Objective-C class type can replace an Objective-C class
00940   // declaration or definition, and vice versa.
00941   if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
00942       (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
00943     return true;
00944   
00945   // For non-function declarations, if the declarations are of the
00946   // same kind then this must be a redeclaration, or semantic analysis
00947   // would not have given us the new declaration.
00948   return this->getKind() == OldD->getKind();
00949 }
00950 
00951 bool NamedDecl::hasLinkage() const {
00952   return getLinkage() != NoLinkage;
00953 }
00954 
00955 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
00956   NamedDecl *ND = this;
00957   while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
00958     ND = UD->getTargetDecl();
00959 
00960   if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
00961     return AD->getClassInterface();
00962 
00963   return ND;
00964 }
00965 
00966 bool NamedDecl::isCXXInstanceMember() const {
00967   if (!isCXXClassMember())
00968     return false;
00969   
00970   const NamedDecl *D = this;
00971   if (isa<UsingShadowDecl>(D))
00972     D = cast<UsingShadowDecl>(D)->getTargetDecl();
00973 
00974   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
00975     return true;
00976   if (isa<CXXMethodDecl>(D))
00977     return cast<CXXMethodDecl>(D)->isInstance();
00978   if (isa<FunctionTemplateDecl>(D))
00979     return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
00980                                  ->getTemplatedDecl())->isInstance();
00981   return false;
00982 }
00983 
00984 //===----------------------------------------------------------------------===//
00985 // DeclaratorDecl Implementation
00986 //===----------------------------------------------------------------------===//
00987 
00988 template <typename DeclT>
00989 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
00990   if (decl->getNumTemplateParameterLists() > 0)
00991     return decl->getTemplateParameterList(0)->getTemplateLoc();
00992   else
00993     return decl->getInnerLocStart();
00994 }
00995 
00996 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
00997   TypeSourceInfo *TSI = getTypeSourceInfo();
00998   if (TSI) return TSI->getTypeLoc().getBeginLoc();
00999   return SourceLocation();
01000 }
01001 
01002 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
01003   if (QualifierLoc) {
01004     // Make sure the extended decl info is allocated.
01005     if (!hasExtInfo()) {
01006       // Save (non-extended) type source info pointer.
01007       TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
01008       // Allocate external info struct.
01009       DeclInfo = new (getASTContext()) ExtInfo;
01010       // Restore savedTInfo into (extended) decl info.
01011       getExtInfo()->TInfo = savedTInfo;
01012     }
01013     // Set qualifier info.
01014     getExtInfo()->QualifierLoc = QualifierLoc;
01015   } else {
01016     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
01017     if (hasExtInfo()) {
01018       if (getExtInfo()->NumTemplParamLists == 0) {
01019         // Save type source info pointer.
01020         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
01021         // Deallocate the extended decl info.
01022         getASTContext().Deallocate(getExtInfo());
01023         // Restore savedTInfo into (non-extended) decl info.
01024         DeclInfo = savedTInfo;
01025       }
01026       else
01027         getExtInfo()->QualifierLoc = QualifierLoc;
01028     }
01029   }
01030 }
01031 
01032 void
01033 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
01034                                               unsigned NumTPLists,
01035                                               TemplateParameterList **TPLists) {
01036   assert(NumTPLists > 0);
01037   // Make sure the extended decl info is allocated.
01038   if (!hasExtInfo()) {
01039     // Save (non-extended) type source info pointer.
01040     TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
01041     // Allocate external info struct.
01042     DeclInfo = new (getASTContext()) ExtInfo;
01043     // Restore savedTInfo into (extended) decl info.
01044     getExtInfo()->TInfo = savedTInfo;
01045   }
01046   // Set the template parameter lists info.
01047   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
01048 }
01049 
01050 SourceLocation DeclaratorDecl::getOuterLocStart() const {
01051   return getTemplateOrInnerLocStart(this);
01052 }
01053 
01054 namespace {
01055 
01056 // Helper function: returns true if QT is or contains a type
01057 // having a postfix component.
01058 bool typeIsPostfix(clang::QualType QT) {
01059   while (true) {
01060     const Type* T = QT.getTypePtr();
01061     switch (T->getTypeClass()) {
01062     default:
01063       return false;
01064     case Type::Pointer:
01065       QT = cast<PointerType>(T)->getPointeeType();
01066       break;
01067     case Type::BlockPointer:
01068       QT = cast<BlockPointerType>(T)->getPointeeType();
01069       break;
01070     case Type::MemberPointer:
01071       QT = cast<MemberPointerType>(T)->getPointeeType();
01072       break;
01073     case Type::LValueReference:
01074     case Type::RValueReference:
01075       QT = cast<ReferenceType>(T)->getPointeeType();
01076       break;
01077     case Type::PackExpansion:
01078       QT = cast<PackExpansionType>(T)->getPattern();
01079       break;
01080     case Type::Paren:
01081     case Type::ConstantArray:
01082     case Type::DependentSizedArray:
01083     case Type::IncompleteArray:
01084     case Type::VariableArray:
01085     case Type::FunctionProto:
01086     case Type::FunctionNoProto:
01087       return true;
01088     }
01089   }
01090 }
01091 
01092 } // namespace
01093 
01094 SourceRange DeclaratorDecl::getSourceRange() const {
01095   SourceLocation RangeEnd = getLocation();
01096   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
01097     if (typeIsPostfix(TInfo->getType()))
01098       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
01099   }
01100   return SourceRange(getOuterLocStart(), RangeEnd);
01101 }
01102 
01103 void
01104 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
01105                                              unsigned NumTPLists,
01106                                              TemplateParameterList **TPLists) {
01107   assert((NumTPLists == 0 || TPLists != 0) &&
01108          "Empty array of template parameters with positive size!");
01109 
01110   // Free previous template parameters (if any).
01111   if (NumTemplParamLists > 0) {
01112     Context.Deallocate(TemplParamLists);
01113     TemplParamLists = 0;
01114     NumTemplParamLists = 0;
01115   }
01116   // Set info on matched template parameter lists (if any).
01117   if (NumTPLists > 0) {
01118     TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
01119     NumTemplParamLists = NumTPLists;
01120     for (unsigned i = NumTPLists; i-- > 0; )
01121       TemplParamLists[i] = TPLists[i];
01122   }
01123 }
01124 
01125 //===----------------------------------------------------------------------===//
01126 // VarDecl Implementation
01127 //===----------------------------------------------------------------------===//
01128 
01129 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
01130   switch (SC) {
01131   case SC_None:                 break;
01132   case SC_Auto:                 return "auto";
01133   case SC_Extern:               return "extern";
01134   case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
01135   case SC_PrivateExtern:        return "__private_extern__";
01136   case SC_Register:             return "register";
01137   case SC_Static:               return "static";
01138   }
01139 
01140   llvm_unreachable("Invalid storage class");
01141 }
01142 
01143 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
01144                          SourceLocation StartL, SourceLocation IdL,
01145                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
01146                          StorageClass S, StorageClass SCAsWritten) {
01147   return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
01148 }
01149 
01150 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
01151   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
01152   return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0, 
01153                            QualType(), 0, SC_None, SC_None);
01154 }
01155 
01156 void VarDecl::setStorageClass(StorageClass SC) {
01157   assert(isLegalForVariable(SC));
01158   if (getStorageClass() != SC)
01159     ClearLinkageCache();
01160   
01161   VarDeclBits.SClass = SC;
01162 }
01163 
01164 SourceRange VarDecl::getSourceRange() const {
01165   if (getInit())
01166     return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
01167   return DeclaratorDecl::getSourceRange();
01168 }
01169 
01170 bool VarDecl::isExternC() const {
01171   if (getLinkage() != ExternalLinkage)
01172     return false;
01173 
01174   const DeclContext *DC = getDeclContext();
01175   if (DC->isRecord())
01176     return false;
01177 
01178   ASTContext &Context = getASTContext();
01179   if (!Context.getLangOpts().CPlusPlus)
01180     return true;
01181   return DC->isExternCContext();
01182 }
01183 
01184 VarDecl *VarDecl::getCanonicalDecl() {
01185   return getFirstDeclaration();
01186 }
01187 
01188 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
01189   ASTContext &C) const
01190 {
01191   // C++ [basic.def]p2:
01192   //   A declaration is a definition unless [...] it contains the 'extern'
01193   //   specifier or a linkage-specification and neither an initializer [...],
01194   //   it declares a static data member in a class declaration [...].
01195   // C++ [temp.expl.spec]p15:
01196   //   An explicit specialization of a static data member of a template is a
01197   //   definition if the declaration includes an initializer; otherwise, it is
01198   //   a declaration.
01199   if (isStaticDataMember()) {
01200     if (isOutOfLine() && (hasInit() ||
01201           getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
01202       return Definition;
01203     else
01204       return DeclarationOnly;
01205   }
01206   // C99 6.7p5:
01207   //   A definition of an identifier is a declaration for that identifier that
01208   //   [...] causes storage to be reserved for that object.
01209   // Note: that applies for all non-file-scope objects.
01210   // C99 6.9.2p1:
01211   //   If the declaration of an identifier for an object has file scope and an
01212   //   initializer, the declaration is an external definition for the identifier
01213   if (hasInit())
01214     return Definition;
01215   // AST for 'extern "C" int foo;' is annotated with 'extern'.
01216   if (hasExternalStorage())
01217     return DeclarationOnly;
01218   
01219   if (getStorageClassAsWritten() == SC_Extern ||
01220        getStorageClassAsWritten() == SC_PrivateExtern) {
01221     for (const VarDecl *PrevVar = getPreviousDecl();
01222          PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
01223       if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
01224         return DeclarationOnly;
01225     }
01226   }
01227   // C99 6.9.2p2:
01228   //   A declaration of an object that has file scope without an initializer,
01229   //   and without a storage class specifier or the scs 'static', constitutes
01230   //   a tentative definition.
01231   // No such thing in C++.
01232   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
01233     return TentativeDefinition;
01234 
01235   // What's left is (in C, block-scope) declarations without initializers or
01236   // external storage. These are definitions.
01237   return Definition;
01238 }
01239 
01240 VarDecl *VarDecl::getActingDefinition() {
01241   DefinitionKind Kind = isThisDeclarationADefinition();
01242   if (Kind != TentativeDefinition)
01243     return 0;
01244 
01245   VarDecl *LastTentative = 0;
01246   VarDecl *First = getFirstDeclaration();
01247   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
01248        I != E; ++I) {
01249     Kind = (*I)->isThisDeclarationADefinition();
01250     if (Kind == Definition)
01251       return 0;
01252     else if (Kind == TentativeDefinition)
01253       LastTentative = *I;
01254   }
01255   return LastTentative;
01256 }
01257 
01258 bool VarDecl::isTentativeDefinitionNow() const {
01259   DefinitionKind Kind = isThisDeclarationADefinition();
01260   if (Kind != TentativeDefinition)
01261     return false;
01262 
01263   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
01264     if ((*I)->isThisDeclarationADefinition() == Definition)
01265       return false;
01266   }
01267   return true;
01268 }
01269 
01270 VarDecl *VarDecl::getDefinition(ASTContext &C) {
01271   VarDecl *First = getFirstDeclaration();
01272   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
01273        I != E; ++I) {
01274     if ((*I)->isThisDeclarationADefinition(C) == Definition)
01275       return *I;
01276   }
01277   return 0;
01278 }
01279 
01280 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
01281   DefinitionKind Kind = DeclarationOnly;
01282   
01283   const VarDecl *First = getFirstDeclaration();
01284   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
01285        I != E; ++I) {
01286     Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
01287     if (Kind == Definition)
01288       break;
01289   }
01290 
01291   return Kind;
01292 }
01293 
01294 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
01295   redecl_iterator I = redecls_begin(), E = redecls_end();
01296   while (I != E && !I->getInit())
01297     ++I;
01298 
01299   if (I != E) {
01300     D = *I;
01301     return I->getInit();
01302   }
01303   return 0;
01304 }
01305 
01306 bool VarDecl::isOutOfLine() const {
01307   if (Decl::isOutOfLine())
01308     return true;
01309 
01310   if (!isStaticDataMember())
01311     return false;
01312 
01313   // If this static data member was instantiated from a static data member of
01314   // a class template, check whether that static data member was defined 
01315   // out-of-line.
01316   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
01317     return VD->isOutOfLine();
01318   
01319   return false;
01320 }
01321 
01322 VarDecl *VarDecl::getOutOfLineDefinition() {
01323   if (!isStaticDataMember())
01324     return 0;
01325   
01326   for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
01327        RD != RDEnd; ++RD) {
01328     if (RD->getLexicalDeclContext()->isFileContext())
01329       return *RD;
01330   }
01331   
01332   return 0;
01333 }
01334 
01335 void VarDecl::setInit(Expr *I) {
01336   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
01337     Eval->~EvaluatedStmt();
01338     getASTContext().Deallocate(Eval);
01339   }
01340 
01341   Init = I;
01342 }
01343 
01344 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
01345   const LangOptions &Lang = C.getLangOpts();
01346 
01347   if (!Lang.CPlusPlus)
01348     return false;
01349 
01350   // In C++11, any variable of reference type can be used in a constant
01351   // expression if it is initialized by a constant expression.
01352   if (Lang.CPlusPlus0x && getType()->isReferenceType())
01353     return true;
01354 
01355   // Only const objects can be used in constant expressions in C++. C++98 does
01356   // not require the variable to be non-volatile, but we consider this to be a
01357   // defect.
01358   if (!getType().isConstQualified() || getType().isVolatileQualified())
01359     return false;
01360 
01361   // In C++, const, non-volatile variables of integral or enumeration types
01362   // can be used in constant expressions.
01363   if (getType()->isIntegralOrEnumerationType())
01364     return true;
01365 
01366   // Additionally, in C++11, non-volatile constexpr variables can be used in
01367   // constant expressions.
01368   return Lang.CPlusPlus0x && isConstexpr();
01369 }
01370 
01371 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
01372 /// form, which contains extra information on the evaluated value of the
01373 /// initializer.
01374 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
01375   EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
01376   if (!Eval) {
01377     Stmt *S = Init.get<Stmt *>();
01378     Eval = new (getASTContext()) EvaluatedStmt;
01379     Eval->Value = S;
01380     Init = Eval;
01381   }
01382   return Eval;
01383 }
01384 
01385 APValue *VarDecl::evaluateValue() const {
01386   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
01387   return evaluateValue(Notes);
01388 }
01389 
01390 APValue *VarDecl::evaluateValue(
01391     llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
01392   EvaluatedStmt *Eval = ensureEvaluatedStmt();
01393 
01394   // We only produce notes indicating why an initializer is non-constant the
01395   // first time it is evaluated. FIXME: The notes won't always be emitted the
01396   // first time we try evaluation, so might not be produced at all.
01397   if (Eval->WasEvaluated)
01398     return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
01399 
01400   const Expr *Init = cast<Expr>(Eval->Value);
01401   assert(!Init->isValueDependent());
01402 
01403   if (Eval->IsEvaluating) {
01404     // FIXME: Produce a diagnostic for self-initialization.
01405     Eval->CheckedICE = true;
01406     Eval->IsICE = false;
01407     return 0;
01408   }
01409 
01410   Eval->IsEvaluating = true;
01411 
01412   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
01413                                             this, Notes);
01414 
01415   // Ensure the result is an uninitialized APValue if evaluation fails.
01416   if (!Result)
01417     Eval->Evaluated = APValue();
01418 
01419   Eval->IsEvaluating = false;
01420   Eval->WasEvaluated = true;
01421 
01422   // In C++11, we have determined whether the initializer was a constant
01423   // expression as a side-effect.
01424   if (getASTContext().getLangOpts().CPlusPlus0x && !Eval->CheckedICE) {
01425     Eval->CheckedICE = true;
01426     Eval->IsICE = Result && Notes.empty();
01427   }
01428 
01429   return Result ? &Eval->Evaluated : 0;
01430 }
01431 
01432 bool VarDecl::checkInitIsICE() const {
01433   // Initializers of weak variables are never ICEs.
01434   if (isWeak())
01435     return false;
01436 
01437   EvaluatedStmt *Eval = ensureEvaluatedStmt();
01438   if (Eval->CheckedICE)
01439     // We have already checked whether this subexpression is an
01440     // integral constant expression.
01441     return Eval->IsICE;
01442 
01443   const Expr *Init = cast<Expr>(Eval->Value);
01444   assert(!Init->isValueDependent());
01445 
01446   // In C++11, evaluate the initializer to check whether it's a constant
01447   // expression.
01448   if (getASTContext().getLangOpts().CPlusPlus0x) {
01449     llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
01450     evaluateValue(Notes);
01451     return Eval->IsICE;
01452   }
01453 
01454   // It's an ICE whether or not the definition we found is
01455   // out-of-line.  See DR 721 and the discussion in Clang PR
01456   // 6206 for details.
01457 
01458   if (Eval->CheckingICE)
01459     return false;
01460   Eval->CheckingICE = true;
01461 
01462   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
01463   Eval->CheckingICE = false;
01464   Eval->CheckedICE = true;
01465   return Eval->IsICE;
01466 }
01467 
01468 bool VarDecl::extendsLifetimeOfTemporary() const {
01469   assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
01470   
01471   const Expr *E = getInit();
01472   if (!E)
01473     return false;
01474   
01475   if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
01476     E = Cleanups->getSubExpr();
01477   
01478   return isa<MaterializeTemporaryExpr>(E);
01479 }
01480 
01481 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
01482   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
01483     return cast<VarDecl>(MSI->getInstantiatedFrom());
01484   
01485   return 0;
01486 }
01487 
01488 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
01489   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
01490     return MSI->getTemplateSpecializationKind();
01491   
01492   return TSK_Undeclared;
01493 }
01494 
01495 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
01496   return getASTContext().getInstantiatedFromStaticDataMember(this);
01497 }
01498 
01499 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
01500                                          SourceLocation PointOfInstantiation) {
01501   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
01502   assert(MSI && "Not an instantiated static data member?");
01503   MSI->setTemplateSpecializationKind(TSK);
01504   if (TSK != TSK_ExplicitSpecialization &&
01505       PointOfInstantiation.isValid() &&
01506       MSI->getPointOfInstantiation().isInvalid())
01507     MSI->setPointOfInstantiation(PointOfInstantiation);
01508 }
01509 
01510 //===----------------------------------------------------------------------===//
01511 // ParmVarDecl Implementation
01512 //===----------------------------------------------------------------------===//
01513 
01514 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
01515                                  SourceLocation StartLoc,
01516                                  SourceLocation IdLoc, IdentifierInfo *Id,
01517                                  QualType T, TypeSourceInfo *TInfo,
01518                                  StorageClass S, StorageClass SCAsWritten,
01519                                  Expr *DefArg) {
01520   return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
01521                              S, SCAsWritten, DefArg);
01522 }
01523 
01524 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
01525   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
01526   return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
01527                                0, QualType(), 0, SC_None, SC_None, 0);
01528 }
01529 
01530 SourceRange ParmVarDecl::getSourceRange() const {
01531   if (!hasInheritedDefaultArg()) {
01532     SourceRange ArgRange = getDefaultArgRange();
01533     if (ArgRange.isValid())
01534       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
01535   }
01536 
01537   return DeclaratorDecl::getSourceRange();
01538 }
01539 
01540 Expr *ParmVarDecl::getDefaultArg() {
01541   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
01542   assert(!hasUninstantiatedDefaultArg() &&
01543          "Default argument is not yet instantiated!");
01544   
01545   Expr *Arg = getInit();
01546   if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
01547     return E->getSubExpr();
01548 
01549   return Arg;
01550 }
01551 
01552 SourceRange ParmVarDecl::getDefaultArgRange() const {
01553   if (const Expr *E = getInit())
01554     return E->getSourceRange();
01555 
01556   if (hasUninstantiatedDefaultArg())
01557     return getUninstantiatedDefaultArg()->getSourceRange();
01558 
01559   return SourceRange();
01560 }
01561 
01562 bool ParmVarDecl::isParameterPack() const {
01563   return isa<PackExpansionType>(getType());
01564 }
01565 
01566 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
01567   getASTContext().setParameterIndex(this, parameterIndex);
01568   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
01569 }
01570 
01571 unsigned ParmVarDecl::getParameterIndexLarge() const {
01572   return getASTContext().getParameterIndex(this);
01573 }
01574 
01575 //===----------------------------------------------------------------------===//
01576 // FunctionDecl Implementation
01577 //===----------------------------------------------------------------------===//
01578 
01579 void FunctionDecl::getNameForDiagnostic(std::string &S,
01580                                         const PrintingPolicy &Policy,
01581                                         bool Qualified) const {
01582   NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
01583   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
01584   if (TemplateArgs)
01585     S += TemplateSpecializationType::PrintTemplateArgumentList(
01586                                                          TemplateArgs->data(),
01587                                                          TemplateArgs->size(),
01588                                                                Policy);
01589     
01590 }
01591 
01592 bool FunctionDecl::isVariadic() const {
01593   if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
01594     return FT->isVariadic();
01595   return false;
01596 }
01597 
01598 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
01599   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
01600     if (I->Body || I->IsLateTemplateParsed) {
01601       Definition = *I;
01602       return true;
01603     }
01604   }
01605 
01606   return false;
01607 }
01608 
01609 bool FunctionDecl::hasTrivialBody() const
01610 {
01611   Stmt *S = getBody();
01612   if (!S) {
01613     // Since we don't have a body for this function, we don't know if it's
01614     // trivial or not.
01615     return false;
01616   }
01617 
01618   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
01619     return true;
01620   return false;
01621 }
01622 
01623 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
01624   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
01625     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
01626       Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
01627       return true;
01628     }
01629   }
01630 
01631   return false;
01632 }
01633 
01634 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
01635   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
01636     if (I->Body) {
01637       Definition = *I;
01638       return I->Body.get(getASTContext().getExternalSource());
01639     } else if (I->IsLateTemplateParsed) {
01640       Definition = *I;
01641       return 0;
01642     }
01643   }
01644 
01645   return 0;
01646 }
01647 
01648 void FunctionDecl::setBody(Stmt *B) {
01649   Body = B;
01650   if (B)
01651     EndRangeLoc = B->getLocEnd();
01652 }
01653 
01654 void FunctionDecl::setPure(bool P) {
01655   IsPure = P;
01656   if (P)
01657     if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
01658       Parent->markedVirtualFunctionPure();
01659 }
01660 
01661 bool FunctionDecl::isMain() const {
01662   const TranslationUnitDecl *tunit =
01663     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
01664   return tunit &&
01665          !tunit->getASTContext().getLangOpts().Freestanding &&
01666          getIdentifier() &&
01667          getIdentifier()->isStr("main");
01668 }
01669 
01670 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
01671   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
01672   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
01673          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
01674          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
01675          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
01676 
01677   if (isa<CXXRecordDecl>(getDeclContext())) return false;
01678   assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
01679 
01680   const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
01681   if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
01682 
01683   ASTContext &Context =
01684     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
01685       ->getASTContext();
01686 
01687   // The result type and first argument type are constant across all
01688   // these operators.  The second argument must be exactly void*.
01689   return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
01690 }
01691 
01692 bool FunctionDecl::isExternC() const {
01693   if (getLinkage() != ExternalLinkage)
01694     return false;
01695 
01696   if (getAttr<OverloadableAttr>())
01697     return false;
01698 
01699   const DeclContext *DC = getDeclContext();
01700   if (DC->isRecord())
01701     return false;
01702 
01703   ASTContext &Context = getASTContext();
01704   if (!Context.getLangOpts().CPlusPlus)
01705     return true;
01706 
01707   return isMain() || DC->isExternCContext();
01708 }
01709 
01710 bool FunctionDecl::isGlobal() const {
01711   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
01712     return Method->isStatic();
01713 
01714   if (getStorageClass() == SC_Static)
01715     return false;
01716 
01717   for (const DeclContext *DC = getDeclContext();
01718        DC->isNamespace();
01719        DC = DC->getParent()) {
01720     if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
01721       if (!Namespace->getDeclName())
01722         return false;
01723       break;
01724     }
01725   }
01726 
01727   return true;
01728 }
01729 
01730 void
01731 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
01732   redeclarable_base::setPreviousDeclaration(PrevDecl);
01733 
01734   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
01735     FunctionTemplateDecl *PrevFunTmpl
01736       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
01737     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
01738     FunTmpl->setPreviousDeclaration(PrevFunTmpl);
01739   }
01740   
01741   if (PrevDecl && PrevDecl->IsInline)
01742     IsInline = true;
01743 }
01744 
01745 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
01746   return getFirstDeclaration();
01747 }
01748 
01749 FunctionDecl *FunctionDecl::getCanonicalDecl() {
01750   return getFirstDeclaration();
01751 }
01752 
01753 void FunctionDecl::setStorageClass(StorageClass SC) {
01754   assert(isLegalForFunction(SC));
01755   if (getStorageClass() != SC)
01756     ClearLinkageCache();
01757   
01758   SClass = SC;
01759 }
01760 
01761 /// \brief Returns a value indicating whether this function
01762 /// corresponds to a builtin function.
01763 ///
01764 /// The function corresponds to a built-in function if it is
01765 /// declared at translation scope or within an extern "C" block and
01766 /// its name matches with the name of a builtin. The returned value
01767 /// will be 0 for functions that do not correspond to a builtin, a
01768 /// value of type \c Builtin::ID if in the target-independent range
01769 /// \c [1,Builtin::First), or a target-specific builtin value.
01770 unsigned FunctionDecl::getBuiltinID() const {
01771   if (!getIdentifier())
01772     return 0;
01773 
01774   unsigned BuiltinID = getIdentifier()->getBuiltinID();
01775   if (!BuiltinID)
01776     return 0;
01777 
01778   ASTContext &Context = getASTContext();
01779   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
01780     return BuiltinID;
01781 
01782   // This function has the name of a known C library
01783   // function. Determine whether it actually refers to the C library
01784   // function or whether it just has the same name.
01785 
01786   // If this is a static function, it's not a builtin.
01787   if (getStorageClass() == SC_Static)
01788     return 0;
01789 
01790   // If this function is at translation-unit scope and we're not in
01791   // C++, it refers to the C library function.
01792   if (!Context.getLangOpts().CPlusPlus &&
01793       getDeclContext()->isTranslationUnit())
01794     return BuiltinID;
01795 
01796   // If the function is in an extern "C" linkage specification and is
01797   // not marked "overloadable", it's the real function.
01798   if (isa<LinkageSpecDecl>(getDeclContext()) &&
01799       cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
01800         == LinkageSpecDecl::lang_c &&
01801       !getAttr<OverloadableAttr>())
01802     return BuiltinID;
01803 
01804   // Not a builtin
01805   return 0;
01806 }
01807 
01808 
01809 /// getNumParams - Return the number of parameters this function must have
01810 /// based on its FunctionType.  This is the length of the ParamInfo array
01811 /// after it has been created.
01812 unsigned FunctionDecl::getNumParams() const {
01813   const FunctionType *FT = getType()->getAs<FunctionType>();
01814   if (isa<FunctionNoProtoType>(FT))
01815     return 0;
01816   return cast<FunctionProtoType>(FT)->getNumArgs();
01817 
01818 }
01819 
01820 void FunctionDecl::setParams(ASTContext &C,
01821                              llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
01822   assert(ParamInfo == 0 && "Already has param info!");
01823   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
01824 
01825   // Zero params -> null pointer.
01826   if (!NewParamInfo.empty()) {
01827     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
01828     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
01829   }
01830 }
01831 
01832 void FunctionDecl::setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls) {
01833   assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
01834 
01835   if (!NewDecls.empty()) {
01836     NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
01837     std::copy(NewDecls.begin(), NewDecls.end(), A);
01838     DeclsInPrototypeScope = llvm::ArrayRef<NamedDecl*>(A, NewDecls.size());
01839   }
01840 }
01841 
01842 /// getMinRequiredArguments - Returns the minimum number of arguments
01843 /// needed to call this function. This may be fewer than the number of
01844 /// function parameters, if some of the parameters have default
01845 /// arguments (in C++) or the last parameter is a parameter pack.
01846 unsigned FunctionDecl::getMinRequiredArguments() const {
01847   if (!getASTContext().getLangOpts().CPlusPlus)
01848     return getNumParams();
01849   
01850   unsigned NumRequiredArgs = getNumParams();  
01851   
01852   // If the last parameter is a parameter pack, we don't need an argument for 
01853   // it.
01854   if (NumRequiredArgs > 0 &&
01855       getParamDecl(NumRequiredArgs - 1)->isParameterPack())
01856     --NumRequiredArgs;
01857       
01858   // If this parameter has a default argument, we don't need an argument for
01859   // it.
01860   while (NumRequiredArgs > 0 &&
01861          getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
01862     --NumRequiredArgs;
01863 
01864   // We might have parameter packs before the end. These can't be deduced,
01865   // but they can still handle multiple arguments.
01866   unsigned ArgIdx = NumRequiredArgs;
01867   while (ArgIdx > 0) {
01868     if (getParamDecl(ArgIdx - 1)->isParameterPack())
01869       NumRequiredArgs = ArgIdx;
01870     
01871     --ArgIdx;
01872   }
01873   
01874   return NumRequiredArgs;
01875 }
01876 
01877 bool FunctionDecl::isInlined() const {
01878   if (IsInline)
01879     return true;
01880   
01881   if (isa<CXXMethodDecl>(this)) {
01882     if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
01883       return true;
01884   }
01885 
01886   switch (getTemplateSpecializationKind()) {
01887   case TSK_Undeclared:
01888   case TSK_ExplicitSpecialization:
01889     return false;
01890 
01891   case TSK_ImplicitInstantiation:
01892   case TSK_ExplicitInstantiationDeclaration:
01893   case TSK_ExplicitInstantiationDefinition:
01894     // Handle below.
01895     break;
01896   }
01897 
01898   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
01899   bool HasPattern = false;
01900   if (PatternDecl)
01901     HasPattern = PatternDecl->hasBody(PatternDecl);
01902   
01903   if (HasPattern && PatternDecl)
01904     return PatternDecl->isInlined();
01905   
01906   return false;
01907 }
01908 
01909 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
01910   // Only consider file-scope declarations in this test.
01911   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
01912     return false;
01913 
01914   // Only consider explicit declarations; the presence of a builtin for a
01915   // libcall shouldn't affect whether a definition is externally visible.
01916   if (Redecl->isImplicit())
01917     return false;
01918 
01919   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 
01920     return true; // Not an inline definition
01921 
01922   return false;
01923 }
01924 
01925 /// \brief For a function declaration in C or C++, determine whether this
01926 /// declaration causes the definition to be externally visible.
01927 ///
01928 /// Specifically, this determines if adding the current declaration to the set
01929 /// of redeclarations of the given functions causes
01930 /// isInlineDefinitionExternallyVisible to change from false to true.
01931 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
01932   assert(!doesThisDeclarationHaveABody() &&
01933          "Must have a declaration without a body.");
01934 
01935   ASTContext &Context = getASTContext();
01936 
01937   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
01938     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
01939     // an externally visible definition.
01940     //
01941     // FIXME: What happens if gnu_inline gets added on after the first
01942     // declaration?
01943     if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
01944       return false;
01945 
01946     const FunctionDecl *Prev = this;
01947     bool FoundBody = false;
01948     while ((Prev = Prev->getPreviousDecl())) {
01949       FoundBody |= Prev->Body;
01950 
01951       if (Prev->Body) {
01952         // If it's not the case that both 'inline' and 'extern' are
01953         // specified on the definition, then it is always externally visible.
01954         if (!Prev->isInlineSpecified() ||
01955             Prev->getStorageClassAsWritten() != SC_Extern)
01956           return false;
01957       } else if (Prev->isInlineSpecified() && 
01958                  Prev->getStorageClassAsWritten() != SC_Extern) {
01959         return false;
01960       }
01961     }
01962     return FoundBody;
01963   }
01964 
01965   if (Context.getLangOpts().CPlusPlus)
01966     return false;
01967 
01968   // C99 6.7.4p6:
01969   //   [...] If all of the file scope declarations for a function in a 
01970   //   translation unit include the inline function specifier without extern, 
01971   //   then the definition in that translation unit is an inline definition.
01972   if (isInlineSpecified() && getStorageClass() != SC_Extern)
01973     return false;
01974   const FunctionDecl *Prev = this;
01975   bool FoundBody = false;
01976   while ((Prev = Prev->getPreviousDecl())) {
01977     FoundBody |= Prev->Body;
01978     if (RedeclForcesDefC99(Prev))
01979       return false;
01980   }
01981   return FoundBody;
01982 }
01983 
01984 /// \brief For an inline function definition in C or C++, determine whether the 
01985 /// definition will be externally visible.
01986 ///
01987 /// Inline function definitions are always available for inlining optimizations.
01988 /// However, depending on the language dialect, declaration specifiers, and
01989 /// attributes, the definition of an inline function may or may not be
01990 /// "externally" visible to other translation units in the program.
01991 ///
01992 /// In C99, inline definitions are not externally visible by default. However,
01993 /// if even one of the global-scope declarations is marked "extern inline", the
01994 /// inline definition becomes externally visible (C99 6.7.4p6).
01995 ///
01996 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
01997 /// definition, we use the GNU semantics for inline, which are nearly the 
01998 /// opposite of C99 semantics. In particular, "inline" by itself will create 
01999 /// an externally visible symbol, but "extern inline" will not create an 
02000 /// externally visible symbol.
02001 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
02002   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
02003   assert(isInlined() && "Function must be inline");
02004   ASTContext &Context = getASTContext();
02005   
02006   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
02007     // Note: If you change the logic here, please change
02008     // doesDeclarationForceExternallyVisibleDefinition as well.
02009     //
02010     // If it's not the case that both 'inline' and 'extern' are
02011     // specified on the definition, then this inline definition is
02012     // externally visible.
02013     if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
02014       return true;
02015     
02016     // If any declaration is 'inline' but not 'extern', then this definition
02017     // is externally visible.
02018     for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
02019          Redecl != RedeclEnd;
02020          ++Redecl) {
02021       if (Redecl->isInlineSpecified() && 
02022           Redecl->getStorageClassAsWritten() != SC_Extern)
02023         return true;
02024     }    
02025     
02026     return false;
02027   }
02028 
02029   // C99 6.7.4p6:
02030   //   [...] If all of the file scope declarations for a function in a 
02031   //   translation unit include the inline function specifier without extern, 
02032   //   then the definition in that translation unit is an inline definition.
02033   for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
02034        Redecl != RedeclEnd;
02035        ++Redecl) {
02036     if (RedeclForcesDefC99(*Redecl))
02037       return true;
02038   }
02039   
02040   // C99 6.7.4p6:
02041   //   An inline definition does not provide an external definition for the 
02042   //   function, and does not forbid an external definition in another 
02043   //   translation unit.
02044   return false;
02045 }
02046 
02047 /// getOverloadedOperator - Which C++ overloaded operator this
02048 /// function represents, if any.
02049 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
02050   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
02051     return getDeclName().getCXXOverloadedOperator();
02052   else
02053     return OO_None;
02054 }
02055 
02056 /// getLiteralIdentifier - The literal suffix identifier this function
02057 /// represents, if any.
02058 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
02059   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
02060     return getDeclName().getCXXLiteralIdentifier();
02061   else
02062     return 0;
02063 }
02064 
02065 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
02066   if (TemplateOrSpecialization.isNull())
02067     return TK_NonTemplate;
02068   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
02069     return TK_FunctionTemplate;
02070   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
02071     return TK_MemberSpecialization;
02072   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
02073     return TK_FunctionTemplateSpecialization;
02074   if (TemplateOrSpecialization.is
02075                                <DependentFunctionTemplateSpecializationInfo*>())
02076     return TK_DependentFunctionTemplateSpecialization;
02077 
02078   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
02079 }
02080 
02081 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
02082   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
02083     return cast<FunctionDecl>(Info->getInstantiatedFrom());
02084   
02085   return 0;
02086 }
02087 
02088 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
02089   return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
02090 }
02091 
02092 void 
02093 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
02094                                                FunctionDecl *FD,
02095                                                TemplateSpecializationKind TSK) {
02096   assert(TemplateOrSpecialization.isNull() && 
02097          "Member function is already a specialization");
02098   MemberSpecializationInfo *Info 
02099     = new (C) MemberSpecializationInfo(FD, TSK);
02100   TemplateOrSpecialization = Info;
02101 }
02102 
02103 bool FunctionDecl::isImplicitlyInstantiable() const {
02104   // If the function is invalid, it can't be implicitly instantiated.
02105   if (isInvalidDecl())
02106     return false;
02107   
02108   switch (getTemplateSpecializationKind()) {
02109   case TSK_Undeclared:
02110   case TSK_ExplicitInstantiationDefinition:
02111     return false;
02112       
02113   case TSK_ImplicitInstantiation:
02114     return true;
02115 
02116   // It is possible to instantiate TSK_ExplicitSpecialization kind
02117   // if the FunctionDecl has a class scope specialization pattern.
02118   case TSK_ExplicitSpecialization:
02119     return getClassScopeSpecializationPattern() != 0;
02120 
02121   case TSK_ExplicitInstantiationDeclaration:
02122     // Handled below.
02123     break;
02124   }
02125 
02126   // Find the actual template from which we will instantiate.
02127   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
02128   bool HasPattern = false;
02129   if (PatternDecl)
02130     HasPattern = PatternDecl->hasBody(PatternDecl);
02131   
02132   // C++0x [temp.explicit]p9:
02133   //   Except for inline functions, other explicit instantiation declarations
02134   //   have the effect of suppressing the implicit instantiation of the entity
02135   //   to which they refer. 
02136   if (!HasPattern || !PatternDecl) 
02137     return true;
02138 
02139   return PatternDecl->isInlined();
02140 }
02141 
02142 bool FunctionDecl::isTemplateInstantiation() const {
02143   switch (getTemplateSpecializationKind()) {
02144     case TSK_Undeclared:
02145     case TSK_ExplicitSpecialization:
02146       return false;      
02147     case TSK_ImplicitInstantiation:
02148     case TSK_ExplicitInstantiationDeclaration:
02149     case TSK_ExplicitInstantiationDefinition:
02150       return true;
02151   }
02152   llvm_unreachable("All TSK values handled.");
02153 }
02154    
02155 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
02156   // Handle class scope explicit specialization special case.
02157   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
02158     return getClassScopeSpecializationPattern();
02159 
02160   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
02161     while (Primary->getInstantiatedFromMemberTemplate()) {
02162       // If we have hit a point where the user provided a specialization of
02163       // this template, we're done looking.
02164       if (Primary->isMemberSpecialization())
02165         break;
02166       
02167       Primary = Primary->getInstantiatedFromMemberTemplate();
02168     }
02169     
02170     return Primary->getTemplatedDecl();
02171   } 
02172     
02173   return getInstantiatedFromMemberFunction();
02174 }
02175 
02176 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
02177   if (FunctionTemplateSpecializationInfo *Info
02178         = TemplateOrSpecialization
02179             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
02180     return Info->Template.getPointer();
02181   }
02182   return 0;
02183 }
02184 
02185 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
02186     return getASTContext().getClassScopeSpecializationPattern(this);
02187 }
02188 
02189 const TemplateArgumentList *
02190 FunctionDecl::getTemplateSpecializationArgs() const {
02191   if (FunctionTemplateSpecializationInfo *Info
02192         = TemplateOrSpecialization
02193             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
02194     return Info->TemplateArguments;
02195   }
02196   return 0;
02197 }
02198 
02199 const ASTTemplateArgumentListInfo *
02200 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
02201   if (FunctionTemplateSpecializationInfo *Info
02202         = TemplateOrSpecialization
02203             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
02204     return Info->TemplateArgumentsAsWritten;
02205   }
02206   return 0;
02207 }
02208 
02209 void
02210 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
02211                                                 FunctionTemplateDecl *Template,
02212                                      const TemplateArgumentList *TemplateArgs,
02213                                                 void *InsertPos,
02214                                                 TemplateSpecializationKind TSK,
02215                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
02216                                           SourceLocation PointOfInstantiation) {
02217   assert(TSK != TSK_Undeclared && 
02218          "Must specify the type of function template specialization");
02219   FunctionTemplateSpecializationInfo *Info
02220     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
02221   if (!Info)
02222     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
02223                                                       TemplateArgs,
02224                                                       TemplateArgsAsWritten,
02225                                                       PointOfInstantiation);
02226   TemplateOrSpecialization = Info;
02227   Template->addSpecialization(Info, InsertPos);
02228 }
02229 
02230 void
02231 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
02232                                     const UnresolvedSetImpl &Templates,
02233                              const TemplateArgumentListInfo &TemplateArgs) {
02234   assert(TemplateOrSpecialization.isNull());
02235   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
02236   Size += Templates.size() * sizeof(FunctionTemplateDecl*);
02237   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
02238   void *Buffer = Context.Allocate(Size);
02239   DependentFunctionTemplateSpecializationInfo *Info =
02240     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
02241                                                              TemplateArgs);
02242   TemplateOrSpecialization = Info;
02243 }
02244 
02245 DependentFunctionTemplateSpecializationInfo::
02246 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
02247                                       const TemplateArgumentListInfo &TArgs)
02248   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
02249 
02250   d.NumTemplates = Ts.size();
02251   d.NumArgs = TArgs.size();
02252 
02253   FunctionTemplateDecl **TsArray =
02254     const_cast<FunctionTemplateDecl**>(getTemplates());
02255   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
02256     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
02257 
02258   TemplateArgumentLoc *ArgsArray =
02259     const_cast<TemplateArgumentLoc*>(getTemplateArgs());
02260   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
02261     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
02262 }
02263 
02264 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
02265   // For a function template specialization, query the specialization
02266   // information object.
02267   FunctionTemplateSpecializationInfo *FTSInfo
02268     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
02269   if (FTSInfo)
02270     return FTSInfo->getTemplateSpecializationKind();
02271 
02272   MemberSpecializationInfo *MSInfo
02273     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
02274   if (MSInfo)
02275     return MSInfo->getTemplateSpecializationKind();
02276   
02277   return TSK_Undeclared;
02278 }
02279 
02280 void
02281 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
02282                                           SourceLocation PointOfInstantiation) {
02283   if (FunctionTemplateSpecializationInfo *FTSInfo
02284         = TemplateOrSpecialization.dyn_cast<
02285                                     FunctionTemplateSpecializationInfo*>()) {
02286     FTSInfo->setTemplateSpecializationKind(TSK);
02287     if (TSK != TSK_ExplicitSpecialization &&
02288         PointOfInstantiation.isValid() &&
02289         FTSInfo->getPointOfInstantiation().isInvalid())
02290       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
02291   } else if (MemberSpecializationInfo *MSInfo
02292              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
02293     MSInfo->setTemplateSpecializationKind(TSK);
02294     if (TSK != TSK_ExplicitSpecialization &&
02295         PointOfInstantiation.isValid() &&
02296         MSInfo->getPointOfInstantiation().isInvalid())
02297       MSInfo->setPointOfInstantiation(PointOfInstantiation);
02298   } else
02299     llvm_unreachable("Function cannot have a template specialization kind");
02300 }
02301 
02302 SourceLocation FunctionDecl::getPointOfInstantiation() const {
02303   if (FunctionTemplateSpecializationInfo *FTSInfo
02304         = TemplateOrSpecialization.dyn_cast<
02305                                         FunctionTemplateSpecializationInfo*>())
02306     return FTSInfo->getPointOfInstantiation();
02307   else if (MemberSpecializationInfo *MSInfo
02308              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
02309     return MSInfo->getPointOfInstantiation();
02310   
02311   return SourceLocation();
02312 }
02313 
02314 bool FunctionDecl::isOutOfLine() const {
02315   if (Decl::isOutOfLine())
02316     return true;
02317   
02318   // If this function was instantiated from a member function of a 
02319   // class template, check whether that member function was defined out-of-line.
02320   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
02321     const FunctionDecl *Definition;
02322     if (FD->hasBody(Definition))
02323       return Definition->isOutOfLine();
02324   }
02325   
02326   // If this function was instantiated from a function template,
02327   // check whether that function template was defined out-of-line.
02328   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
02329     const FunctionDecl *Definition;
02330     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
02331       return Definition->isOutOfLine();
02332   }
02333   
02334   return false;
02335 }
02336 
02337 SourceRange FunctionDecl::getSourceRange() const {
02338   return SourceRange(getOuterLocStart(), EndRangeLoc);
02339 }
02340 
02341 unsigned FunctionDecl::getMemoryFunctionKind() const {
02342   IdentifierInfo *FnInfo = getIdentifier();
02343 
02344   if (!FnInfo)
02345     return 0;
02346     
02347   // Builtin handling.
02348   switch (getBuiltinID()) {
02349   case Builtin::BI__builtin_memset:
02350   case Builtin::BI__builtin___memset_chk:
02351   case Builtin::BImemset:
02352     return Builtin::BImemset;
02353 
02354   case Builtin::BI__builtin_memcpy:
02355   case Builtin::BI__builtin___memcpy_chk:
02356   case Builtin::BImemcpy:
02357     return Builtin::BImemcpy;
02358 
02359   case Builtin::BI__builtin_memmove:
02360   case Builtin::BI__builtin___memmove_chk:
02361   case Builtin::BImemmove:
02362     return Builtin::BImemmove;
02363 
02364   case Builtin::BIstrlcpy:
02365     return Builtin::BIstrlcpy;
02366   case Builtin::BIstrlcat:
02367     return Builtin::BIstrlcat;
02368 
02369   case Builtin::BI__builtin_memcmp:
02370   case Builtin::BImemcmp:
02371     return Builtin::BImemcmp;
02372 
02373   case Builtin::BI__builtin_strncpy:
02374   case Builtin::BI__builtin___strncpy_chk:
02375   case Builtin::BIstrncpy:
02376     return Builtin::BIstrncpy;
02377 
02378   case Builtin::BI__builtin_strncmp:
02379   case Builtin::BIstrncmp:
02380     return Builtin::BIstrncmp;
02381 
02382   case Builtin::BI__builtin_strncasecmp:
02383   case Builtin::BIstrncasecmp:
02384     return Builtin::BIstrncasecmp;
02385 
02386   case Builtin::BI__builtin_strncat:
02387   case Builtin::BI__builtin___strncat_chk:
02388   case Builtin::BIstrncat:
02389     return Builtin::BIstrncat;
02390 
02391   case Builtin::BI__builtin_strndup:
02392   case Builtin::BIstrndup:
02393     return Builtin::BIstrndup;
02394 
02395   case Builtin::BI__builtin_strlen:
02396   case Builtin::BIstrlen:
02397     return Builtin::BIstrlen;
02398 
02399   default:
02400     if (isExternC()) {
02401       if (FnInfo->isStr("memset"))
02402         return Builtin::BImemset;
02403       else if (FnInfo->isStr("memcpy"))
02404         return Builtin::BImemcpy;
02405       else if (FnInfo->isStr("memmove"))
02406         return Builtin::BImemmove;
02407       else if (FnInfo->isStr("memcmp"))
02408         return Builtin::BImemcmp;
02409       else if (FnInfo->isStr("strncpy"))
02410         return Builtin::BIstrncpy;
02411       else if (FnInfo->isStr("strncmp"))
02412         return Builtin::BIstrncmp;
02413       else if (FnInfo->isStr("strncasecmp"))
02414         return Builtin::BIstrncasecmp;
02415       else if (FnInfo->isStr("strncat"))
02416         return Builtin::BIstrncat;
02417       else if (FnInfo->isStr("strndup"))
02418         return Builtin::BIstrndup;
02419       else if (FnInfo->isStr("strlen"))
02420         return Builtin::BIstrlen;
02421     }
02422     break;
02423   }
02424   return 0;
02425 }
02426 
02427 //===----------------------------------------------------------------------===//
02428 // FieldDecl Implementation
02429 //===----------------------------------------------------------------------===//
02430 
02431 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
02432                              SourceLocation StartLoc, SourceLocation IdLoc,
02433                              IdentifierInfo *Id, QualType T,
02434                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
02435                              bool HasInit) {
02436   return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
02437                            BW, Mutable, HasInit);
02438 }
02439 
02440 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02441   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
02442   return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
02443                              0, QualType(), 0, 0, false, false);
02444 }
02445 
02446 bool FieldDecl::isAnonymousStructOrUnion() const {
02447   if (!isImplicit() || getDeclName())
02448     return false;
02449 
02450   if (const RecordType *Record = getType()->getAs<RecordType>())
02451     return Record->getDecl()->isAnonymousStructOrUnion();
02452 
02453   return false;
02454 }
02455 
02456 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
02457   assert(isBitField() && "not a bitfield");
02458   Expr *BitWidth = InitializerOrBitWidth.getPointer();
02459   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
02460 }
02461 
02462 unsigned FieldDecl::getFieldIndex() const {
02463   if (CachedFieldIndex) return CachedFieldIndex - 1;
02464 
02465   unsigned Index = 0;
02466   const RecordDecl *RD = getParent();
02467   const FieldDecl *LastFD = 0;
02468   bool IsMsStruct = RD->hasAttr<MsStructAttr>();
02469 
02470   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
02471        I != E; ++I, ++Index) {
02472     I->CachedFieldIndex = Index + 1;
02473 
02474     if (IsMsStruct) {
02475       // Zero-length bitfields following non-bitfield members are ignored.
02476       if (getASTContext().ZeroBitfieldFollowsNonBitfield(&*I, LastFD)) {
02477         --Index;
02478         continue;
02479       }
02480       LastFD = &*I;
02481     }
02482   }
02483 
02484   assert(CachedFieldIndex && "failed to find field in parent");
02485   return CachedFieldIndex - 1;
02486 }
02487 
02488 SourceRange FieldDecl::getSourceRange() const {
02489   if (const Expr *E = InitializerOrBitWidth.getPointer())
02490     return SourceRange(getInnerLocStart(), E->getLocEnd());
02491   return DeclaratorDecl::getSourceRange();
02492 }
02493 
02494 void FieldDecl::setInClassInitializer(Expr *Init) {
02495   assert(!InitializerOrBitWidth.getPointer() &&
02496          "bit width or initializer already set");
02497   InitializerOrBitWidth.setPointer(Init);
02498   InitializerOrBitWidth.setInt(0);
02499 }
02500 
02501 //===----------------------------------------------------------------------===//
02502 // TagDecl Implementation
02503 //===----------------------------------------------------------------------===//
02504 
02505 SourceLocation TagDecl::getOuterLocStart() const {
02506   return getTemplateOrInnerLocStart(this);
02507 }
02508 
02509 SourceRange TagDecl::getSourceRange() const {
02510   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
02511   return SourceRange(getOuterLocStart(), E);
02512 }
02513 
02514 TagDecl* TagDecl::getCanonicalDecl() {
02515   return getFirstDeclaration();
02516 }
02517 
02518 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 
02519   TypedefNameDeclOrQualifier = TDD; 
02520   if (TypeForDecl)
02521     const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
02522   ClearLinkageCache();
02523 }
02524 
02525 void TagDecl::startDefinition() {
02526   IsBeingDefined = true;
02527 
02528   if (isa<CXXRecordDecl>(this)) {
02529     CXXRecordDecl *D = cast<CXXRecordDecl>(this);
02530     struct CXXRecordDecl::DefinitionData *Data = 
02531       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
02532     for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
02533       cast<CXXRecordDecl>(*I)->DefinitionData = Data;
02534   }
02535 }
02536 
02537 void TagDecl::completeDefinition() {
02538   assert((!isa<CXXRecordDecl>(this) ||
02539           cast<CXXRecordDecl>(this)->hasDefinition()) &&
02540          "definition completed but not started");
02541 
02542   IsCompleteDefinition = true;
02543   IsBeingDefined = false;
02544 
02545   if (ASTMutationListener *L = getASTMutationListener())
02546     L->CompletedTagDefinition(this);
02547 }
02548 
02549 TagDecl *TagDecl::getDefinition() const {
02550   if (isCompleteDefinition())
02551     return const_cast<TagDecl *>(this);
02552   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
02553     return CXXRD->getDefinition();
02554 
02555   for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
02556        R != REnd; ++R)
02557     if (R->isCompleteDefinition())
02558       return *R;
02559 
02560   return 0;
02561 }
02562 
02563 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
02564   if (QualifierLoc) {
02565     // Make sure the extended qualifier info is allocated.
02566     if (!hasExtInfo())
02567       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
02568     // Set qualifier info.
02569     getExtInfo()->QualifierLoc = QualifierLoc;
02570   } else {
02571     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
02572     if (hasExtInfo()) {
02573       if (getExtInfo()->NumTemplParamLists == 0) {
02574         getASTContext().Deallocate(getExtInfo());
02575         TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
02576       }
02577       else
02578         getExtInfo()->QualifierLoc = QualifierLoc;
02579     }
02580   }
02581 }
02582 
02583 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
02584                                             unsigned NumTPLists,
02585                                             TemplateParameterList **TPLists) {
02586   assert(NumTPLists > 0);
02587   // Make sure the extended decl info is allocated.
02588   if (!hasExtInfo())
02589     // Allocate external info struct.
02590     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
02591   // Set the template parameter lists info.
02592   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
02593 }
02594 
02595 //===----------------------------------------------------------------------===//
02596 // EnumDecl Implementation
02597 //===----------------------------------------------------------------------===//
02598 
02599 void EnumDecl::anchor() { }
02600 
02601 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
02602                            SourceLocation StartLoc, SourceLocation IdLoc,
02603                            IdentifierInfo *Id,
02604                            EnumDecl *PrevDecl, bool IsScoped,
02605                            bool IsScopedUsingClassTag, bool IsFixed) {
02606   EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
02607                                     IsScoped, IsScopedUsingClassTag, IsFixed);
02608   C.getTypeDeclType(Enum, PrevDecl);
02609   return Enum;
02610 }
02611 
02612 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02613   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
02614   return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
02615                             false, false, false);
02616 }
02617 
02618 void EnumDecl::completeDefinition(QualType NewType,
02619                                   QualType NewPromotionType,
02620                                   unsigned NumPositiveBits,
02621                                   unsigned NumNegativeBits) {
02622   assert(!isCompleteDefinition() && "Cannot redefine enums!");
02623   if (!IntegerType)
02624     IntegerType = NewType.getTypePtr();
02625   PromotionType = NewPromotionType;
02626   setNumPositiveBits(NumPositiveBits);
02627   setNumNegativeBits(NumNegativeBits);
02628   TagDecl::completeDefinition();
02629 }
02630 
02631 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
02632   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
02633     return MSI->getTemplateSpecializationKind();
02634 
02635   return TSK_Undeclared;
02636 }
02637 
02638 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
02639                                          SourceLocation PointOfInstantiation) {
02640   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
02641   assert(MSI && "Not an instantiated member enumeration?");
02642   MSI->setTemplateSpecializationKind(TSK);
02643   if (TSK != TSK_ExplicitSpecialization &&
02644       PointOfInstantiation.isValid() &&
02645       MSI->getPointOfInstantiation().isInvalid())
02646     MSI->setPointOfInstantiation(PointOfInstantiation);
02647 }
02648 
02649 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
02650   if (SpecializationInfo)
02651     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
02652 
02653   return 0;
02654 }
02655 
02656 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
02657                                             TemplateSpecializationKind TSK) {
02658   assert(!SpecializationInfo && "Member enum is already a specialization");
02659   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
02660 }
02661 
02662 //===----------------------------------------------------------------------===//
02663 // RecordDecl Implementation
02664 //===----------------------------------------------------------------------===//
02665 
02666 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
02667                        SourceLocation StartLoc, SourceLocation IdLoc,
02668                        IdentifierInfo *Id, RecordDecl *PrevDecl)
02669   : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
02670   HasFlexibleArrayMember = false;
02671   AnonymousStructOrUnion = false;
02672   HasObjectMember = false;
02673   LoadedFieldsFromExternalStorage = false;
02674   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
02675 }
02676 
02677 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
02678                                SourceLocation StartLoc, SourceLocation IdLoc,
02679                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
02680   RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
02681                                      PrevDecl);
02682   C.getTypeDeclType(R, PrevDecl);
02683   return R;
02684 }
02685 
02686 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
02687   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
02688   return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
02689                               SourceLocation(), 0, 0);
02690 }
02691 
02692 bool RecordDecl::isInjectedClassName() const {
02693   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
02694     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
02695 }
02696 
02697 RecordDecl::field_iterator RecordDecl::field_begin() const {
02698   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
02699     LoadFieldsFromExternalStorage();
02700 
02701   return field_iterator(decl_iterator(FirstDecl));
02702 }
02703 
02704 /// completeDefinition - Notes that the definition of this type is now
02705 /// complete.
02706 void RecordDecl::completeDefinition() {
02707   assert(!isCompleteDefinition() && "Cannot redefine record!");
02708   TagDecl::completeDefinition();
02709 }
02710 
02711 void RecordDecl::LoadFieldsFromExternalStorage() const {
02712   ExternalASTSource *Source = getASTContext().getExternalSource();
02713   assert(hasExternalLexicalStorage() && Source && "No external storage?");
02714 
02715   // Notify that we have a RecordDecl doing some initialization.
02716   ExternalASTSource::Deserializing TheFields(Source);
02717 
02718   SmallVector<Decl*, 64> Decls;
02719   LoadedFieldsFromExternalStorage = true;  
02720   switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
02721   case ELR_Success:
02722     break;
02723     
02724   case ELR_AlreadyLoaded:
02725   case ELR_Failure:
02726     return;
02727   }
02728 
02729 #ifndef NDEBUG
02730   // Check that all decls we got were FieldDecls.
02731   for (unsigned i=0, e=Decls.size(); i != e; ++i)
02732     assert(isa<FieldDecl>(Decls[i]));
02733 #endif
02734 
02735   if (Decls.empty())
02736     return;
02737 
02738   llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
02739                                                  /*FieldsAlreadyLoaded=*/false);
02740 }
02741 
02742 //===----------------------------------------------------------------------===//
02743 // BlockDecl Implementation
02744 //===----------------------------------------------------------------------===//
02745 
02746 void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
02747   assert(ParamInfo == 0 && "Already has param info!");
02748 
02749   // Zero params -> null pointer.
02750   if (!NewParamInfo.empty()) {
02751     NumParams = NewParamInfo.size();
02752     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
02753     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
02754   }
02755 }
02756 
02757 void BlockDecl::setCaptures(ASTContext &Context,
02758                             const Capture *begin,
02759                             const Capture *end,
02760                             bool capturesCXXThis) {
02761   CapturesCXXThis = capturesCXXThis;
02762 
02763   if (begin == end) {
02764     NumCaptures = 0;
02765     Captures = 0;
02766     return;
02767   }
02768 
02769   NumCaptures = end - begin;
02770 
02771   // Avoid new Capture[] because we don't want to provide a default
02772   // constructor.
02773   size_t allocationSize = NumCaptures * sizeof(Capture);
02774   void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
02775   memcpy(buffer, begin, allocationSize);
02776   Captures = static_cast<Capture*>(buffer);
02777 }
02778 
02779 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
02780   for (capture_const_iterator
02781          i = capture_begin(), e = capture_end(); i != e; ++i)
02782     // Only auto vars can be captured, so no redeclaration worries.
02783     if (i->getVariable() == variable)
02784       return true;
02785 
02786   return false;
02787 }
02788 
02789 SourceRange BlockDecl::getSourceRange() const {
02790   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
02791 }
02792 
02793 //===----------------------------------------------------------------------===//
02794 // Other Decl Allocation/Deallocation Method Implementations
02795 //===----------------------------------------------------------------------===//
02796 
02797 void TranslationUnitDecl::anchor() { }
02798 
02799 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
02800   return new (C) TranslationUnitDecl(C);
02801 }
02802 
02803 void LabelDecl::anchor() { }
02804 
02805 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
02806                              SourceLocation IdentL, IdentifierInfo *II) {
02807   return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
02808 }
02809 
02810 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
02811                              SourceLocation IdentL, IdentifierInfo *II,
02812                              SourceLocation GnuLabelL) {
02813   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
02814   return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
02815 }
02816 
02817 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02818   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
02819   return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
02820 }
02821 
02822 void ValueDecl::anchor() { }
02823 
02824 void ImplicitParamDecl::anchor() { }
02825 
02826 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
02827                                              SourceLocation IdLoc,
02828                                              IdentifierInfo *Id,
02829                                              QualType Type) {
02830   return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
02831 }
02832 
02833 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 
02834                                                          unsigned ID) {
02835   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
02836   return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
02837 }
02838 
02839 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
02840                                    SourceLocation StartLoc,
02841                                    const DeclarationNameInfo &NameInfo,
02842                                    QualType T, TypeSourceInfo *TInfo,
02843                                    StorageClass SC, StorageClass SCAsWritten,
02844                                    bool isInlineSpecified, 
02845                                    bool hasWrittenPrototype,
02846                                    bool isConstexprSpecified) {
02847   FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
02848                                            T, TInfo, SC, SCAsWritten,
02849                                            isInlineSpecified,
02850                                            isConstexprSpecified);
02851   New->HasWrittenPrototype = hasWrittenPrototype;
02852   return New;
02853 }
02854 
02855 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02856   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
02857   return new (Mem) FunctionDecl(Function, 0, SourceLocation(), 
02858                                 DeclarationNameInfo(), QualType(), 0,
02859                                 SC_None, SC_None, false, false);
02860 }
02861 
02862 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
02863   return new (C) BlockDecl(DC, L);
02864 }
02865 
02866 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02867   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
02868   return new (Mem) BlockDecl(0, SourceLocation());
02869 }
02870 
02871 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
02872                                            SourceLocation L,
02873                                            IdentifierInfo *Id, QualType T,
02874                                            Expr *E, const llvm::APSInt &V) {
02875   return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
02876 }
02877 
02878 EnumConstantDecl *
02879 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02880   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
02881   return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0, 
02882                                     llvm::APSInt());
02883 }
02884 
02885 void IndirectFieldDecl::anchor() { }
02886 
02887 IndirectFieldDecl *
02888 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
02889                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
02890                           unsigned CHS) {
02891   return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
02892 }
02893 
02894 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
02895                                                          unsigned ID) {
02896   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
02897   return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
02898                                      QualType(), 0, 0);
02899 }
02900 
02901 SourceRange EnumConstantDecl::getSourceRange() const {
02902   SourceLocation End = getLocation();
02903   if (Init)
02904     End = Init->getLocEnd();
02905   return SourceRange(getLocation(), End);
02906 }
02907 
02908 void TypeDecl::anchor() { }
02909 
02910 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
02911                                  SourceLocation StartLoc, SourceLocation IdLoc,
02912                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
02913   return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
02914 }
02915 
02916 void TypedefNameDecl::anchor() { }
02917 
02918 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02919   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
02920   return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
02921 }
02922 
02923 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
02924                                      SourceLocation StartLoc,
02925                                      SourceLocation IdLoc, IdentifierInfo *Id,
02926                                      TypeSourceInfo *TInfo) {
02927   return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
02928 }
02929 
02930 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
02931   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
02932   return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
02933 }
02934 
02935 SourceRange TypedefDecl::getSourceRange() const {
02936   SourceLocation RangeEnd = getLocation();
02937   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
02938     if (typeIsPostfix(TInfo->getType()))
02939       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
02940   }
02941   return SourceRange(getLocStart(), RangeEnd);
02942 }
02943 
02944 SourceRange TypeAliasDecl::getSourceRange() const {
02945   SourceLocation RangeEnd = getLocStart();
02946   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
02947     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
02948   return SourceRange(getLocStart(), RangeEnd);
02949 }
02950 
02951 void FileScopeAsmDecl::anchor() { }
02952 
02953 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
02954                                            StringLiteral *Str,
02955                                            SourceLocation AsmLoc,
02956                                            SourceLocation RParenLoc) {
02957   return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
02958 }
02959 
02960 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 
02961                                                        unsigned ID) {
02962   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
02963   return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
02964 }
02965 
02966 //===----------------------------------------------------------------------===//
02967 // ImportDecl Implementation
02968 //===----------------------------------------------------------------------===//
02969 
02970 /// \brief Retrieve the number of module identifiers needed to name the given
02971 /// module.
02972 static unsigned getNumModuleIdentifiers(Module *Mod) {
02973   unsigned Result = 1;
02974   while (Mod->Parent) {
02975     Mod = Mod->Parent;
02976     ++Result;
02977   }
02978   return Result;
02979 }
02980 
02981 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 
02982                        Module *Imported,
02983                        ArrayRef<SourceLocation> IdentifierLocs)
02984   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
02985     NextLocalImport()
02986 {
02987   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
02988   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
02989   memcpy(StoredLocs, IdentifierLocs.data(), 
02990          IdentifierLocs.size() * sizeof(SourceLocation));
02991 }
02992 
02993 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 
02994                        Module *Imported, SourceLocation EndLoc)
02995   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
02996     NextLocalImport()
02997 {
02998   *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
02999 }
03000 
03001 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 
03002                                SourceLocation StartLoc, Module *Imported,
03003                                ArrayRef<SourceLocation> IdentifierLocs) {
03004   void *Mem = C.Allocate(sizeof(ImportDecl) + 
03005                          IdentifierLocs.size() * sizeof(SourceLocation));
03006   return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
03007 }
03008 
03009 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 
03010                                        SourceLocation StartLoc,
03011                                        Module *Imported, 
03012                                        SourceLocation EndLoc) {
03013   void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
03014   ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
03015   Import->setImplicit();
03016   return Import;
03017 }
03018 
03019 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
03020                                            unsigned NumLocations) {
03021   void *Mem = AllocateDeserializedDecl(C, ID, 
03022                                        (sizeof(ImportDecl) + 
03023                                         NumLocations * sizeof(SourceLocation)));
03024   return new (Mem) ImportDecl(EmptyShell());  
03025 }
03026 
03027 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
03028   if (!ImportedAndComplete.getInt())
03029     return ArrayRef<SourceLocation>();
03030 
03031   const SourceLocation *StoredLocs
03032     = reinterpret_cast<const SourceLocation *>(this + 1);
03033   return ArrayRef<SourceLocation>(StoredLocs, 
03034                                   getNumModuleIdentifiers(getImportedModule()));
03035 }
03036 
03037 SourceRange ImportDecl::getSourceRange() const {
03038   if (!ImportedAndComplete.getInt())
03039     return SourceRange(getLocation(), 
03040                        *reinterpret_cast<const SourceLocation *>(this + 1));
03041   
03042   return SourceRange(getLocation(), getIdentifierLocs().back());
03043 }