Home | History | Annotate | Download | only in AST
      1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the Decl subclasses.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/AST/Decl.h"
     15 #include "clang/AST/DeclCXX.h"
     16 #include "clang/AST/DeclObjC.h"
     17 #include "clang/AST/DeclTemplate.h"
     18 #include "clang/AST/ASTContext.h"
     19 #include "clang/AST/TypeLoc.h"
     20 #include "clang/AST/Stmt.h"
     21 #include "clang/AST/Expr.h"
     22 #include "clang/AST/ExprCXX.h"
     23 #include "clang/AST/PrettyPrinter.h"
     24 #include "clang/AST/ASTMutationListener.h"
     25 #include "clang/Basic/Builtins.h"
     26 #include "clang/Basic/IdentifierTable.h"
     27 #include "clang/Basic/Specifiers.h"
     28 #include "clang/Basic/TargetInfo.h"
     29 #include "llvm/Support/ErrorHandling.h"
     30 
     31 #include <algorithm>
     32 
     33 using namespace clang;
     34 
     35 //===----------------------------------------------------------------------===//
     36 // NamedDecl Implementation
     37 //===----------------------------------------------------------------------===//
     38 
     39 static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
     40   // If this declaration has an explicit visibility attribute, use it.
     41   if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
     42     switch (A->getVisibility()) {
     43     case VisibilityAttr::Default:
     44       return DefaultVisibility;
     45     case VisibilityAttr::Hidden:
     46       return HiddenVisibility;
     47     case VisibilityAttr::Protected:
     48       return ProtectedVisibility;
     49     }
     50 
     51     return DefaultVisibility;
     52   }
     53 
     54   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
     55   // implies visibility(default).
     56   if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
     57     for (specific_attr_iterator<AvailabilityAttr>
     58               A = D->specific_attr_begin<AvailabilityAttr>(),
     59            AEnd = D->specific_attr_end<AvailabilityAttr>();
     60          A != AEnd; ++A)
     61       if ((*A)->getPlatform()->getName().equals("macosx"))
     62         return DefaultVisibility;
     63   }
     64 
     65   return llvm::Optional<Visibility>();
     66 }
     67 
     68 typedef NamedDecl::LinkageInfo LinkageInfo;
     69 typedef std::pair<Linkage,Visibility> LVPair;
     70 
     71 static LVPair merge(LVPair L, LVPair R) {
     72   return LVPair(minLinkage(L.first, R.first),
     73                 minVisibility(L.second, R.second));
     74 }
     75 
     76 static LVPair merge(LVPair L, LinkageInfo R) {
     77   return LVPair(minLinkage(L.first, R.linkage()),
     78                 minVisibility(L.second, R.visibility()));
     79 }
     80 
     81 namespace {
     82 /// Flags controlling the computation of linkage and visibility.
     83 struct LVFlags {
     84   bool ConsiderGlobalVisibility;
     85   bool ConsiderVisibilityAttributes;
     86   bool ConsiderTemplateParameterTypes;
     87 
     88   LVFlags() : ConsiderGlobalVisibility(true),
     89               ConsiderVisibilityAttributes(true),
     90               ConsiderTemplateParameterTypes(true) {
     91   }
     92 
     93   /// \brief Returns a set of flags that is only useful for computing the
     94   /// linkage, not the visibility, of a declaration.
     95   static LVFlags CreateOnlyDeclLinkage() {
     96     LVFlags F;
     97     F.ConsiderGlobalVisibility = false;
     98     F.ConsiderVisibilityAttributes = false;
     99     F.ConsiderTemplateParameterTypes = false;
    100     return F;
    101   }
    102 
    103   /// Returns a set of flags, otherwise based on these, which ignores
    104   /// off all sources of visibility except template arguments.
    105   LVFlags onlyTemplateVisibility() const {
    106     LVFlags F = *this;
    107     F.ConsiderGlobalVisibility = false;
    108     F.ConsiderVisibilityAttributes = false;
    109     F.ConsiderTemplateParameterTypes = false;
    110     return F;
    111   }
    112 };
    113 } // end anonymous namespace
    114 
    115 /// \brief Get the most restrictive linkage for the types in the given
    116 /// template parameter list.
    117 static LVPair
    118 getLVForTemplateParameterList(const TemplateParameterList *Params) {
    119   LVPair LV(ExternalLinkage, DefaultVisibility);
    120   for (TemplateParameterList::const_iterator P = Params->begin(),
    121                                           PEnd = Params->end();
    122        P != PEnd; ++P) {
    123     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
    124       if (NTTP->isExpandedParameterPack()) {
    125         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
    126           QualType T = NTTP->getExpansionType(I);
    127           if (!T->isDependentType())
    128             LV = merge(LV, T->getLinkageAndVisibility());
    129         }
    130         continue;
    131       }
    132 
    133       if (!NTTP->getType()->isDependentType()) {
    134         LV = merge(LV, NTTP->getType()->getLinkageAndVisibility());
    135         continue;
    136       }
    137     }
    138 
    139     if (TemplateTemplateParmDecl *TTP
    140                                    = dyn_cast<TemplateTemplateParmDecl>(*P)) {
    141       LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters()));
    142     }
    143   }
    144 
    145   return LV;
    146 }
    147 
    148 /// getLVForDecl - Get the linkage and visibility for the given declaration.
    149 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
    150 
    151 /// \brief Get the most restrictive linkage for the types and
    152 /// declarations in the given template argument list.
    153 static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args,
    154                                            unsigned NumArgs,
    155                                            LVFlags &F) {
    156   LVPair LV(ExternalLinkage, DefaultVisibility);
    157 
    158   for (unsigned I = 0; I != NumArgs; ++I) {
    159     switch (Args[I].getKind()) {
    160     case TemplateArgument::Null:
    161     case TemplateArgument::Integral:
    162     case TemplateArgument::Expression:
    163       break;
    164 
    165     case TemplateArgument::Type:
    166       LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility());
    167       break;
    168 
    169     case TemplateArgument::Declaration:
    170       // The decl can validly be null as the representation of nullptr
    171       // arguments, valid only in C++0x.
    172       if (Decl *D = Args[I].getAsDecl()) {
    173         if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
    174           LV = merge(LV, getLVForDecl(ND, F));
    175       }
    176       break;
    177 
    178     case TemplateArgument::Template:
    179     case TemplateArgument::TemplateExpansion:
    180       if (TemplateDecl *Template
    181                 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
    182         LV = merge(LV, getLVForDecl(Template, F));
    183       break;
    184 
    185     case TemplateArgument::Pack:
    186       LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(),
    187                                                   Args[I].pack_size(),
    188                                                   F));
    189       break;
    190     }
    191   }
    192 
    193   return LV;
    194 }
    195 
    196 static LVPair
    197 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
    198                              LVFlags &F) {
    199   return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
    200 }
    201 
    202 static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
    203                                const FunctionTemplateSpecializationInfo *spec) {
    204   return !(spec->isExplicitSpecialization() &&
    205            fn->hasAttr<VisibilityAttr>());
    206 }
    207 
    208 static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
    209   return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
    210 }
    211 
    212 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
    213   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
    214          "Not a name having namespace scope");
    215   ASTContext &Context = D->getASTContext();
    216 
    217   // C++ [basic.link]p3:
    218   //   A name having namespace scope (3.3.6) has internal linkage if it
    219   //   is the name of
    220   //     - an object, reference, function or function template that is
    221   //       explicitly declared static; or,
    222   // (This bullet corresponds to C99 6.2.2p3.)
    223   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
    224     // Explicitly declared static.
    225     if (Var->getStorageClass() == SC_Static)
    226       return LinkageInfo::internal();
    227 
    228     // - an object or reference that is explicitly declared const
    229     //   and neither explicitly declared extern nor previously
    230     //   declared to have external linkage; or
    231     // (there is no equivalent in C99)
    232     if (Context.getLangOptions().CPlusPlus &&
    233         Var->getType().isConstant(Context) &&
    234         Var->getStorageClass() != SC_Extern &&
    235         Var->getStorageClass() != SC_PrivateExtern) {
    236       bool FoundExtern = false;
    237       for (const VarDecl *PrevVar = Var->getPreviousDeclaration();
    238            PrevVar && !FoundExtern;
    239            PrevVar = PrevVar->getPreviousDeclaration())
    240         if (isExternalLinkage(PrevVar->getLinkage()))
    241           FoundExtern = true;
    242 
    243       if (!FoundExtern)
    244         return LinkageInfo::internal();
    245     }
    246     if (Var->getStorageClass() == SC_None) {
    247       const VarDecl *PrevVar = Var->getPreviousDeclaration();
    248       for (; PrevVar; PrevVar = PrevVar->getPreviousDeclaration())
    249         if (PrevVar->getStorageClass() == SC_PrivateExtern)
    250           break;
    251         if (PrevVar)
    252           return PrevVar->getLinkageAndVisibility();
    253     }
    254   } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
    255     // C++ [temp]p4:
    256     //   A non-member function template can have internal linkage; any
    257     //   other template name shall have external linkage.
    258     const FunctionDecl *Function = 0;
    259     if (const FunctionTemplateDecl *FunTmpl
    260                                         = dyn_cast<FunctionTemplateDecl>(D))
    261       Function = FunTmpl->getTemplatedDecl();
    262     else
    263       Function = cast<FunctionDecl>(D);
    264 
    265     // Explicitly declared static.
    266     if (Function->getStorageClass() == SC_Static)
    267       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
    268   } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
    269     //   - a data member of an anonymous union.
    270     if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
    271       return LinkageInfo::internal();
    272   }
    273 
    274   if (D->isInAnonymousNamespace()) {
    275     const VarDecl *Var = dyn_cast<VarDecl>(D);
    276     const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
    277     if ((!Var || !Var->isExternC()) && (!Func || !Func->isExternC()))
    278       return LinkageInfo::uniqueExternal();
    279   }
    280 
    281   // Set up the defaults.
    282 
    283   // C99 6.2.2p5:
    284   //   If the declaration of an identifier for an object has file
    285   //   scope and no storage-class specifier, its linkage is
    286   //   external.
    287   LinkageInfo LV;
    288 
    289   if (F.ConsiderVisibilityAttributes) {
    290     if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
    291       LV.setVisibility(*Vis, true);
    292       F.ConsiderGlobalVisibility = false;
    293     } else {
    294       // If we're declared in a namespace with a visibility attribute,
    295       // use that namespace's visibility, but don't call it explicit.
    296       for (const DeclContext *DC = D->getDeclContext();
    297            !isa<TranslationUnitDecl>(DC);
    298            DC = DC->getParent()) {
    299         if (!isa<NamespaceDecl>(DC)) continue;
    300         if (llvm::Optional<Visibility> Vis
    301                            = cast<NamespaceDecl>(DC)->getExplicitVisibility()) {
    302           LV.setVisibility(*Vis, false);
    303           F.ConsiderGlobalVisibility = false;
    304           break;
    305         }
    306       }
    307     }
    308   }
    309 
    310   // C++ [basic.link]p4:
    311 
    312   //   A name having namespace scope has external linkage if it is the
    313   //   name of
    314   //
    315   //     - an object or reference, unless it has internal linkage; or
    316   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
    317     // GCC applies the following optimization to variables and static
    318     // data members, but not to functions:
    319     //
    320     // Modify the variable's LV by the LV of its type unless this is
    321     // C or extern "C".  This follows from [basic.link]p9:
    322     //   A type without linkage shall not be used as the type of a
    323     //   variable or function with external linkage unless
    324     //    - the entity has C language linkage, or
    325     //    - the entity is declared within an unnamed namespace, or
    326     //    - the entity is not used or is defined in the same
    327     //      translation unit.
    328     // and [basic.link]p10:
    329     //   ...the types specified by all declarations referring to a
    330     //   given variable or function shall be identical...
    331     // C does not have an equivalent rule.
    332     //
    333     // Ignore this if we've got an explicit attribute;  the user
    334     // probably knows what they're doing.
    335     //
    336     // Note that we don't want to make the variable non-external
    337     // because of this, but unique-external linkage suits us.
    338     if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) {
    339       LVPair TypeLV = Var->getType()->getLinkageAndVisibility();
    340       if (TypeLV.first != ExternalLinkage)
    341         return LinkageInfo::uniqueExternal();
    342       if (!LV.visibilityExplicit())
    343         LV.mergeVisibility(TypeLV.second);
    344     }
    345 
    346     if (Var->getStorageClass() == SC_PrivateExtern)
    347       LV.setVisibility(HiddenVisibility, true);
    348 
    349     if (!Context.getLangOptions().CPlusPlus &&
    350         (Var->getStorageClass() == SC_Extern ||
    351          Var->getStorageClass() == SC_PrivateExtern)) {
    352 
    353       // C99 6.2.2p4:
    354       //   For an identifier declared with the storage-class specifier
    355       //   extern in a scope in which a prior declaration of that
    356       //   identifier is visible, if the prior declaration specifies
    357       //   internal or external linkage, the linkage of the identifier
    358       //   at the later declaration is the same as the linkage
    359       //   specified at the prior declaration. If no prior declaration
    360       //   is visible, or if the prior declaration specifies no
    361       //   linkage, then the identifier has external linkage.
    362       if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) {
    363         LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
    364         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
    365         LV.mergeVisibility(PrevLV);
    366       }
    367     }
    368 
    369   //     - a function, unless it has internal linkage; or
    370   } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
    371     // In theory, we can modify the function's LV by the LV of its
    372     // type unless it has C linkage (see comment above about variables
    373     // for justification).  In practice, GCC doesn't do this, so it's
    374     // just too painful to make work.
    375 
    376     if (Function->getStorageClass() == SC_PrivateExtern)
    377       LV.setVisibility(HiddenVisibility, true);
    378 
    379     // C99 6.2.2p5:
    380     //   If the declaration of an identifier for a function has no
    381     //   storage-class specifier, its linkage is determined exactly
    382     //   as if it were declared with the storage-class specifier
    383     //   extern.
    384     if (!Context.getLangOptions().CPlusPlus &&
    385         (Function->getStorageClass() == SC_Extern ||
    386          Function->getStorageClass() == SC_PrivateExtern ||
    387          Function->getStorageClass() == SC_None)) {
    388       // C99 6.2.2p4:
    389       //   For an identifier declared with the storage-class specifier
    390       //   extern in a scope in which a prior declaration of that
    391       //   identifier is visible, if the prior declaration specifies
    392       //   internal or external linkage, the linkage of the identifier
    393       //   at the later declaration is the same as the linkage
    394       //   specified at the prior declaration. If no prior declaration
    395       //   is visible, or if the prior declaration specifies no
    396       //   linkage, then the identifier has external linkage.
    397       if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) {
    398         LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
    399         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
    400         LV.mergeVisibility(PrevLV);
    401       }
    402     }
    403 
    404     // In C++, then if the type of the function uses a type with
    405     // unique-external linkage, it's not legally usable from outside
    406     // this translation unit.  However, we should use the C linkage
    407     // rules instead for extern "C" declarations.
    408     if (Context.getLangOptions().CPlusPlus && !Function->isExternC() &&
    409         Function->getType()->getLinkage() == UniqueExternalLinkage)
    410       return LinkageInfo::uniqueExternal();
    411 
    412     // Consider LV from the template and the template arguments unless
    413     // this is an explicit specialization with a visibility attribute.
    414     if (FunctionTemplateSpecializationInfo *specInfo
    415                                = Function->getTemplateSpecializationInfo()) {
    416       if (shouldConsiderTemplateLV(Function, specInfo)) {
    417         LV.merge(getLVForDecl(specInfo->getTemplate(),
    418                               F.onlyTemplateVisibility()));
    419         const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
    420         LV.merge(getLVForTemplateArgumentList(templateArgs, F));
    421       }
    422     }
    423 
    424   //     - a named class (Clause 9), or an unnamed class defined in a
    425   //       typedef declaration in which the class has the typedef name
    426   //       for linkage purposes (7.1.3); or
    427   //     - a named enumeration (7.2), or an unnamed enumeration
    428   //       defined in a typedef declaration in which the enumeration
    429   //       has the typedef name for linkage purposes (7.1.3); or
    430   } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
    431     // Unnamed tags have no linkage.
    432     if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
    433       return LinkageInfo::none();
    434 
    435     // If this is a class template specialization, consider the
    436     // linkage of the template and template arguments.
    437     if (const ClassTemplateSpecializationDecl *spec
    438           = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
    439       if (shouldConsiderTemplateLV(spec)) {
    440         // From the template.
    441         LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
    442                               F.onlyTemplateVisibility()));
    443 
    444         // The arguments at which the template was instantiated.
    445         const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
    446         LV.merge(getLVForTemplateArgumentList(TemplateArgs, F));
    447       }
    448     }
    449 
    450     // Consider -fvisibility unless the type has C linkage.
    451     if (F.ConsiderGlobalVisibility)
    452       F.ConsiderGlobalVisibility =
    453         (Context.getLangOptions().CPlusPlus &&
    454          !Tag->getDeclContext()->isExternCContext());
    455 
    456   //     - an enumerator belonging to an enumeration with external linkage;
    457   } else if (isa<EnumConstantDecl>(D)) {
    458     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
    459     if (!isExternalLinkage(EnumLV.linkage()))
    460       return LinkageInfo::none();
    461     LV.merge(EnumLV);
    462 
    463   //     - a template, unless it is a function template that has
    464   //       internal linkage (Clause 14);
    465   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
    466     if (F.ConsiderTemplateParameterTypes)
    467       LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
    468 
    469   //     - a namespace (7.3), unless it is declared within an unnamed
    470   //       namespace.
    471   } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
    472     return LV;
    473 
    474   // By extension, we assign external linkage to Objective-C
    475   // interfaces.
    476   } else if (isa<ObjCInterfaceDecl>(D)) {
    477     // fallout
    478 
    479   // Everything not covered here has no linkage.
    480   } else {
    481     return LinkageInfo::none();
    482   }
    483 
    484   // If we ended up with non-external linkage, visibility should
    485   // always be default.
    486   if (LV.linkage() != ExternalLinkage)
    487     return LinkageInfo(LV.linkage(), DefaultVisibility, false);
    488 
    489   // If we didn't end up with hidden visibility, consider attributes
    490   // and -fvisibility.
    491   if (F.ConsiderGlobalVisibility)
    492     LV.mergeVisibility(Context.getLangOptions().getVisibilityMode());
    493 
    494   return LV;
    495 }
    496 
    497 static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
    498   // Only certain class members have linkage.  Note that fields don't
    499   // really have linkage, but it's convenient to say they do for the
    500   // purposes of calculating linkage of pointer-to-data-member
    501   // template arguments.
    502   if (!(isa<CXXMethodDecl>(D) ||
    503         isa<VarDecl>(D) ||
    504         isa<FieldDecl>(D) ||
    505         (isa<TagDecl>(D) &&
    506          (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
    507     return LinkageInfo::none();
    508 
    509   LinkageInfo LV;
    510 
    511   // The flags we're going to use to compute the class's visibility.
    512   LVFlags ClassF = F;
    513 
    514   // If we have an explicit visibility attribute, merge that in.
    515   if (F.ConsiderVisibilityAttributes) {
    516     if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
    517       LV.mergeVisibility(*Vis, true);
    518 
    519       // Ignore global visibility later, but not this attribute.
    520       F.ConsiderGlobalVisibility = false;
    521 
    522       // Ignore both global visibility and attributes when computing our
    523       // parent's visibility.
    524       ClassF = F.onlyTemplateVisibility();
    525     }
    526   }
    527 
    528   // Class members only have linkage if their class has external
    529   // linkage.
    530   LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
    531   if (!isExternalLinkage(LV.linkage()))
    532     return LinkageInfo::none();
    533 
    534   // If the class already has unique-external linkage, we can't improve.
    535   if (LV.linkage() == UniqueExternalLinkage)
    536     return LinkageInfo::uniqueExternal();
    537 
    538   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
    539     // If the type of the function uses a type with unique-external
    540     // linkage, it's not legally usable from outside this translation unit.
    541     if (MD->getType()->getLinkage() == UniqueExternalLinkage)
    542       return LinkageInfo::uniqueExternal();
    543 
    544     TemplateSpecializationKind TSK = TSK_Undeclared;
    545 
    546     // If this is a method template specialization, use the linkage for
    547     // the template parameters and arguments.
    548     if (FunctionTemplateSpecializationInfo *spec
    549            = MD->getTemplateSpecializationInfo()) {
    550       if (shouldConsiderTemplateLV(MD, spec)) {
    551         LV.merge(getLVForTemplateArgumentList(*spec->TemplateArguments, F));
    552         if (F.ConsiderTemplateParameterTypes)
    553           LV.merge(getLVForTemplateParameterList(
    554                               spec->getTemplate()->getTemplateParameters()));
    555       }
    556 
    557       TSK = spec->getTemplateSpecializationKind();
    558     } else if (MemberSpecializationInfo *MSI =
    559                  MD->getMemberSpecializationInfo()) {
    560       TSK = MSI->getTemplateSpecializationKind();
    561     }
    562 
    563     // If we're paying attention to global visibility, apply
    564     // -finline-visibility-hidden if this is an inline method.
    565     //
    566     // Note that ConsiderGlobalVisibility doesn't yet have information
    567     // about whether containing classes have visibility attributes,
    568     // and that's intentional.
    569     if (TSK != TSK_ExplicitInstantiationDeclaration &&
    570         F.ConsiderGlobalVisibility &&
    571         MD->getASTContext().getLangOptions().InlineVisibilityHidden) {
    572       // InlineVisibilityHidden only applies to definitions, and
    573       // isInlined() only gives meaningful answers on definitions
    574       // anyway.
    575       const FunctionDecl *Def = 0;
    576       if (MD->hasBody(Def) && Def->isInlined())
    577         LV.setVisibility(HiddenVisibility);
    578     }
    579 
    580     // Note that in contrast to basically every other situation, we
    581     // *do* apply -fvisibility to method declarations.
    582 
    583   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
    584     if (const ClassTemplateSpecializationDecl *spec
    585         = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
    586       if (shouldConsiderTemplateLV(spec)) {
    587         // Merge template argument/parameter information for member
    588         // class template specializations.
    589         LV.merge(getLVForTemplateArgumentList(spec->getTemplateArgs(), F));
    590       if (F.ConsiderTemplateParameterTypes)
    591         LV.merge(getLVForTemplateParameterList(
    592                     spec->getSpecializedTemplate()->getTemplateParameters()));
    593       }
    594     }
    595 
    596   // Static data members.
    597   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
    598     // Modify the variable's linkage by its type, but ignore the
    599     // type's visibility unless it's a definition.
    600     LVPair TypeLV = VD->getType()->getLinkageAndVisibility();
    601     if (TypeLV.first != ExternalLinkage)
    602       LV.mergeLinkage(UniqueExternalLinkage);
    603     if (!LV.visibilityExplicit())
    604       LV.mergeVisibility(TypeLV.second);
    605   }
    606 
    607   F.ConsiderGlobalVisibility &= !LV.visibilityExplicit();
    608 
    609   // Apply -fvisibility if desired.
    610   if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) {
    611     LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode());
    612   }
    613 
    614   return LV;
    615 }
    616 
    617 static void clearLinkageForClass(const CXXRecordDecl *record) {
    618   for (CXXRecordDecl::decl_iterator
    619          i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
    620     Decl *child = *i;
    621     if (isa<NamedDecl>(child))
    622       cast<NamedDecl>(child)->ClearLinkageCache();
    623   }
    624 }
    625 
    626 void NamedDecl::ClearLinkageCache() {
    627   // Note that we can't skip clearing the linkage of children just
    628   // because the parent doesn't have cached linkage:  we don't cache
    629   // when computing linkage for parent contexts.
    630 
    631   HasCachedLinkage = 0;
    632 
    633   // If we're changing the linkage of a class, we need to reset the
    634   // linkage of child declarations, too.
    635   if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
    636     clearLinkageForClass(record);
    637 
    638   if (ClassTemplateDecl *temp =
    639         dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
    640     // Clear linkage for the template pattern.
    641     CXXRecordDecl *record = temp->getTemplatedDecl();
    642     record->HasCachedLinkage = 0;
    643     clearLinkageForClass(record);
    644 
    645     // We need to clear linkage for specializations, too.
    646     for (ClassTemplateDecl::spec_iterator
    647            i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
    648       i->ClearLinkageCache();
    649   }
    650 
    651   // Clear cached linkage for function template decls, too.
    652   if (FunctionTemplateDecl *temp =
    653         dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
    654     temp->getTemplatedDecl()->ClearLinkageCache();
    655     for (FunctionTemplateDecl::spec_iterator
    656            i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
    657       i->ClearLinkageCache();
    658   }
    659 
    660 }
    661 
    662 Linkage NamedDecl::getLinkage() const {
    663   if (HasCachedLinkage) {
    664     assert(Linkage(CachedLinkage) ==
    665              getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
    666     return Linkage(CachedLinkage);
    667   }
    668 
    669   CachedLinkage = getLVForDecl(this,
    670                                LVFlags::CreateOnlyDeclLinkage()).linkage();
    671   HasCachedLinkage = 1;
    672   return Linkage(CachedLinkage);
    673 }
    674 
    675 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
    676   LinkageInfo LI = getLVForDecl(this, LVFlags());
    677   assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
    678   HasCachedLinkage = 1;
    679   CachedLinkage = LI.linkage();
    680   return LI;
    681 }
    682 
    683 llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
    684   // Use the most recent declaration of a variable.
    685   if (const VarDecl *var = dyn_cast<VarDecl>(this))
    686     return getVisibilityOf(var->getMostRecentDeclaration());
    687 
    688   // Use the most recent declaration of a function, and also handle
    689   // function template specializations.
    690   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
    691     if (llvm::Optional<Visibility> V
    692                             = getVisibilityOf(fn->getMostRecentDeclaration()))
    693       return V;
    694 
    695     // If the function is a specialization of a template with an
    696     // explicit visibility attribute, use that.
    697     if (FunctionTemplateSpecializationInfo *templateInfo
    698           = fn->getTemplateSpecializationInfo())
    699       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
    700 
    701     return llvm::Optional<Visibility>();
    702   }
    703 
    704   // Otherwise, just check the declaration itself first.
    705   if (llvm::Optional<Visibility> V = getVisibilityOf(this))
    706     return V;
    707 
    708   // If there wasn't explicit visibility there, and this is a
    709   // specialization of a class template, check for visibility
    710   // on the pattern.
    711   if (const ClassTemplateSpecializationDecl *spec
    712         = dyn_cast<ClassTemplateSpecializationDecl>(this))
    713     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
    714 
    715   return llvm::Optional<Visibility>();
    716 }
    717 
    718 static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
    719   // Objective-C: treat all Objective-C declarations as having external
    720   // linkage.
    721   switch (D->getKind()) {
    722     default:
    723       break;
    724     case Decl::TemplateTemplateParm: // count these as external
    725     case Decl::NonTypeTemplateParm:
    726     case Decl::ObjCAtDefsField:
    727     case Decl::ObjCCategory:
    728     case Decl::ObjCCategoryImpl:
    729     case Decl::ObjCCompatibleAlias:
    730     case Decl::ObjCForwardProtocol:
    731     case Decl::ObjCImplementation:
    732     case Decl::ObjCMethod:
    733     case Decl::ObjCProperty:
    734     case Decl::ObjCPropertyImpl:
    735     case Decl::ObjCProtocol:
    736       return LinkageInfo::external();
    737   }
    738 
    739   // Handle linkage for namespace-scope names.
    740   if (D->getDeclContext()->getRedeclContext()->isFileContext())
    741     return getLVForNamespaceScopeDecl(D, Flags);
    742 
    743   // C++ [basic.link]p5:
    744   //   In addition, a member function, static data member, a named
    745   //   class or enumeration of class scope, or an unnamed class or
    746   //   enumeration defined in a class-scope typedef declaration such
    747   //   that the class or enumeration has the typedef name for linkage
    748   //   purposes (7.1.3), has external linkage if the name of the class
    749   //   has external linkage.
    750   if (D->getDeclContext()->isRecord())
    751     return getLVForClassMember(D, Flags);
    752 
    753   // C++ [basic.link]p6:
    754   //   The name of a function declared in block scope and the name of
    755   //   an object declared by a block scope extern declaration have
    756   //   linkage. If there is a visible declaration of an entity with
    757   //   linkage having the same name and type, ignoring entities
    758   //   declared outside the innermost enclosing namespace scope, the
    759   //   block scope declaration declares that same entity and receives
    760   //   the linkage of the previous declaration. If there is more than
    761   //   one such matching entity, the program is ill-formed. Otherwise,
    762   //   if no matching entity is found, the block scope entity receives
    763   //   external linkage.
    764   if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
    765     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
    766       if (Function->isInAnonymousNamespace() && !Function->isExternC())
    767         return LinkageInfo::uniqueExternal();
    768 
    769       LinkageInfo LV;
    770       if (Flags.ConsiderVisibilityAttributes) {
    771         if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
    772           LV.setVisibility(*Vis);
    773       }
    774 
    775       if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) {
    776         LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
    777         if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
    778         LV.mergeVisibility(PrevLV);
    779       }
    780 
    781       return LV;
    782     }
    783 
    784     if (const VarDecl *Var = dyn_cast<VarDecl>(D))
    785       if (Var->getStorageClass() == SC_Extern ||
    786           Var->getStorageClass() == SC_PrivateExtern) {
    787         if (Var->isInAnonymousNamespace() && !Var->isExternC())
    788           return LinkageInfo::uniqueExternal();
    789 
    790         LinkageInfo LV;
    791         if (Var->getStorageClass() == SC_PrivateExtern)
    792           LV.setVisibility(HiddenVisibility);
    793         else if (Flags.ConsiderVisibilityAttributes) {
    794           if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
    795             LV.setVisibility(*Vis);
    796         }
    797 
    798         if (const VarDecl *Prev = Var->getPreviousDeclaration()) {
    799           LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
    800           if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
    801           LV.mergeVisibility(PrevLV);
    802         }
    803 
    804         return LV;
    805       }
    806   }
    807 
    808   // C++ [basic.link]p6:
    809   //   Names not covered by these rules have no linkage.
    810   return LinkageInfo::none();
    811 }
    812 
    813 std::string NamedDecl::getQualifiedNameAsString() const {
    814   return getQualifiedNameAsString(getASTContext().getLangOptions());
    815 }
    816 
    817 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
    818   const DeclContext *Ctx = getDeclContext();
    819 
    820   if (Ctx->isFunctionOrMethod())
    821     return getNameAsString();
    822 
    823   typedef SmallVector<const DeclContext *, 8> ContextsTy;
    824   ContextsTy Contexts;
    825 
    826   // Collect contexts.
    827   while (Ctx && isa<NamedDecl>(Ctx)) {
    828     Contexts.push_back(Ctx);
    829     Ctx = Ctx->getParent();
    830   };
    831 
    832   std::string QualName;
    833   llvm::raw_string_ostream OS(QualName);
    834 
    835   for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
    836        I != E; ++I) {
    837     if (const ClassTemplateSpecializationDecl *Spec
    838           = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
    839       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
    840       std::string TemplateArgsStr
    841         = TemplateSpecializationType::PrintTemplateArgumentList(
    842                                            TemplateArgs.data(),
    843                                            TemplateArgs.size(),
    844                                            P);
    845       OS << Spec->getName() << TemplateArgsStr;
    846     } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
    847       if (ND->isAnonymousNamespace())
    848         OS << "<anonymous namespace>";
    849       else
    850         OS << *ND;
    851     } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
    852       if (!RD->getIdentifier())
    853         OS << "<anonymous " << RD->getKindName() << '>';
    854       else
    855         OS << *RD;
    856     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
    857       const FunctionProtoType *FT = 0;
    858       if (FD->hasWrittenPrototype())
    859         FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
    860 
    861       OS << *FD << '(';
    862       if (FT) {
    863         unsigned NumParams = FD->getNumParams();
    864         for (unsigned i = 0; i < NumParams; ++i) {
    865           if (i)
    866             OS << ", ";
    867           std::string Param;
    868           FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
    869           OS << Param;
    870         }
    871 
    872         if (FT->isVariadic()) {
    873           if (NumParams > 0)
    874             OS << ", ";
    875           OS << "...";
    876         }
    877       }
    878       OS << ')';
    879     } else {
    880       OS << *cast<NamedDecl>(*I);
    881     }
    882     OS << "::";
    883   }
    884 
    885   if (getDeclName())
    886     OS << *this;
    887   else
    888     OS << "<anonymous>";
    889 
    890   return OS.str();
    891 }
    892 
    893 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
    894   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
    895 
    896   // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
    897   // We want to keep it, unless it nominates same namespace.
    898   if (getKind() == Decl::UsingDirective) {
    899     return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
    900              ->getOriginalNamespace() ==
    901            cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
    902              ->getOriginalNamespace();
    903   }
    904 
    905   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
    906     // For function declarations, we keep track of redeclarations.
    907     return FD->getPreviousDeclaration() == OldD;
    908 
    909   // For function templates, the underlying function declarations are linked.
    910   if (const FunctionTemplateDecl *FunctionTemplate
    911         = dyn_cast<FunctionTemplateDecl>(this))
    912     if (const FunctionTemplateDecl *OldFunctionTemplate
    913           = dyn_cast<FunctionTemplateDecl>(OldD))
    914       return FunctionTemplate->getTemplatedDecl()
    915                ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
    916 
    917   // For method declarations, we keep track of redeclarations.
    918   if (isa<ObjCMethodDecl>(this))
    919     return false;
    920 
    921   if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
    922     return true;
    923 
    924   if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
    925     return cast<UsingShadowDecl>(this)->getTargetDecl() ==
    926            cast<UsingShadowDecl>(OldD)->getTargetDecl();
    927 
    928   if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
    929     ASTContext &Context = getASTContext();
    930     return Context.getCanonicalNestedNameSpecifier(
    931                                      cast<UsingDecl>(this)->getQualifier()) ==
    932            Context.getCanonicalNestedNameSpecifier(
    933                                         cast<UsingDecl>(OldD)->getQualifier());
    934   }
    935 
    936   // For non-function declarations, if the declarations are of the
    937   // same kind then this must be a redeclaration, or semantic analysis
    938   // would not have given us the new declaration.
    939   return this->getKind() == OldD->getKind();
    940 }
    941 
    942 bool NamedDecl::hasLinkage() const {
    943   return getLinkage() != NoLinkage;
    944 }
    945 
    946 NamedDecl *NamedDecl::getUnderlyingDecl() {
    947   NamedDecl *ND = this;
    948   while (true) {
    949     if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
    950       ND = UD->getTargetDecl();
    951     else if (ObjCCompatibleAliasDecl *AD
    952               = dyn_cast<ObjCCompatibleAliasDecl>(ND))
    953       return AD->getClassInterface();
    954     else
    955       return ND;
    956   }
    957 }
    958 
    959 bool NamedDecl::isCXXInstanceMember() const {
    960   assert(isCXXClassMember() &&
    961          "checking whether non-member is instance member");
    962 
    963   const NamedDecl *D = this;
    964   if (isa<UsingShadowDecl>(D))
    965     D = cast<UsingShadowDecl>(D)->getTargetDecl();
    966 
    967   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
    968     return true;
    969   if (isa<CXXMethodDecl>(D))
    970     return cast<CXXMethodDecl>(D)->isInstance();
    971   if (isa<FunctionTemplateDecl>(D))
    972     return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
    973                                  ->getTemplatedDecl())->isInstance();
    974   return false;
    975 }
    976 
    977 //===----------------------------------------------------------------------===//
    978 // DeclaratorDecl Implementation
    979 //===----------------------------------------------------------------------===//
    980 
    981 template <typename DeclT>
    982 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
    983   if (decl->getNumTemplateParameterLists() > 0)
    984     return decl->getTemplateParameterList(0)->getTemplateLoc();
    985   else
    986     return decl->getInnerLocStart();
    987 }
    988 
    989 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
    990   TypeSourceInfo *TSI = getTypeSourceInfo();
    991   if (TSI) return TSI->getTypeLoc().getBeginLoc();
    992   return SourceLocation();
    993 }
    994 
    995 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
    996   if (QualifierLoc) {
    997     // Make sure the extended decl info is allocated.
    998     if (!hasExtInfo()) {
    999       // Save (non-extended) type source info pointer.
   1000       TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
   1001       // Allocate external info struct.
   1002       DeclInfo = new (getASTContext()) ExtInfo;
   1003       // Restore savedTInfo into (extended) decl info.
   1004       getExtInfo()->TInfo = savedTInfo;
   1005     }
   1006     // Set qualifier info.
   1007     getExtInfo()->QualifierLoc = QualifierLoc;
   1008   } else {
   1009     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
   1010     if (hasExtInfo()) {
   1011       if (getExtInfo()->NumTemplParamLists == 0) {
   1012         // Save type source info pointer.
   1013         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
   1014         // Deallocate the extended decl info.
   1015         getASTContext().Deallocate(getExtInfo());
   1016         // Restore savedTInfo into (non-extended) decl info.
   1017         DeclInfo = savedTInfo;
   1018       }
   1019       else
   1020         getExtInfo()->QualifierLoc = QualifierLoc;
   1021     }
   1022   }
   1023 }
   1024 
   1025 void
   1026 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
   1027                                               unsigned NumTPLists,
   1028                                               TemplateParameterList **TPLists) {
   1029   assert(NumTPLists > 0);
   1030   // Make sure the extended decl info is allocated.
   1031   if (!hasExtInfo()) {
   1032     // Save (non-extended) type source info pointer.
   1033     TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
   1034     // Allocate external info struct.
   1035     DeclInfo = new (getASTContext()) ExtInfo;
   1036     // Restore savedTInfo into (extended) decl info.
   1037     getExtInfo()->TInfo = savedTInfo;
   1038   }
   1039   // Set the template parameter lists info.
   1040   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
   1041 }
   1042 
   1043 SourceLocation DeclaratorDecl::getOuterLocStart() const {
   1044   return getTemplateOrInnerLocStart(this);
   1045 }
   1046 
   1047 namespace {
   1048 
   1049 // Helper function: returns true if QT is or contains a type
   1050 // having a postfix component.
   1051 bool typeIsPostfix(clang::QualType QT) {
   1052   while (true) {
   1053     const Type* T = QT.getTypePtr();
   1054     switch (T->getTypeClass()) {
   1055     default:
   1056       return false;
   1057     case Type::Pointer:
   1058       QT = cast<PointerType>(T)->getPointeeType();
   1059       break;
   1060     case Type::BlockPointer:
   1061       QT = cast<BlockPointerType>(T)->getPointeeType();
   1062       break;
   1063     case Type::MemberPointer:
   1064       QT = cast<MemberPointerType>(T)->getPointeeType();
   1065       break;
   1066     case Type::LValueReference:
   1067     case Type::RValueReference:
   1068       QT = cast<ReferenceType>(T)->getPointeeType();
   1069       break;
   1070     case Type::PackExpansion:
   1071       QT = cast<PackExpansionType>(T)->getPattern();
   1072       break;
   1073     case Type::Paren:
   1074     case Type::ConstantArray:
   1075     case Type::DependentSizedArray:
   1076     case Type::IncompleteArray:
   1077     case Type::VariableArray:
   1078     case Type::FunctionProto:
   1079     case Type::FunctionNoProto:
   1080       return true;
   1081     }
   1082   }
   1083 }
   1084 
   1085 } // namespace
   1086 
   1087 SourceRange DeclaratorDecl::getSourceRange() const {
   1088   SourceLocation RangeEnd = getLocation();
   1089   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
   1090     if (typeIsPostfix(TInfo->getType()))
   1091       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
   1092   }
   1093   return SourceRange(getOuterLocStart(), RangeEnd);
   1094 }
   1095 
   1096 void
   1097 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
   1098                                              unsigned NumTPLists,
   1099                                              TemplateParameterList **TPLists) {
   1100   assert((NumTPLists == 0 || TPLists != 0) &&
   1101          "Empty array of template parameters with positive size!");
   1102 
   1103   // Free previous template parameters (if any).
   1104   if (NumTemplParamLists > 0) {
   1105     Context.Deallocate(TemplParamLists);
   1106     TemplParamLists = 0;
   1107     NumTemplParamLists = 0;
   1108   }
   1109   // Set info on matched template parameter lists (if any).
   1110   if (NumTPLists > 0) {
   1111     TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
   1112     NumTemplParamLists = NumTPLists;
   1113     for (unsigned i = NumTPLists; i-- > 0; )
   1114       TemplParamLists[i] = TPLists[i];
   1115   }
   1116 }
   1117 
   1118 //===----------------------------------------------------------------------===//
   1119 // VarDecl Implementation
   1120 //===----------------------------------------------------------------------===//
   1121 
   1122 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
   1123   switch (SC) {
   1124   case SC_None:                 break;
   1125   case SC_Auto:                 return "auto";
   1126   case SC_Extern:               return "extern";
   1127   case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
   1128   case SC_PrivateExtern:        return "__private_extern__";
   1129   case SC_Register:             return "register";
   1130   case SC_Static:               return "static";
   1131   }
   1132 
   1133   llvm_unreachable("Invalid storage class");
   1134   return 0;
   1135 }
   1136 
   1137 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
   1138                          SourceLocation StartL, SourceLocation IdL,
   1139                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
   1140                          StorageClass S, StorageClass SCAsWritten) {
   1141   return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
   1142 }
   1143 
   1144 void VarDecl::setStorageClass(StorageClass SC) {
   1145   assert(isLegalForVariable(SC));
   1146   if (getStorageClass() != SC)
   1147     ClearLinkageCache();
   1148 
   1149   VarDeclBits.SClass = SC;
   1150 }
   1151 
   1152 SourceRange VarDecl::getSourceRange() const {
   1153   if (getInit())
   1154     return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
   1155   return DeclaratorDecl::getSourceRange();
   1156 }
   1157 
   1158 bool VarDecl::isExternC() const {
   1159   ASTContext &Context = getASTContext();
   1160   if (!Context.getLangOptions().CPlusPlus)
   1161     return (getDeclContext()->isTranslationUnit() &&
   1162             getStorageClass() != SC_Static) ||
   1163       (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
   1164 
   1165   const DeclContext *DC = getDeclContext();
   1166   if (DC->isFunctionOrMethod())
   1167     return false;
   1168 
   1169   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
   1170     if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))  {
   1171       if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
   1172         return getStorageClass() != SC_Static;
   1173 
   1174       break;
   1175     }
   1176 
   1177   }
   1178 
   1179   return false;
   1180 }
   1181 
   1182 VarDecl *VarDecl::getCanonicalDecl() {
   1183   return getFirstDeclaration();
   1184 }
   1185 
   1186 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const {
   1187   // C++ [basic.def]p2:
   1188   //   A declaration is a definition unless [...] it contains the 'extern'
   1189   //   specifier or a linkage-specification and neither an initializer [...],
   1190   //   it declares a static data member in a class declaration [...].
   1191   // C++ [temp.expl.spec]p15:
   1192   //   An explicit specialization of a static data member of a template is a
   1193   //   definition if the declaration includes an initializer; otherwise, it is
   1194   //   a declaration.
   1195   if (isStaticDataMember()) {
   1196     if (isOutOfLine() && (hasInit() ||
   1197           getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
   1198       return Definition;
   1199     else
   1200       return DeclarationOnly;
   1201   }
   1202   // C99 6.7p5:
   1203   //   A definition of an identifier is a declaration for that identifier that
   1204   //   [...] causes storage to be reserved for that object.
   1205   // Note: that applies for all non-file-scope objects.
   1206   // C99 6.9.2p1:
   1207   //   If the declaration of an identifier for an object has file scope and an
   1208   //   initializer, the declaration is an external definition for the identifier
   1209   if (hasInit())
   1210     return Definition;
   1211   // AST for 'extern "C" int foo;' is annotated with 'extern'.
   1212   if (hasExternalStorage())
   1213     return DeclarationOnly;
   1214 
   1215   if (getStorageClassAsWritten() == SC_Extern ||
   1216        getStorageClassAsWritten() == SC_PrivateExtern) {
   1217     for (const VarDecl *PrevVar = getPreviousDeclaration();
   1218          PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) {
   1219       if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
   1220         return DeclarationOnly;
   1221     }
   1222   }
   1223   // C99 6.9.2p2:
   1224   //   A declaration of an object that has file scope without an initializer,
   1225   //   and without a storage class specifier or the scs 'static', constitutes
   1226   //   a tentative definition.
   1227   // No such thing in C++.
   1228   if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl())
   1229     return TentativeDefinition;
   1230 
   1231   // What's left is (in C, block-scope) declarations without initializers or
   1232   // external storage. These are definitions.
   1233   return Definition;
   1234 }
   1235 
   1236 VarDecl *VarDecl::getActingDefinition() {
   1237   DefinitionKind Kind = isThisDeclarationADefinition();
   1238   if (Kind != TentativeDefinition)
   1239     return 0;
   1240 
   1241   VarDecl *LastTentative = 0;
   1242   VarDecl *First = getFirstDeclaration();
   1243   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
   1244        I != E; ++I) {
   1245     Kind = (*I)->isThisDeclarationADefinition();
   1246     if (Kind == Definition)
   1247       return 0;
   1248     else if (Kind == TentativeDefinition)
   1249       LastTentative = *I;
   1250   }
   1251   return LastTentative;
   1252 }
   1253 
   1254 bool VarDecl::isTentativeDefinitionNow() const {
   1255   DefinitionKind Kind = isThisDeclarationADefinition();
   1256   if (Kind != TentativeDefinition)
   1257     return false;
   1258 
   1259   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
   1260     if ((*I)->isThisDeclarationADefinition() == Definition)
   1261       return false;
   1262   }
   1263   return true;
   1264 }
   1265 
   1266 VarDecl *VarDecl::getDefinition() {
   1267   VarDecl *First = getFirstDeclaration();
   1268   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
   1269        I != E; ++I) {
   1270     if ((*I)->isThisDeclarationADefinition() == Definition)
   1271       return *I;
   1272   }
   1273   return 0;
   1274 }
   1275 
   1276 VarDecl::DefinitionKind VarDecl::hasDefinition() const {
   1277   DefinitionKind Kind = DeclarationOnly;
   1278 
   1279   const VarDecl *First = getFirstDeclaration();
   1280   for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
   1281        I != E; ++I)
   1282     Kind = std::max(Kind, (*I)->isThisDeclarationADefinition());
   1283 
   1284   return Kind;
   1285 }
   1286 
   1287 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
   1288   redecl_iterator I = redecls_begin(), E = redecls_end();
   1289   while (I != E && !I->getInit())
   1290     ++I;
   1291 
   1292   if (I != E) {
   1293     D = *I;
   1294     return I->getInit();
   1295   }
   1296   return 0;
   1297 }
   1298 
   1299 bool VarDecl::isOutOfLine() const {
   1300   if (Decl::isOutOfLine())
   1301     return true;
   1302 
   1303   if (!isStaticDataMember())
   1304     return false;
   1305 
   1306   // If this static data member was instantiated from a static data member of
   1307   // a class template, check whether that static data member was defined
   1308   // out-of-line.
   1309   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
   1310     return VD->isOutOfLine();
   1311 
   1312   return false;
   1313 }
   1314 
   1315 VarDecl *VarDecl::getOutOfLineDefinition() {
   1316   if (!isStaticDataMember())
   1317     return 0;
   1318 
   1319   for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
   1320        RD != RDEnd; ++RD) {
   1321     if (RD->getLexicalDeclContext()->isFileContext())
   1322       return *RD;
   1323   }
   1324 
   1325   return 0;
   1326 }
   1327 
   1328 void VarDecl::setInit(Expr *I) {
   1329   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
   1330     Eval->~EvaluatedStmt();
   1331     getASTContext().Deallocate(Eval);
   1332   }
   1333 
   1334   Init = I;
   1335 }
   1336 
   1337 bool VarDecl::extendsLifetimeOfTemporary() const {
   1338   assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
   1339 
   1340   const Expr *E = getInit();
   1341   if (!E)
   1342     return false;
   1343 
   1344   if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
   1345     E = Cleanups->getSubExpr();
   1346 
   1347   return isa<MaterializeTemporaryExpr>(E);
   1348 }
   1349 
   1350 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
   1351   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
   1352     return cast<VarDecl>(MSI->getInstantiatedFrom());
   1353 
   1354   return 0;
   1355 }
   1356 
   1357 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
   1358   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
   1359     return MSI->getTemplateSpecializationKind();
   1360 
   1361   return TSK_Undeclared;
   1362 }
   1363 
   1364 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
   1365   return getASTContext().getInstantiatedFromStaticDataMember(this);
   1366 }
   1367 
   1368 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
   1369                                          SourceLocation PointOfInstantiation) {
   1370   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
   1371   assert(MSI && "Not an instantiated static data member?");
   1372   MSI->setTemplateSpecializationKind(TSK);
   1373   if (TSK != TSK_ExplicitSpecialization &&
   1374       PointOfInstantiation.isValid() &&
   1375       MSI->getPointOfInstantiation().isInvalid())
   1376     MSI->setPointOfInstantiation(PointOfInstantiation);
   1377 }
   1378 
   1379 //===----------------------------------------------------------------------===//
   1380 // ParmVarDecl Implementation
   1381 //===----------------------------------------------------------------------===//
   1382 
   1383 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
   1384                                  SourceLocation StartLoc,
   1385                                  SourceLocation IdLoc, IdentifierInfo *Id,
   1386                                  QualType T, TypeSourceInfo *TInfo,
   1387                                  StorageClass S, StorageClass SCAsWritten,
   1388                                  Expr *DefArg) {
   1389   return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
   1390                              S, SCAsWritten, DefArg);
   1391 }
   1392 
   1393 SourceRange ParmVarDecl::getSourceRange() const {
   1394   if (!hasInheritedDefaultArg()) {
   1395     SourceRange ArgRange = getDefaultArgRange();
   1396     if (ArgRange.isValid())
   1397       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
   1398   }
   1399 
   1400   return DeclaratorDecl::getSourceRange();
   1401 }
   1402 
   1403 Expr *ParmVarDecl::getDefaultArg() {
   1404   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
   1405   assert(!hasUninstantiatedDefaultArg() &&
   1406          "Default argument is not yet instantiated!");
   1407 
   1408   Expr *Arg = getInit();
   1409   if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
   1410     return E->getSubExpr();
   1411 
   1412   return Arg;
   1413 }
   1414 
   1415 unsigned ParmVarDecl::getNumDefaultArgTemporaries() const {
   1416   if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(getInit()))
   1417     return E->getNumTemporaries();
   1418 
   1419   return 0;
   1420 }
   1421 
   1422 CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) {
   1423   assert(getNumDefaultArgTemporaries() &&
   1424          "Default arguments does not have any temporaries!");
   1425 
   1426   ExprWithCleanups *E = cast<ExprWithCleanups>(getInit());
   1427   return E->getTemporary(i);
   1428 }
   1429 
   1430 SourceRange ParmVarDecl::getDefaultArgRange() const {
   1431   if (const Expr *E = getInit())
   1432     return E->getSourceRange();
   1433 
   1434   if (hasUninstantiatedDefaultArg())
   1435     return getUninstantiatedDefaultArg()->getSourceRange();
   1436 
   1437   return SourceRange();
   1438 }
   1439 
   1440 bool ParmVarDecl::isParameterPack() const {
   1441   return isa<PackExpansionType>(getType());
   1442 }
   1443 
   1444 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
   1445   getASTContext().setParameterIndex(this, parameterIndex);
   1446   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
   1447 }
   1448 
   1449 unsigned ParmVarDecl::getParameterIndexLarge() const {
   1450   return getASTContext().getParameterIndex(this);
   1451 }
   1452 
   1453 //===----------------------------------------------------------------------===//
   1454 // FunctionDecl Implementation
   1455 //===----------------------------------------------------------------------===//
   1456 
   1457 void FunctionDecl::getNameForDiagnostic(std::string &S,
   1458                                         const PrintingPolicy &Policy,
   1459                                         bool Qualified) const {
   1460   NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
   1461   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
   1462   if (TemplateArgs)
   1463     S += TemplateSpecializationType::PrintTemplateArgumentList(
   1464                                                          TemplateArgs->data(),
   1465                                                          TemplateArgs->size(),
   1466                                                                Policy);
   1467 
   1468 }
   1469 
   1470 bool FunctionDecl::isVariadic() const {
   1471   if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
   1472     return FT->isVariadic();
   1473   return false;
   1474 }
   1475 
   1476 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
   1477   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
   1478     if (I->Body || I->IsLateTemplateParsed) {
   1479       Definition = *I;
   1480       return true;
   1481     }
   1482   }
   1483 
   1484   return false;
   1485 }
   1486 
   1487 bool FunctionDecl::hasTrivialBody() const
   1488 {
   1489   Stmt *S = getBody();
   1490   if (!S) {
   1491     // Since we don't have a body for this function, we don't know if it's
   1492     // trivial or not.
   1493     return false;
   1494   }
   1495 
   1496   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
   1497     return true;
   1498   return false;
   1499 }
   1500 
   1501 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
   1502   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
   1503     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
   1504       Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
   1505       return true;
   1506     }
   1507   }
   1508 
   1509   return false;
   1510 }
   1511 
   1512 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
   1513   for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
   1514     if (I->Body) {
   1515       Definition = *I;
   1516       return I->Body.get(getASTContext().getExternalSource());
   1517     } else if (I->IsLateTemplateParsed) {
   1518       Definition = *I;
   1519       return 0;
   1520     }
   1521   }
   1522 
   1523   return 0;
   1524 }
   1525 
   1526 void FunctionDecl::setBody(Stmt *B) {
   1527   Body = B;
   1528   if (B)
   1529     EndRangeLoc = B->getLocEnd();
   1530 }
   1531 
   1532 void FunctionDecl::setPure(bool P) {
   1533   IsPure = P;
   1534   if (P)
   1535     if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
   1536       Parent->markedVirtualFunctionPure();
   1537 }
   1538 
   1539 bool FunctionDecl::isMain() const {
   1540   const TranslationUnitDecl *tunit =
   1541     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
   1542   return tunit &&
   1543          !tunit->getASTContext().getLangOptions().Freestanding &&
   1544          getIdentifier() &&
   1545          getIdentifier()->isStr("main");
   1546 }
   1547 
   1548 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
   1549   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
   1550   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
   1551          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
   1552          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
   1553          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
   1554 
   1555   if (isa<CXXRecordDecl>(getDeclContext())) return false;
   1556   assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
   1557 
   1558   const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
   1559   if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
   1560 
   1561   ASTContext &Context =
   1562     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
   1563       ->getASTContext();
   1564 
   1565   // The result type and first argument type are constant across all
   1566   // these operators.  The second argument must be exactly void*.
   1567   return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
   1568 }
   1569 
   1570 bool FunctionDecl::isExternC() const {
   1571   ASTContext &Context = getASTContext();
   1572   // In C, any non-static, non-overloadable function has external
   1573   // linkage.
   1574   if (!Context.getLangOptions().CPlusPlus)
   1575     return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>();
   1576 
   1577   const DeclContext *DC = getDeclContext();
   1578   if (DC->isRecord())
   1579     return false;
   1580 
   1581   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
   1582     if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))  {
   1583       if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
   1584         return getStorageClass() != SC_Static &&
   1585                !getAttr<OverloadableAttr>();
   1586 
   1587       break;
   1588     }
   1589   }
   1590 
   1591   return isMain();
   1592 }
   1593 
   1594 bool FunctionDecl::isGlobal() const {
   1595   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
   1596     return Method->isStatic();
   1597 
   1598   if (getStorageClass() == SC_Static)
   1599     return false;
   1600 
   1601   for (const DeclContext *DC = getDeclContext();
   1602        DC->isNamespace();
   1603        DC = DC->getParent()) {
   1604     if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
   1605       if (!Namespace->getDeclName())
   1606         return false;
   1607       break;
   1608     }
   1609   }
   1610 
   1611   return true;
   1612 }
   1613 
   1614 void
   1615 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
   1616   redeclarable_base::setPreviousDeclaration(PrevDecl);
   1617 
   1618   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
   1619     FunctionTemplateDecl *PrevFunTmpl
   1620       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
   1621     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
   1622     FunTmpl->setPreviousDeclaration(PrevFunTmpl);
   1623   }
   1624 
   1625   if (PrevDecl->IsInline)
   1626     IsInline = true;
   1627 }
   1628 
   1629 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
   1630   return getFirstDeclaration();
   1631 }
   1632 
   1633 FunctionDecl *FunctionDecl::getCanonicalDecl() {
   1634   return getFirstDeclaration();
   1635 }
   1636 
   1637 void FunctionDecl::setStorageClass(StorageClass SC) {
   1638   assert(isLegalForFunction(SC));
   1639   if (getStorageClass() != SC)
   1640     ClearLinkageCache();
   1641 
   1642   SClass = SC;
   1643 }
   1644 
   1645 /// \brief Returns a value indicating whether this function
   1646 /// corresponds to a builtin function.
   1647 ///
   1648 /// The function corresponds to a built-in function if it is
   1649 /// declared at translation scope or within an extern "C" block and
   1650 /// its name matches with the name of a builtin. The returned value
   1651 /// will be 0 for functions that do not correspond to a builtin, a
   1652 /// value of type \c Builtin::ID if in the target-independent range
   1653 /// \c [1,Builtin::First), or a target-specific builtin value.
   1654 unsigned FunctionDecl::getBuiltinID() const {
   1655   ASTContext &Context = getASTContext();
   1656   if (!getIdentifier() || !getIdentifier()->getBuiltinID())
   1657     return 0;
   1658 
   1659   unsigned BuiltinID = getIdentifier()->getBuiltinID();
   1660   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
   1661     return BuiltinID;
   1662 
   1663   // This function has the name of a known C library
   1664   // function. Determine whether it actually refers to the C library
   1665   // function or whether it just has the same name.
   1666 
   1667   // If this is a static function, it's not a builtin.
   1668   if (getStorageClass() == SC_Static)
   1669     return 0;
   1670 
   1671   // If this function is at translation-unit scope and we're not in
   1672   // C++, it refers to the C library function.
   1673   if (!Context.getLangOptions().CPlusPlus &&
   1674       getDeclContext()->isTranslationUnit())
   1675     return BuiltinID;
   1676 
   1677   // If the function is in an extern "C" linkage specification and is
   1678   // not marked "overloadable", it's the real function.
   1679   if (isa<LinkageSpecDecl>(getDeclContext()) &&
   1680       cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
   1681         == LinkageSpecDecl::lang_c &&
   1682       !getAttr<OverloadableAttr>())
   1683     return BuiltinID;
   1684 
   1685   // Not a builtin
   1686   return 0;
   1687 }
   1688 
   1689 
   1690 /// getNumParams - Return the number of parameters this function must have
   1691 /// based on its FunctionType.  This is the length of the ParamInfo array
   1692 /// after it has been created.
   1693 unsigned FunctionDecl::getNumParams() const {
   1694   const FunctionType *FT = getType()->getAs<FunctionType>();
   1695   if (isa<FunctionNoProtoType>(FT))
   1696     return 0;
   1697   return cast<FunctionProtoType>(FT)->getNumArgs();
   1698 
   1699 }
   1700 
   1701 void FunctionDecl::setParams(ASTContext &C,
   1702                              llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
   1703   assert(ParamInfo == 0 && "Already has param info!");
   1704   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
   1705 
   1706   // Zero params -> null pointer.
   1707   if (!NewParamInfo.empty()) {
   1708     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
   1709     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
   1710   }
   1711 }
   1712 
   1713 /// getMinRequiredArguments - Returns the minimum number of arguments
   1714 /// needed to call this function. This may be fewer than the number of
   1715 /// function parameters, if some of the parameters have default
   1716 /// arguments (in C++) or the last parameter is a parameter pack.
   1717 unsigned FunctionDecl::getMinRequiredArguments() const {
   1718   if (!getASTContext().getLangOptions().CPlusPlus)
   1719     return getNumParams();
   1720 
   1721   unsigned NumRequiredArgs = getNumParams();
   1722 
   1723   // If the last parameter is a parameter pack, we don't need an argument for
   1724   // it.
   1725   if (NumRequiredArgs > 0 &&
   1726       getParamDecl(NumRequiredArgs - 1)->isParameterPack())
   1727     --NumRequiredArgs;
   1728 
   1729   // If this parameter has a default argument, we don't need an argument for
   1730   // it.
   1731   while (NumRequiredArgs > 0 &&
   1732          getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
   1733     --NumRequiredArgs;
   1734 
   1735   // We might have parameter packs before the end. These can't be deduced,
   1736   // but they can still handle multiple arguments.
   1737   unsigned ArgIdx = NumRequiredArgs;
   1738   while (ArgIdx > 0) {
   1739     if (getParamDecl(ArgIdx - 1)->isParameterPack())
   1740       NumRequiredArgs = ArgIdx;
   1741 
   1742     --ArgIdx;
   1743   }
   1744 
   1745   return NumRequiredArgs;
   1746 }
   1747 
   1748 bool FunctionDecl::isInlined() const {
   1749   if (IsInline)
   1750     return true;
   1751 
   1752   if (isa<CXXMethodDecl>(this)) {
   1753     if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
   1754       return true;
   1755   }
   1756 
   1757   switch (getTemplateSpecializationKind()) {
   1758   case TSK_Undeclared:
   1759   case TSK_ExplicitSpecialization:
   1760     return false;
   1761 
   1762   case TSK_ImplicitInstantiation:
   1763   case TSK_ExplicitInstantiationDeclaration:
   1764   case TSK_ExplicitInstantiationDefinition:
   1765     // Handle below.
   1766     break;
   1767   }
   1768 
   1769   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
   1770   bool HasPattern = false;
   1771   if (PatternDecl)
   1772     HasPattern = PatternDecl->hasBody(PatternDecl);
   1773 
   1774   if (HasPattern && PatternDecl)
   1775     return PatternDecl->isInlined();
   1776 
   1777   return false;
   1778 }
   1779 
   1780 /// \brief For a function declaration in C or C++, determine whether this
   1781 /// declaration causes the definition to be externally visible.
   1782 ///
   1783 /// Determines whether this is the first non-inline redeclaration of an inline
   1784 /// function in a language where "inline" does not normally require an
   1785 /// externally visible definition.
   1786 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
   1787   assert(!doesThisDeclarationHaveABody() &&
   1788          "Must have a declaration without a body.");
   1789 
   1790   ASTContext &Context = getASTContext();
   1791 
   1792   // In C99 mode, a function may have an inline definition (causing it to
   1793   // be deferred) then redeclared later.  As a special case, "extern inline"
   1794   // is not required to produce an external symbol.
   1795   if (Context.getLangOptions().GNUInline || !Context.getLangOptions().C99 ||
   1796       Context.getLangOptions().CPlusPlus)
   1797     return false;
   1798   if (getLinkage() != ExternalLinkage || isInlineSpecified())
   1799     return false;
   1800   const FunctionDecl *Definition = 0;
   1801   if (hasBody(Definition))
   1802     return Definition->isInlined() &&
   1803            Definition->isInlineDefinitionExternallyVisible();
   1804   return false;
   1805 }
   1806 
   1807 /// \brief For an inline function definition in C or C++, determine whether the
   1808 /// definition will be externally visible.
   1809 ///
   1810 /// Inline function definitions are always available for inlining optimizations.
   1811 /// However, depending on the language dialect, declaration specifiers, and
   1812 /// attributes, the definition of an inline function may or may not be
   1813 /// "externally" visible to other translation units in the program.
   1814 ///
   1815 /// In C99, inline definitions are not externally visible by default. However,
   1816 /// if even one of the global-scope declarations is marked "extern inline", the
   1817 /// inline definition becomes externally visible (C99 6.7.4p6).
   1818 ///
   1819 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
   1820 /// definition, we use the GNU semantics for inline, which are nearly the
   1821 /// opposite of C99 semantics. In particular, "inline" by itself will create
   1822 /// an externally visible symbol, but "extern inline" will not create an
   1823 /// externally visible symbol.
   1824 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
   1825   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
   1826   assert(isInlined() && "Function must be inline");
   1827   ASTContext &Context = getASTContext();
   1828 
   1829   if (Context.getLangOptions().GNUInline || hasAttr<GNUInlineAttr>()) {
   1830     // If it's not the case that both 'inline' and 'extern' are
   1831     // specified on the definition, then this inline definition is
   1832     // externally visible.
   1833     if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
   1834       return true;
   1835 
   1836     // If any declaration is 'inline' but not 'extern', then this definition
   1837     // is externally visible.
   1838     for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
   1839          Redecl != RedeclEnd;
   1840          ++Redecl) {
   1841       if (Redecl->isInlineSpecified() &&
   1842           Redecl->getStorageClassAsWritten() != SC_Extern)
   1843         return true;
   1844     }
   1845 
   1846     return false;
   1847   }
   1848 
   1849   // C99 6.7.4p6:
   1850   //   [...] If all of the file scope declarations for a function in a
   1851   //   translation unit include the inline function specifier without extern,
   1852   //   then the definition in that translation unit is an inline definition.
   1853   for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
   1854        Redecl != RedeclEnd;
   1855        ++Redecl) {
   1856     // Only consider file-scope declarations in this test.
   1857     if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
   1858       continue;
   1859 
   1860     // Only consider explicit declarations; the presence of a builtin for a
   1861     // libcall shouldn't affect whether a definition is externally visible.
   1862     if (Redecl->isImplicit())
   1863       continue;
   1864 
   1865     if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
   1866       return true; // Not an inline definition
   1867   }
   1868 
   1869   // C99 6.7.4p6:
   1870   //   An inline definition does not provide an external definition for the
   1871   //   function, and does not forbid an external definition in another
   1872   //   translation unit.
   1873   return false;
   1874 }
   1875 
   1876 /// getOverloadedOperator - Which C++ overloaded operator this
   1877 /// function represents, if any.
   1878 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
   1879   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
   1880     return getDeclName().getCXXOverloadedOperator();
   1881   else
   1882     return OO_None;
   1883 }
   1884 
   1885 /// getLiteralIdentifier - The literal suffix identifier this function
   1886 /// represents, if any.
   1887 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
   1888   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
   1889     return getDeclName().getCXXLiteralIdentifier();
   1890   else
   1891     return 0;
   1892 }
   1893 
   1894 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
   1895   if (TemplateOrSpecialization.isNull())
   1896     return TK_NonTemplate;
   1897   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
   1898     return TK_FunctionTemplate;
   1899   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
   1900     return TK_MemberSpecialization;
   1901   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
   1902     return TK_FunctionTemplateSpecialization;
   1903   if (TemplateOrSpecialization.is
   1904                                <DependentFunctionTemplateSpecializationInfo*>())
   1905     return TK_DependentFunctionTemplateSpecialization;
   1906 
   1907   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
   1908 }
   1909 
   1910 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
   1911   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
   1912     return cast<FunctionDecl>(Info->getInstantiatedFrom());
   1913 
   1914   return 0;
   1915 }
   1916 
   1917 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
   1918   return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
   1919 }
   1920 
   1921 void
   1922 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
   1923                                                FunctionDecl *FD,
   1924                                                TemplateSpecializationKind TSK) {
   1925   assert(TemplateOrSpecialization.isNull() &&
   1926          "Member function is already a specialization");
   1927   MemberSpecializationInfo *Info
   1928     = new (C) MemberSpecializationInfo(FD, TSK);
   1929   TemplateOrSpecialization = Info;
   1930 }
   1931 
   1932 bool FunctionDecl::isImplicitlyInstantiable() const {
   1933   // If the function is invalid, it can't be implicitly instantiated.
   1934   if (isInvalidDecl())
   1935     return false;
   1936 
   1937   switch (getTemplateSpecializationKind()) {
   1938   case TSK_Undeclared:
   1939   case TSK_ExplicitInstantiationDefinition:
   1940     return false;
   1941 
   1942   case TSK_ImplicitInstantiation:
   1943     return true;
   1944 
   1945   // It is possible to instantiate TSK_ExplicitSpecialization kind
   1946   // if the FunctionDecl has a class scope specialization pattern.
   1947   case TSK_ExplicitSpecialization:
   1948     return getClassScopeSpecializationPattern() != 0;
   1949 
   1950   case TSK_ExplicitInstantiationDeclaration:
   1951     // Handled below.
   1952     break;
   1953   }
   1954 
   1955   // Find the actual template from which we will instantiate.
   1956   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
   1957   bool HasPattern = false;
   1958   if (PatternDecl)
   1959     HasPattern = PatternDecl->hasBody(PatternDecl);
   1960 
   1961   // C++0x [temp.explicit]p9:
   1962   //   Except for inline functions, other explicit instantiation declarations
   1963   //   have the effect of suppressing the implicit instantiation of the entity
   1964   //   to which they refer.
   1965   if (!HasPattern || !PatternDecl)
   1966     return true;
   1967 
   1968   return PatternDecl->isInlined();
   1969 }
   1970 
   1971 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
   1972   // Handle class scope explicit specialization special case.
   1973   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
   1974     return getClassScopeSpecializationPattern();
   1975 
   1976   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
   1977     while (Primary->getInstantiatedFromMemberTemplate()) {
   1978       // If we have hit a point where the user provided a specialization of
   1979       // this template, we're done looking.
   1980       if (Primary->isMemberSpecialization())
   1981         break;
   1982 
   1983       Primary = Primary->getInstantiatedFromMemberTemplate();
   1984     }
   1985 
   1986     return Primary->getTemplatedDecl();
   1987   }
   1988 
   1989   return getInstantiatedFromMemberFunction();
   1990 }
   1991 
   1992 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
   1993   if (FunctionTemplateSpecializationInfo *Info
   1994         = TemplateOrSpecialization
   1995             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
   1996     return Info->Template.getPointer();
   1997   }
   1998   return 0;
   1999 }
   2000 
   2001 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
   2002     return getASTContext().getClassScopeSpecializationPattern(this);
   2003 }
   2004 
   2005 const TemplateArgumentList *
   2006 FunctionDecl::getTemplateSpecializationArgs() const {
   2007   if (FunctionTemplateSpecializationInfo *Info
   2008         = TemplateOrSpecialization
   2009             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
   2010     return Info->TemplateArguments;
   2011   }
   2012   return 0;
   2013 }
   2014 
   2015 const ASTTemplateArgumentListInfo *
   2016 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
   2017   if (FunctionTemplateSpecializationInfo *Info
   2018         = TemplateOrSpecialization
   2019             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
   2020     return Info->TemplateArgumentsAsWritten;
   2021   }
   2022   return 0;
   2023 }
   2024 
   2025 void
   2026 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
   2027                                                 FunctionTemplateDecl *Template,
   2028                                      const TemplateArgumentList *TemplateArgs,
   2029                                                 void *InsertPos,
   2030                                                 TemplateSpecializationKind TSK,
   2031                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
   2032                                           SourceLocation PointOfInstantiation) {
   2033   assert(TSK != TSK_Undeclared &&
   2034          "Must specify the type of function template specialization");
   2035   FunctionTemplateSpecializationInfo *Info
   2036     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
   2037   if (!Info)
   2038     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
   2039                                                       TemplateArgs,
   2040                                                       TemplateArgsAsWritten,
   2041                                                       PointOfInstantiation);
   2042   TemplateOrSpecialization = Info;
   2043 
   2044   // Insert this function template specialization into the set of known
   2045   // function template specializations.
   2046   if (InsertPos)
   2047     Template->addSpecialization(Info, InsertPos);
   2048   else {
   2049     // Try to insert the new node. If there is an existing node, leave it, the
   2050     // set will contain the canonical decls while
   2051     // FunctionTemplateDecl::findSpecialization will return
   2052     // the most recent redeclarations.
   2053     FunctionTemplateSpecializationInfo *Existing
   2054       = Template->getSpecializations().GetOrInsertNode(Info);
   2055     (void)Existing;
   2056     assert((!Existing || Existing->Function->isCanonicalDecl()) &&
   2057            "Set is supposed to only contain canonical decls");
   2058   }
   2059 }
   2060 
   2061 void
   2062 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
   2063                                     const UnresolvedSetImpl &Templates,
   2064                              const TemplateArgumentListInfo &TemplateArgs) {
   2065   assert(TemplateOrSpecialization.isNull());
   2066   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
   2067   Size += Templates.size() * sizeof(FunctionTemplateDecl*);
   2068   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
   2069   void *Buffer = Context.Allocate(Size);
   2070   DependentFunctionTemplateSpecializationInfo *Info =
   2071     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
   2072                                                              TemplateArgs);
   2073   TemplateOrSpecialization = Info;
   2074 }
   2075 
   2076 DependentFunctionTemplateSpecializationInfo::
   2077 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
   2078                                       const TemplateArgumentListInfo &TArgs)
   2079   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
   2080 
   2081   d.NumTemplates = Ts.size();
   2082   d.NumArgs = TArgs.size();
   2083 
   2084   FunctionTemplateDecl **TsArray =
   2085     const_cast<FunctionTemplateDecl**>(getTemplates());
   2086   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
   2087     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
   2088 
   2089   TemplateArgumentLoc *ArgsArray =
   2090     const_cast<TemplateArgumentLoc*>(getTemplateArgs());
   2091   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
   2092     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
   2093 }
   2094 
   2095 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
   2096   // For a function template specialization, query the specialization
   2097   // information object.
   2098   FunctionTemplateSpecializationInfo *FTSInfo
   2099     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
   2100   if (FTSInfo)
   2101     return FTSInfo->getTemplateSpecializationKind();
   2102 
   2103   MemberSpecializationInfo *MSInfo
   2104     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
   2105   if (MSInfo)
   2106     return MSInfo->getTemplateSpecializationKind();
   2107 
   2108   return TSK_Undeclared;
   2109 }
   2110 
   2111 void
   2112 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
   2113                                           SourceLocation PointOfInstantiation) {
   2114   if (FunctionTemplateSpecializationInfo *FTSInfo
   2115         = TemplateOrSpecialization.dyn_cast<
   2116                                     FunctionTemplateSpecializationInfo*>()) {
   2117     FTSInfo->setTemplateSpecializationKind(TSK);
   2118     if (TSK != TSK_ExplicitSpecialization &&
   2119         PointOfInstantiation.isValid() &&
   2120         FTSInfo->getPointOfInstantiation().isInvalid())
   2121       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
   2122   } else if (MemberSpecializationInfo *MSInfo
   2123              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
   2124     MSInfo->setTemplateSpecializationKind(TSK);
   2125     if (TSK != TSK_ExplicitSpecialization &&
   2126         PointOfInstantiation.isValid() &&
   2127         MSInfo->getPointOfInstantiation().isInvalid())
   2128       MSInfo->setPointOfInstantiation(PointOfInstantiation);
   2129   } else
   2130     llvm_unreachable("Function cannot have a template specialization kind");
   2131 }
   2132 
   2133 SourceLocation FunctionDecl::getPointOfInstantiation() const {
   2134   if (FunctionTemplateSpecializationInfo *FTSInfo
   2135         = TemplateOrSpecialization.dyn_cast<
   2136                                         FunctionTemplateSpecializationInfo*>())
   2137     return FTSInfo->getPointOfInstantiation();
   2138   else if (MemberSpecializationInfo *MSInfo
   2139              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
   2140     return MSInfo->getPointOfInstantiation();
   2141 
   2142   return SourceLocation();
   2143 }
   2144 
   2145 bool FunctionDecl::isOutOfLine() const {
   2146   if (Decl::isOutOfLine())
   2147     return true;
   2148 
   2149   // If this function was instantiated from a member function of a
   2150   // class template, check whether that member function was defined out-of-line.
   2151   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
   2152     const FunctionDecl *Definition;
   2153     if (FD->hasBody(Definition))
   2154       return Definition->isOutOfLine();
   2155   }
   2156 
   2157   // If this function was instantiated from a function template,
   2158   // check whether that function template was defined out-of-line.
   2159   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
   2160     const FunctionDecl *Definition;
   2161     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
   2162       return Definition->isOutOfLine();
   2163   }
   2164 
   2165   return false;
   2166 }
   2167 
   2168 SourceRange FunctionDecl::getSourceRange() const {
   2169   return SourceRange(getOuterLocStart(), EndRangeLoc);
   2170 }
   2171 
   2172 //===----------------------------------------------------------------------===//
   2173 // FieldDecl Implementation
   2174 //===----------------------------------------------------------------------===//
   2175 
   2176 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
   2177                              SourceLocation StartLoc, SourceLocation IdLoc,
   2178                              IdentifierInfo *Id, QualType T,
   2179                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
   2180                              bool HasInit) {
   2181   return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
   2182                            BW, Mutable, HasInit);
   2183 }
   2184 
   2185 bool FieldDecl::isAnonymousStructOrUnion() const {
   2186   if (!isImplicit() || getDeclName())
   2187     return false;
   2188 
   2189   if (const RecordType *Record = getType()->getAs<RecordType>())
   2190     return Record->getDecl()->isAnonymousStructOrUnion();
   2191 
   2192   return false;
   2193 }
   2194 
   2195 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
   2196   assert(isBitField() && "not a bitfield");
   2197   Expr *BitWidth = InitializerOrBitWidth.getPointer();
   2198   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
   2199 }
   2200 
   2201 unsigned FieldDecl::getFieldIndex() const {
   2202   if (CachedFieldIndex) return CachedFieldIndex - 1;
   2203 
   2204   unsigned index = 0;
   2205   const RecordDecl *RD = getParent();
   2206   const FieldDecl *LastFD = 0;
   2207   bool IsMsStruct = RD->hasAttr<MsStructAttr>();
   2208 
   2209   RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
   2210   while (true) {
   2211     assert(i != e && "failed to find field in parent!");
   2212     if (*i == this)
   2213       break;
   2214 
   2215     if (IsMsStruct) {
   2216       // Zero-length bitfields following non-bitfield members are ignored.
   2217       if (getASTContext().ZeroBitfieldFollowsNonBitfield((*i), LastFD)) {
   2218         ++i;
   2219         continue;
   2220       }
   2221       LastFD = (*i);
   2222     }
   2223     ++i;
   2224     ++index;
   2225   }
   2226 
   2227   CachedFieldIndex = index + 1;
   2228   return index;
   2229 }
   2230 
   2231 SourceRange FieldDecl::getSourceRange() const {
   2232   if (const Expr *E = InitializerOrBitWidth.getPointer())
   2233     return SourceRange(getInnerLocStart(), E->getLocEnd());
   2234   return DeclaratorDecl::getSourceRange();
   2235 }
   2236 
   2237 void FieldDecl::setInClassInitializer(Expr *Init) {
   2238   assert(!InitializerOrBitWidth.getPointer() &&
   2239          "bit width or initializer already set");
   2240   InitializerOrBitWidth.setPointer(Init);
   2241   InitializerOrBitWidth.setInt(0);
   2242 }
   2243 
   2244 //===----------------------------------------------------------------------===//
   2245 // TagDecl Implementation
   2246 //===----------------------------------------------------------------------===//
   2247 
   2248 SourceLocation TagDecl::getOuterLocStart() const {
   2249   return getTemplateOrInnerLocStart(this);
   2250 }
   2251 
   2252 SourceRange TagDecl::getSourceRange() const {
   2253   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
   2254   return SourceRange(getOuterLocStart(), E);
   2255 }
   2256 
   2257 TagDecl* TagDecl::getCanonicalDecl() {
   2258   return getFirstDeclaration();
   2259 }
   2260 
   2261 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
   2262   TypedefNameDeclOrQualifier = TDD;
   2263   if (TypeForDecl)
   2264     const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
   2265   ClearLinkageCache();
   2266 }
   2267 
   2268 void TagDecl::startDefinition() {
   2269   IsBeingDefined = true;
   2270 
   2271   if (isa<CXXRecordDecl>(this)) {
   2272     CXXRecordDecl *D = cast<CXXRecordDecl>(this);
   2273     struct CXXRecordDecl::DefinitionData *Data =
   2274       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
   2275     for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
   2276       cast<CXXRecordDecl>(*I)->DefinitionData = Data;
   2277   }
   2278 }
   2279 
   2280 void TagDecl::completeDefinition() {
   2281   assert((!isa<CXXRecordDecl>(this) ||
   2282           cast<CXXRecordDecl>(this)->hasDefinition()) &&
   2283          "definition completed but not started");
   2284 
   2285   IsCompleteDefinition = true;
   2286   IsBeingDefined = false;
   2287 
   2288   if (ASTMutationListener *L = getASTMutationListener())
   2289     L->CompletedTagDefinition(this);
   2290 }
   2291 
   2292 TagDecl *TagDecl::getDefinition() const {
   2293   if (isCompleteDefinition())
   2294     return const_cast<TagDecl *>(this);
   2295   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
   2296     return CXXRD->getDefinition();
   2297 
   2298   for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
   2299        R != REnd; ++R)
   2300     if (R->isCompleteDefinition())
   2301       return *R;
   2302 
   2303   return 0;
   2304 }
   2305 
   2306 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
   2307   if (QualifierLoc) {
   2308     // Make sure the extended qualifier info is allocated.
   2309     if (!hasExtInfo())
   2310       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
   2311     // Set qualifier info.
   2312     getExtInfo()->QualifierLoc = QualifierLoc;
   2313   } else {
   2314     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
   2315     if (hasExtInfo()) {
   2316       if (getExtInfo()->NumTemplParamLists == 0) {
   2317         getASTContext().Deallocate(getExtInfo());
   2318         TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
   2319       }
   2320       else
   2321         getExtInfo()->QualifierLoc = QualifierLoc;
   2322     }
   2323   }
   2324 }
   2325 
   2326 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
   2327                                             unsigned NumTPLists,
   2328                                             TemplateParameterList **TPLists) {
   2329   assert(NumTPLists > 0);
   2330   // Make sure the extended decl info is allocated.
   2331   if (!hasExtInfo())
   2332     // Allocate external info struct.
   2333     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
   2334   // Set the template parameter lists info.
   2335   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
   2336 }
   2337 
   2338 //===----------------------------------------------------------------------===//
   2339 // EnumDecl Implementation
   2340 //===----------------------------------------------------------------------===//
   2341 
   2342 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
   2343                            SourceLocation StartLoc, SourceLocation IdLoc,
   2344                            IdentifierInfo *Id,
   2345                            EnumDecl *PrevDecl, bool IsScoped,
   2346                            bool IsScopedUsingClassTag, bool IsFixed) {
   2347   EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
   2348                                     IsScoped, IsScopedUsingClassTag, IsFixed);
   2349   C.getTypeDeclType(Enum, PrevDecl);
   2350   return Enum;
   2351 }
   2352 
   2353 EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) {
   2354   return new (C) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
   2355                           false, false, false);
   2356 }
   2357 
   2358 void EnumDecl::completeDefinition(QualType NewType,
   2359                                   QualType NewPromotionType,
   2360                                   unsigned NumPositiveBits,
   2361                                   unsigned NumNegativeBits) {
   2362   assert(!isCompleteDefinition() && "Cannot redefine enums!");
   2363   if (!IntegerType)
   2364     IntegerType = NewType.getTypePtr();
   2365   PromotionType = NewPromotionType;
   2366   setNumPositiveBits(NumPositiveBits);
   2367   setNumNegativeBits(NumNegativeBits);
   2368   TagDecl::completeDefinition();
   2369 }
   2370 
   2371 //===----------------------------------------------------------------------===//
   2372 // RecordDecl Implementation
   2373 //===----------------------------------------------------------------------===//
   2374 
   2375 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
   2376                        SourceLocation StartLoc, SourceLocation IdLoc,
   2377                        IdentifierInfo *Id, RecordDecl *PrevDecl)
   2378   : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
   2379   HasFlexibleArrayMember = false;
   2380   AnonymousStructOrUnion = false;
   2381   HasObjectMember = false;
   2382   LoadedFieldsFromExternalStorage = false;
   2383   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
   2384 }
   2385 
   2386 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
   2387                                SourceLocation StartLoc, SourceLocation IdLoc,
   2388                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
   2389   RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
   2390                                      PrevDecl);
   2391   C.getTypeDeclType(R, PrevDecl);
   2392   return R;
   2393 }
   2394 
   2395 RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) {
   2396   return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
   2397                             SourceLocation(), 0, 0);
   2398 }
   2399 
   2400 bool RecordDecl::isInjectedClassName() const {
   2401   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
   2402     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
   2403 }
   2404 
   2405 RecordDecl::field_iterator RecordDecl::field_begin() const {
   2406   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
   2407     LoadFieldsFromExternalStorage();
   2408 
   2409   return field_iterator(decl_iterator(FirstDecl));
   2410 }
   2411 
   2412 /// completeDefinition - Notes that the definition of this type is now
   2413 /// complete.
   2414 void RecordDecl::completeDefinition() {
   2415   assert(!isCompleteDefinition() && "Cannot redefine record!");
   2416   TagDecl::completeDefinition();
   2417 }
   2418 
   2419 void RecordDecl::LoadFieldsFromExternalStorage() const {
   2420   ExternalASTSource *Source = getASTContext().getExternalSource();
   2421   assert(hasExternalLexicalStorage() && Source && "No external storage?");
   2422 
   2423   // Notify that we have a RecordDecl doing some initialization.
   2424   ExternalASTSource::Deserializing TheFields(Source);
   2425 
   2426   SmallVector<Decl*, 64> Decls;
   2427   LoadedFieldsFromExternalStorage = true;
   2428   switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
   2429   case ELR_Success:
   2430     break;
   2431 
   2432   case ELR_AlreadyLoaded:
   2433   case ELR_Failure:
   2434     return;
   2435   }
   2436 
   2437 #ifndef NDEBUG
   2438   // Check that all decls we got were FieldDecls.
   2439   for (unsigned i=0, e=Decls.size(); i != e; ++i)
   2440     assert(isa<FieldDecl>(Decls[i]));
   2441 #endif
   2442 
   2443   if (Decls.empty())
   2444     return;
   2445 
   2446   llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
   2447                                                  /*FieldsAlreadyLoaded=*/false);
   2448 }
   2449 
   2450 //===----------------------------------------------------------------------===//
   2451 // BlockDecl Implementation
   2452 //===----------------------------------------------------------------------===//
   2453 
   2454 void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
   2455   assert(ParamInfo == 0 && "Already has param info!");
   2456 
   2457   // Zero params -> null pointer.
   2458   if (!NewParamInfo.empty()) {
   2459     NumParams = NewParamInfo.size();
   2460     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
   2461     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
   2462   }
   2463 }
   2464 
   2465 void BlockDecl::setCaptures(ASTContext &Context,
   2466                             const Capture *begin,
   2467                             const Capture *end,
   2468                             bool capturesCXXThis) {
   2469   CapturesCXXThis = capturesCXXThis;
   2470 
   2471   if (begin == end) {
   2472     NumCaptures = 0;
   2473     Captures = 0;
   2474     return;
   2475   }
   2476 
   2477   NumCaptures = end - begin;
   2478 
   2479   // Avoid new Capture[] because we don't want to provide a default
   2480   // constructor.
   2481   size_t allocationSize = NumCaptures * sizeof(Capture);
   2482   void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
   2483   memcpy(buffer, begin, allocationSize);
   2484   Captures = static_cast<Capture*>(buffer);
   2485 }
   2486 
   2487 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
   2488   for (capture_const_iterator
   2489          i = capture_begin(), e = capture_end(); i != e; ++i)
   2490     // Only auto vars can be captured, so no redeclaration worries.
   2491     if (i->getVariable() == variable)
   2492       return true;
   2493 
   2494   return false;
   2495 }
   2496 
   2497 SourceRange BlockDecl::getSourceRange() const {
   2498   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
   2499 }
   2500 
   2501 //===----------------------------------------------------------------------===//
   2502 // Other Decl Allocation/Deallocation Method Implementations
   2503 //===----------------------------------------------------------------------===//
   2504 
   2505 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
   2506   return new (C) TranslationUnitDecl(C);
   2507 }
   2508 
   2509 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
   2510                              SourceLocation IdentL, IdentifierInfo *II) {
   2511   return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
   2512 }
   2513 
   2514 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
   2515                              SourceLocation IdentL, IdentifierInfo *II,
   2516                              SourceLocation GnuLabelL) {
   2517   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
   2518   return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
   2519 }
   2520 
   2521 
   2522 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
   2523                                      SourceLocation StartLoc,
   2524                                      SourceLocation IdLoc, IdentifierInfo *Id) {
   2525   return new (C) NamespaceDecl(DC, StartLoc, IdLoc, Id);
   2526 }
   2527 
   2528 NamespaceDecl *NamespaceDecl::getNextNamespace() {
   2529   return dyn_cast_or_null<NamespaceDecl>(
   2530                        NextNamespace.get(getASTContext().getExternalSource()));
   2531 }
   2532 
   2533 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
   2534                                              SourceLocation IdLoc,
   2535                                              IdentifierInfo *Id,
   2536                                              QualType Type) {
   2537   return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
   2538 }
   2539 
   2540 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
   2541                                    SourceLocation StartLoc,
   2542                                    const DeclarationNameInfo &NameInfo,
   2543                                    QualType T, TypeSourceInfo *TInfo,
   2544                                    StorageClass SC, StorageClass SCAsWritten,
   2545                                    bool isInlineSpecified,
   2546                                    bool hasWrittenPrototype,
   2547                                    bool isConstexprSpecified) {
   2548   FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
   2549                                            T, TInfo, SC, SCAsWritten,
   2550                                            isInlineSpecified,
   2551                                            isConstexprSpecified);
   2552   New->HasWrittenPrototype = hasWrittenPrototype;
   2553   return New;
   2554 }
   2555 
   2556 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
   2557   return new (C) BlockDecl(DC, L);
   2558 }
   2559 
   2560 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
   2561                                            SourceLocation L,
   2562                                            IdentifierInfo *Id, QualType T,
   2563                                            Expr *E, const llvm::APSInt &V) {
   2564   return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
   2565 }
   2566 
   2567 IndirectFieldDecl *
   2568 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
   2569                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
   2570                           unsigned CHS) {
   2571   return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
   2572 }
   2573 
   2574 SourceRange EnumConstantDecl::getSourceRange() const {
   2575   SourceLocation End = getLocation();
   2576   if (Init)
   2577     End = Init->getLocEnd();
   2578   return SourceRange(getLocation(), End);
   2579 }
   2580 
   2581 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
   2582                                  SourceLocation StartLoc, SourceLocation IdLoc,
   2583                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
   2584   return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
   2585 }
   2586 
   2587 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
   2588                                      SourceLocation StartLoc,
   2589                                      SourceLocation IdLoc, IdentifierInfo *Id,
   2590                                      TypeSourceInfo *TInfo) {
   2591   return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
   2592 }
   2593 
   2594 SourceRange TypedefDecl::getSourceRange() const {
   2595   SourceLocation RangeEnd = getLocation();
   2596   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
   2597     if (typeIsPostfix(TInfo->getType()))
   2598       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
   2599   }
   2600   return SourceRange(getLocStart(), RangeEnd);
   2601 }
   2602 
   2603 SourceRange TypeAliasDecl::getSourceRange() const {
   2604   SourceLocation RangeEnd = getLocStart();
   2605   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
   2606     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
   2607   return SourceRange(getLocStart(), RangeEnd);
   2608 }
   2609 
   2610 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
   2611                                            StringLiteral *Str,
   2612                                            SourceLocation AsmLoc,
   2613                                            SourceLocation RParenLoc) {
   2614   return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
   2615 }
   2616