xref: /llvm-project-15.0.7/clang/lib/AST/Decl.cpp (revision 9bca298f)
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/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyPrinter.h"
24 #include "clang/AST/Stmt.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/IdentifierTable.h"
28 #include "clang/Basic/Module.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include <algorithm>
33 
34 using namespace clang;
35 
36 Decl *clang::getPrimaryMergedDecl(Decl *D) {
37   return D->getASTContext().getPrimaryMergedDecl(D);
38 }
39 
40 //===----------------------------------------------------------------------===//
41 // NamedDecl Implementation
42 //===----------------------------------------------------------------------===//
43 
44 // Visibility rules aren't rigorously externally specified, but here
45 // are the basic principles behind what we implement:
46 //
47 // 1. An explicit visibility attribute is generally a direct expression
48 // of the user's intent and should be honored.  Only the innermost
49 // visibility attribute applies.  If no visibility attribute applies,
50 // global visibility settings are considered.
51 //
52 // 2. There is one caveat to the above: on or in a template pattern,
53 // an explicit visibility attribute is just a default rule, and
54 // visibility can be decreased by the visibility of template
55 // arguments.  But this, too, has an exception: an attribute on an
56 // explicit specialization or instantiation causes all the visibility
57 // restrictions of the template arguments to be ignored.
58 //
59 // 3. A variable that does not otherwise have explicit visibility can
60 // be restricted by the visibility of its type.
61 //
62 // 4. A visibility restriction is explicit if it comes from an
63 // attribute (or something like it), not a global visibility setting.
64 // When emitting a reference to an external symbol, visibility
65 // restrictions are ignored unless they are explicit.
66 //
67 // 5. When computing the visibility of a non-type, including a
68 // non-type member of a class, only non-type visibility restrictions
69 // are considered: the 'visibility' attribute, global value-visibility
70 // settings, and a few special cases like __private_extern.
71 //
72 // 6. When computing the visibility of a type, including a type member
73 // of a class, only type visibility restrictions are considered:
74 // the 'type_visibility' attribute and global type-visibility settings.
75 // However, a 'visibility' attribute counts as a 'type_visibility'
76 // attribute on any declaration that only has the former.
77 //
78 // The visibility of a "secondary" entity, like a template argument,
79 // is computed using the kind of that entity, not the kind of the
80 // primary entity for which we are computing visibility.  For example,
81 // the visibility of a specialization of either of these templates:
82 //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
83 //   template <class T, bool (&compare)(T, X)> class matcher;
84 // is restricted according to the type visibility of the argument 'T',
85 // the type visibility of 'bool(&)(T,X)', and the value visibility of
86 // the argument function 'compare'.  That 'has_match' is a value
87 // and 'matcher' is a type only matters when looking for attributes
88 // and settings from the immediate context.
89 
90 const unsigned IgnoreExplicitVisibilityBit = 2;
91 const unsigned IgnoreAllVisibilityBit = 4;
92 
93 /// Kinds of LV computation.  The linkage side of the computation is
94 /// always the same, but different things can change how visibility is
95 /// computed.
96 enum LVComputationKind {
97   /// Do an LV computation for, ultimately, a type.
98   /// Visibility may be restricted by type visibility settings and
99   /// the visibility of template arguments.
100   LVForType = NamedDecl::VisibilityForType,
101 
102   /// Do an LV computation for, ultimately, a non-type declaration.
103   /// Visibility may be restricted by value visibility settings and
104   /// the visibility of template arguments.
105   LVForValue = NamedDecl::VisibilityForValue,
106 
107   /// Do an LV computation for, ultimately, a type that already has
108   /// some sort of explicit visibility.  Visibility may only be
109   /// restricted by the visibility of template arguments.
110   LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
111 
112   /// Do an LV computation for, ultimately, a non-type declaration
113   /// that already has some sort of explicit visibility.  Visibility
114   /// may only be restricted by the visibility of template arguments.
115   LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
116 
117   /// Do an LV computation when we only care about the linkage.
118   LVForLinkageOnly =
119       LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
120 };
121 
122 /// Does this computation kind permit us to consider additional
123 /// visibility settings from attributes and the like?
124 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
125   return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
126 }
127 
128 /// Given an LVComputationKind, return one of the same type/value sort
129 /// that records that it already has explicit visibility.
130 static LVComputationKind
131 withExplicitVisibilityAlready(LVComputationKind oldKind) {
132   LVComputationKind newKind =
133     static_cast<LVComputationKind>(unsigned(oldKind) |
134                                    IgnoreExplicitVisibilityBit);
135   assert(oldKind != LVForType          || newKind == LVForExplicitType);
136   assert(oldKind != LVForValue         || newKind == LVForExplicitValue);
137   assert(oldKind != LVForExplicitType  || newKind == LVForExplicitType);
138   assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
139   return newKind;
140 }
141 
142 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
143                                                   LVComputationKind kind) {
144   assert(!hasExplicitVisibilityAlready(kind) &&
145          "asking for explicit visibility when we shouldn't be");
146   return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
147 }
148 
149 /// Is the given declaration a "type" or a "value" for the purposes of
150 /// visibility computation?
151 static bool usesTypeVisibility(const NamedDecl *D) {
152   return isa<TypeDecl>(D) ||
153          isa<ClassTemplateDecl>(D) ||
154          isa<ObjCInterfaceDecl>(D);
155 }
156 
157 /// Does the given declaration have member specialization information,
158 /// and if so, is it an explicit specialization?
159 template <class T> static typename
160 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
161 isExplicitMemberSpecialization(const T *D) {
162   if (const MemberSpecializationInfo *member =
163         D->getMemberSpecializationInfo()) {
164     return member->isExplicitSpecialization();
165   }
166   return false;
167 }
168 
169 /// For templates, this question is easier: a member template can't be
170 /// explicitly instantiated, so there's a single bit indicating whether
171 /// or not this is an explicit member specialization.
172 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
173   return D->isMemberSpecialization();
174 }
175 
176 /// Given a visibility attribute, return the explicit visibility
177 /// associated with it.
178 template <class T>
179 static Visibility getVisibilityFromAttr(const T *attr) {
180   switch (attr->getVisibility()) {
181   case T::Default:
182     return DefaultVisibility;
183   case T::Hidden:
184     return HiddenVisibility;
185   case T::Protected:
186     return ProtectedVisibility;
187   }
188   llvm_unreachable("bad visibility kind");
189 }
190 
191 /// Return the explicit visibility of the given declaration.
192 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
193                                     NamedDecl::ExplicitVisibilityKind kind) {
194   // If we're ultimately computing the visibility of a type, look for
195   // a 'type_visibility' attribute before looking for 'visibility'.
196   if (kind == NamedDecl::VisibilityForType) {
197     if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) {
198       return getVisibilityFromAttr(A);
199     }
200   }
201 
202   // If this declaration has an explicit visibility attribute, use it.
203   if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
204     return getVisibilityFromAttr(A);
205   }
206 
207   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
208   // implies visibility(default).
209   if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
210     for (specific_attr_iterator<AvailabilityAttr>
211               A = D->specific_attr_begin<AvailabilityAttr>(),
212            AEnd = D->specific_attr_end<AvailabilityAttr>();
213          A != AEnd; ++A)
214       if ((*A)->getPlatform()->getName().equals("macosx"))
215         return DefaultVisibility;
216   }
217 
218   return None;
219 }
220 
221 static LinkageInfo
222 getLVForType(const Type &T, LVComputationKind computation) {
223   if (computation == LVForLinkageOnly)
224     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
225   return T.getLinkageAndVisibility();
226 }
227 
228 /// \brief Get the most restrictive linkage for the types in the given
229 /// template parameter list.  For visibility purposes, template
230 /// parameters are part of the signature of a template.
231 static LinkageInfo
232 getLVForTemplateParameterList(const TemplateParameterList *params,
233                               LVComputationKind computation) {
234   LinkageInfo LV;
235   for (TemplateParameterList::const_iterator P = params->begin(),
236                                           PEnd = params->end();
237        P != PEnd; ++P) {
238 
239     // Template type parameters are the most common and never
240     // contribute to visibility, pack or not.
241     if (isa<TemplateTypeParmDecl>(*P))
242       continue;
243 
244     // Non-type template parameters can be restricted by the value type, e.g.
245     //   template <enum X> class A { ... };
246     // We have to be careful here, though, because we can be dealing with
247     // dependent types.
248     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
249       // Handle the non-pack case first.
250       if (!NTTP->isExpandedParameterPack()) {
251         if (!NTTP->getType()->isDependentType()) {
252           LV.merge(getLVForType(*NTTP->getType(), computation));
253         }
254         continue;
255       }
256 
257       // Look at all the types in an expanded pack.
258       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
259         QualType type = NTTP->getExpansionType(i);
260         if (!type->isDependentType())
261           LV.merge(type->getLinkageAndVisibility());
262       }
263       continue;
264     }
265 
266     // Template template parameters can be restricted by their
267     // template parameters, recursively.
268     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
269 
270     // Handle the non-pack case first.
271     if (!TTP->isExpandedParameterPack()) {
272       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
273                                              computation));
274       continue;
275     }
276 
277     // Look at all expansions in an expanded pack.
278     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
279            i != n; ++i) {
280       LV.merge(getLVForTemplateParameterList(
281           TTP->getExpansionTemplateParameters(i), computation));
282     }
283   }
284 
285   return LV;
286 }
287 
288 /// getLVForDecl - Get the linkage and visibility for the given declaration.
289 static LinkageInfo getLVForDecl(const NamedDecl *D,
290                                 LVComputationKind computation);
291 
292 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
293   const Decl *Ret = NULL;
294   const DeclContext *DC = D->getDeclContext();
295   while (DC->getDeclKind() != Decl::TranslationUnit) {
296     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
297       Ret = cast<Decl>(DC);
298     DC = DC->getParent();
299   }
300   return Ret;
301 }
302 
303 /// \brief Get the most restrictive linkage for the types and
304 /// declarations in the given template argument list.
305 ///
306 /// Note that we don't take an LVComputationKind because we always
307 /// want to honor the visibility of template arguments in the same way.
308 static LinkageInfo
309 getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args,
310                              LVComputationKind computation) {
311   LinkageInfo LV;
312 
313   for (unsigned i = 0, e = args.size(); i != e; ++i) {
314     const TemplateArgument &arg = args[i];
315     switch (arg.getKind()) {
316     case TemplateArgument::Null:
317     case TemplateArgument::Integral:
318     case TemplateArgument::Expression:
319       continue;
320 
321     case TemplateArgument::Type:
322       LV.merge(getLVForType(*arg.getAsType(), computation));
323       continue;
324 
325     case TemplateArgument::Declaration:
326       if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) {
327         assert(!usesTypeVisibility(ND));
328         LV.merge(getLVForDecl(ND, computation));
329       }
330       continue;
331 
332     case TemplateArgument::NullPtr:
333       LV.merge(arg.getNullPtrType()->getLinkageAndVisibility());
334       continue;
335 
336     case TemplateArgument::Template:
337     case TemplateArgument::TemplateExpansion:
338       if (TemplateDecl *Template
339                 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
340         LV.merge(getLVForDecl(Template, computation));
341       continue;
342 
343     case TemplateArgument::Pack:
344       LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray(), computation));
345       continue;
346     }
347     llvm_unreachable("bad template argument kind");
348   }
349 
350   return LV;
351 }
352 
353 static LinkageInfo
354 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
355                              LVComputationKind computation) {
356   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
357 }
358 
359 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
360                         const FunctionTemplateSpecializationInfo *specInfo) {
361   // Include visibility from the template parameters and arguments
362   // only if this is not an explicit instantiation or specialization
363   // with direct explicit visibility.  (Implicit instantiations won't
364   // have a direct attribute.)
365   if (!specInfo->isExplicitInstantiationOrSpecialization())
366     return true;
367 
368   return !fn->hasAttr<VisibilityAttr>();
369 }
370 
371 /// Merge in template-related linkage and visibility for the given
372 /// function template specialization.
373 ///
374 /// We don't need a computation kind here because we can assume
375 /// LVForValue.
376 ///
377 /// \param[out] LV the computation to use for the parent
378 static void
379 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
380                 const FunctionTemplateSpecializationInfo *specInfo,
381                 LVComputationKind computation) {
382   bool considerVisibility =
383     shouldConsiderTemplateVisibility(fn, specInfo);
384 
385   // Merge information from the template parameters.
386   FunctionTemplateDecl *temp = specInfo->getTemplate();
387   LinkageInfo tempLV =
388     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
389   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
390 
391   // Merge information from the template arguments.
392   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
393   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
394   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
395 }
396 
397 /// Does the given declaration have a direct visibility attribute
398 /// that would match the given rules?
399 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
400                                          LVComputationKind computation) {
401   switch (computation) {
402   case LVForType:
403   case LVForExplicitType:
404     if (D->hasAttr<TypeVisibilityAttr>())
405       return true;
406     // fallthrough
407   case LVForValue:
408   case LVForExplicitValue:
409     if (D->hasAttr<VisibilityAttr>())
410       return true;
411     return false;
412   case LVForLinkageOnly:
413     return false;
414   }
415   llvm_unreachable("bad visibility computation kind");
416 }
417 
418 /// Should we consider visibility associated with the template
419 /// arguments and parameters of the given class template specialization?
420 static bool shouldConsiderTemplateVisibility(
421                                  const ClassTemplateSpecializationDecl *spec,
422                                  LVComputationKind computation) {
423   // Include visibility from the template parameters and arguments
424   // only if this is not an explicit instantiation or specialization
425   // with direct explicit visibility (and note that implicit
426   // instantiations won't have a direct attribute).
427   //
428   // Furthermore, we want to ignore template parameters and arguments
429   // for an explicit specialization when computing the visibility of a
430   // member thereof with explicit visibility.
431   //
432   // This is a bit complex; let's unpack it.
433   //
434   // An explicit class specialization is an independent, top-level
435   // declaration.  As such, if it or any of its members has an
436   // explicit visibility attribute, that must directly express the
437   // user's intent, and we should honor it.  The same logic applies to
438   // an explicit instantiation of a member of such a thing.
439 
440   // Fast path: if this is not an explicit instantiation or
441   // specialization, we always want to consider template-related
442   // visibility restrictions.
443   if (!spec->isExplicitInstantiationOrSpecialization())
444     return true;
445 
446   // This is the 'member thereof' check.
447   if (spec->isExplicitSpecialization() &&
448       hasExplicitVisibilityAlready(computation))
449     return false;
450 
451   return !hasDirectVisibilityAttribute(spec, computation);
452 }
453 
454 /// Merge in template-related linkage and visibility for the given
455 /// class template specialization.
456 static void mergeTemplateLV(LinkageInfo &LV,
457                             const ClassTemplateSpecializationDecl *spec,
458                             LVComputationKind computation) {
459   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
460 
461   // Merge information from the template parameters, but ignore
462   // visibility if we're only considering template arguments.
463 
464   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
465   LinkageInfo tempLV =
466     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
467   LV.mergeMaybeWithVisibility(tempLV,
468            considerVisibility && !hasExplicitVisibilityAlready(computation));
469 
470   // Merge information from the template arguments.  We ignore
471   // template-argument visibility if we've got an explicit
472   // instantiation with a visibility attribute.
473   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
474   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
475   if (considerVisibility)
476     LV.mergeVisibility(argsLV);
477   LV.mergeExternalVisibility(argsLV);
478 }
479 
480 static bool useInlineVisibilityHidden(const NamedDecl *D) {
481   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
482   const LangOptions &Opts = D->getASTContext().getLangOpts();
483   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
484     return false;
485 
486   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
487   if (!FD)
488     return false;
489 
490   TemplateSpecializationKind TSK = TSK_Undeclared;
491   if (FunctionTemplateSpecializationInfo *spec
492       = FD->getTemplateSpecializationInfo()) {
493     TSK = spec->getTemplateSpecializationKind();
494   } else if (MemberSpecializationInfo *MSI =
495              FD->getMemberSpecializationInfo()) {
496     TSK = MSI->getTemplateSpecializationKind();
497   }
498 
499   const FunctionDecl *Def = 0;
500   // InlineVisibilityHidden only applies to definitions, and
501   // isInlined() only gives meaningful answers on definitions
502   // anyway.
503   return TSK != TSK_ExplicitInstantiationDeclaration &&
504     TSK != TSK_ExplicitInstantiationDefinition &&
505     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
506 }
507 
508 template <typename T> static bool isFirstInExternCContext(T *D) {
509   const T *First = D->getFirstDecl();
510   return First->isInExternCContext();
511 }
512 
513 static bool isSingleLineLanguageLinkage(const Decl &D) {
514   if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
515     if (!SD->hasBraces())
516       return true;
517   return false;
518 }
519 
520 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
521                                               LVComputationKind computation) {
522   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
523          "Not a name having namespace scope");
524   ASTContext &Context = D->getASTContext();
525 
526   // C++ [basic.link]p3:
527   //   A name having namespace scope (3.3.6) has internal linkage if it
528   //   is the name of
529   //     - an object, reference, function or function template that is
530   //       explicitly declared static; or,
531   // (This bullet corresponds to C99 6.2.2p3.)
532   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
533     // Explicitly declared static.
534     if (Var->getStorageClass() == SC_Static)
535       return LinkageInfo::internal();
536 
537     // - a non-volatile object or reference that is explicitly declared const
538     //   or constexpr and neither explicitly declared extern nor previously
539     //   declared to have external linkage; or (there is no equivalent in C99)
540     if (Context.getLangOpts().CPlusPlus &&
541         Var->getType().isConstQualified() &&
542         !Var->getType().isVolatileQualified()) {
543       const VarDecl *PrevVar = Var->getPreviousDecl();
544       if (PrevVar)
545         return getLVForDecl(PrevVar, computation);
546 
547       if (Var->getStorageClass() != SC_Extern &&
548           Var->getStorageClass() != SC_PrivateExtern &&
549           !isSingleLineLanguageLinkage(*Var))
550         return LinkageInfo::internal();
551     }
552 
553     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
554          PrevVar = PrevVar->getPreviousDecl()) {
555       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
556           Var->getStorageClass() == SC_None)
557         return PrevVar->getLinkageAndVisibility();
558       // Explicitly declared static.
559       if (PrevVar->getStorageClass() == SC_Static)
560         return LinkageInfo::internal();
561     }
562   } else if (const FunctionDecl *Function = D->getAsFunction()) {
563     // C++ [temp]p4:
564     //   A non-member function template can have internal linkage; any
565     //   other template name shall have external linkage.
566 
567     // Explicitly declared static.
568     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
569       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
570   }
571   //   - a data member of an anonymous union.
572   assert(!isa<IndirectFieldDecl>(D) && "Didn't expect an IndirectFieldDecl!");
573   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
574 
575   if (D->isInAnonymousNamespace()) {
576     const VarDecl *Var = dyn_cast<VarDecl>(D);
577     const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
578     if ((!Var || !isFirstInExternCContext(Var)) &&
579         (!Func || !isFirstInExternCContext(Func)))
580       return LinkageInfo::uniqueExternal();
581   }
582 
583   // Set up the defaults.
584 
585   // C99 6.2.2p5:
586   //   If the declaration of an identifier for an object has file
587   //   scope and no storage-class specifier, its linkage is
588   //   external.
589   LinkageInfo LV;
590 
591   if (!hasExplicitVisibilityAlready(computation)) {
592     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
593       LV.mergeVisibility(*Vis, true);
594     } else {
595       // If we're declared in a namespace with a visibility attribute,
596       // use that namespace's visibility, and it still counts as explicit.
597       for (const DeclContext *DC = D->getDeclContext();
598            !isa<TranslationUnitDecl>(DC);
599            DC = DC->getParent()) {
600         const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
601         if (!ND) continue;
602         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
603           LV.mergeVisibility(*Vis, true);
604           break;
605         }
606       }
607     }
608 
609     // Add in global settings if the above didn't give us direct visibility.
610     if (!LV.isVisibilityExplicit()) {
611       // Use global type/value visibility as appropriate.
612       Visibility globalVisibility;
613       if (computation == LVForValue) {
614         globalVisibility = Context.getLangOpts().getValueVisibilityMode();
615       } else {
616         assert(computation == LVForType);
617         globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
618       }
619       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
620 
621       // If we're paying attention to global visibility, apply
622       // -finline-visibility-hidden if this is an inline method.
623       if (useInlineVisibilityHidden(D))
624         LV.mergeVisibility(HiddenVisibility, true);
625     }
626   }
627 
628   // C++ [basic.link]p4:
629 
630   //   A name having namespace scope has external linkage if it is the
631   //   name of
632   //
633   //     - an object or reference, unless it has internal linkage; or
634   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
635     // GCC applies the following optimization to variables and static
636     // data members, but not to functions:
637     //
638     // Modify the variable's LV by the LV of its type unless this is
639     // C or extern "C".  This follows from [basic.link]p9:
640     //   A type without linkage shall not be used as the type of a
641     //   variable or function with external linkage unless
642     //    - the entity has C language linkage, or
643     //    - the entity is declared within an unnamed namespace, or
644     //    - the entity is not used or is defined in the same
645     //      translation unit.
646     // and [basic.link]p10:
647     //   ...the types specified by all declarations referring to a
648     //   given variable or function shall be identical...
649     // C does not have an equivalent rule.
650     //
651     // Ignore this if we've got an explicit attribute;  the user
652     // probably knows what they're doing.
653     //
654     // Note that we don't want to make the variable non-external
655     // because of this, but unique-external linkage suits us.
656     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
657       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
658       if (TypeLV.getLinkage() != ExternalLinkage)
659         return LinkageInfo::uniqueExternal();
660       if (!LV.isVisibilityExplicit())
661         LV.mergeVisibility(TypeLV);
662     }
663 
664     if (Var->getStorageClass() == SC_PrivateExtern)
665       LV.mergeVisibility(HiddenVisibility, true);
666 
667     // Note that Sema::MergeVarDecl already takes care of implementing
668     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
669     // to do it here.
670 
671   //     - a function, unless it has internal linkage; or
672   } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
673     // In theory, we can modify the function's LV by the LV of its
674     // type unless it has C linkage (see comment above about variables
675     // for justification).  In practice, GCC doesn't do this, so it's
676     // just too painful to make work.
677 
678     if (Function->getStorageClass() == SC_PrivateExtern)
679       LV.mergeVisibility(HiddenVisibility, true);
680 
681     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
682     // merging storage classes and visibility attributes, so we don't have to
683     // look at previous decls in here.
684 
685     // In C++, then if the type of the function uses a type with
686     // unique-external linkage, it's not legally usable from outside
687     // this translation unit.  However, we should use the C linkage
688     // rules instead for extern "C" declarations.
689     if (Context.getLangOpts().CPlusPlus &&
690         !Function->isInExternCContext()) {
691       // Only look at the type-as-written. If this function has an auto-deduced
692       // return type, we can't compute the linkage of that type because it could
693       // require looking at the linkage of this function, and we don't need this
694       // for correctness because the type is not part of the function's
695       // signature.
696       // FIXME: This is a hack. We should be able to solve this circularity and
697       // the one in getLVForClassMember for Functions some other way.
698       QualType TypeAsWritten = Function->getType();
699       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
700         TypeAsWritten = TSI->getType();
701       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
702         return LinkageInfo::uniqueExternal();
703     }
704 
705     // Consider LV from the template and the template arguments.
706     // We're at file scope, so we do not need to worry about nested
707     // specializations.
708     if (FunctionTemplateSpecializationInfo *specInfo
709                                = Function->getTemplateSpecializationInfo()) {
710       mergeTemplateLV(LV, Function, specInfo, computation);
711     }
712 
713   //     - a named class (Clause 9), or an unnamed class defined in a
714   //       typedef declaration in which the class has the typedef name
715   //       for linkage purposes (7.1.3); or
716   //     - a named enumeration (7.2), or an unnamed enumeration
717   //       defined in a typedef declaration in which the enumeration
718   //       has the typedef name for linkage purposes (7.1.3); or
719   } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
720     // Unnamed tags have no linkage.
721     if (!Tag->hasNameForLinkage())
722       return LinkageInfo::none();
723 
724     // If this is a class template specialization, consider the
725     // linkage of the template and template arguments.  We're at file
726     // scope, so we do not need to worry about nested specializations.
727     if (const ClassTemplateSpecializationDecl *spec
728           = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
729       mergeTemplateLV(LV, spec, computation);
730     }
731 
732   //     - an enumerator belonging to an enumeration with external linkage;
733   } else if (isa<EnumConstantDecl>(D)) {
734     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
735                                       computation);
736     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
737       return LinkageInfo::none();
738     LV.merge(EnumLV);
739 
740   //     - a template, unless it is a function template that has
741   //       internal linkage (Clause 14);
742   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
743     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
744     LinkageInfo tempLV =
745       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
746     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
747 
748   //     - a namespace (7.3), unless it is declared within an unnamed
749   //       namespace.
750   } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
751     return LV;
752 
753   // By extension, we assign external linkage to Objective-C
754   // interfaces.
755   } else if (isa<ObjCInterfaceDecl>(D)) {
756     // fallout
757 
758   // Everything not covered here has no linkage.
759   } else {
760     return LinkageInfo::none();
761   }
762 
763   // If we ended up with non-external linkage, visibility should
764   // always be default.
765   if (LV.getLinkage() != ExternalLinkage)
766     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
767 
768   return LV;
769 }
770 
771 static LinkageInfo getLVForClassMember(const NamedDecl *D,
772                                        LVComputationKind computation) {
773   // Only certain class members have linkage.  Note that fields don't
774   // really have linkage, but it's convenient to say they do for the
775   // purposes of calculating linkage of pointer-to-data-member
776   // template arguments.
777   //
778   // Templates also don't officially have linkage, but since we ignore
779   // the C++ standard and look at template arguments when determining
780   // linkage and visibility of a template specialization, we might hit
781   // a template template argument that way. If we do, we need to
782   // consider its linkage.
783   if (!(isa<CXXMethodDecl>(D) ||
784         isa<VarDecl>(D) ||
785         isa<FieldDecl>(D) ||
786         isa<IndirectFieldDecl>(D) ||
787         isa<TagDecl>(D) ||
788         isa<TemplateDecl>(D)))
789     return LinkageInfo::none();
790 
791   LinkageInfo LV;
792 
793   // If we have an explicit visibility attribute, merge that in.
794   if (!hasExplicitVisibilityAlready(computation)) {
795     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
796       LV.mergeVisibility(*Vis, true);
797     // If we're paying attention to global visibility, apply
798     // -finline-visibility-hidden if this is an inline method.
799     //
800     // Note that we do this before merging information about
801     // the class visibility.
802     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
803       LV.mergeVisibility(HiddenVisibility, true);
804   }
805 
806   // If this class member has an explicit visibility attribute, the only
807   // thing that can change its visibility is the template arguments, so
808   // only look for them when processing the class.
809   LVComputationKind classComputation = computation;
810   if (LV.isVisibilityExplicit())
811     classComputation = withExplicitVisibilityAlready(computation);
812 
813   LinkageInfo classLV =
814     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
815   // If the class already has unique-external linkage, we can't improve.
816   if (classLV.getLinkage() == UniqueExternalLinkage)
817     return LinkageInfo::uniqueExternal();
818 
819   if (!isExternallyVisible(classLV.getLinkage()))
820     return LinkageInfo::none();
821 
822 
823   // Otherwise, don't merge in classLV yet, because in certain cases
824   // we need to completely ignore the visibility from it.
825 
826   // Specifically, if this decl exists and has an explicit attribute.
827   const NamedDecl *explicitSpecSuppressor = 0;
828 
829   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
830     // If the type of the function uses a type with unique-external
831     // linkage, it's not legally usable from outside this translation unit.
832     // But only look at the type-as-written. If this function has an auto-deduced
833     // return type, we can't compute the linkage of that type because it could
834     // require looking at the linkage of this function, and we don't need this
835     // for correctness because the type is not part of the function's
836     // signature.
837     // FIXME: This is a hack. We should be able to solve this circularity and the
838     // one in getLVForNamespaceScopeDecl for Functions some other way.
839     {
840       QualType TypeAsWritten = MD->getType();
841       if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
842         TypeAsWritten = TSI->getType();
843       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
844         return LinkageInfo::uniqueExternal();
845     }
846     // If this is a method template specialization, use the linkage for
847     // the template parameters and arguments.
848     if (FunctionTemplateSpecializationInfo *spec
849            = MD->getTemplateSpecializationInfo()) {
850       mergeTemplateLV(LV, MD, spec, computation);
851       if (spec->isExplicitSpecialization()) {
852         explicitSpecSuppressor = MD;
853       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
854         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
855       }
856     } else if (isExplicitMemberSpecialization(MD)) {
857       explicitSpecSuppressor = MD;
858     }
859 
860   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
861     if (const ClassTemplateSpecializationDecl *spec
862         = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
863       mergeTemplateLV(LV, spec, computation);
864       if (spec->isExplicitSpecialization()) {
865         explicitSpecSuppressor = spec;
866       } else {
867         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
868         if (isExplicitMemberSpecialization(temp)) {
869           explicitSpecSuppressor = temp->getTemplatedDecl();
870         }
871       }
872     } else if (isExplicitMemberSpecialization(RD)) {
873       explicitSpecSuppressor = RD;
874     }
875 
876   // Static data members.
877   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
878     // Modify the variable's linkage by its type, but ignore the
879     // type's visibility unless it's a definition.
880     LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
881     if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
882       LV.mergeVisibility(typeLV);
883     LV.mergeExternalVisibility(typeLV);
884 
885     if (isExplicitMemberSpecialization(VD)) {
886       explicitSpecSuppressor = VD;
887     }
888 
889   // Template members.
890   } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
891     bool considerVisibility =
892       (!LV.isVisibilityExplicit() &&
893        !classLV.isVisibilityExplicit() &&
894        !hasExplicitVisibilityAlready(computation));
895     LinkageInfo tempLV =
896       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
897     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
898 
899     if (const RedeclarableTemplateDecl *redeclTemp =
900           dyn_cast<RedeclarableTemplateDecl>(temp)) {
901       if (isExplicitMemberSpecialization(redeclTemp)) {
902         explicitSpecSuppressor = temp->getTemplatedDecl();
903       }
904     }
905   }
906 
907   // We should never be looking for an attribute directly on a template.
908   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
909 
910   // If this member is an explicit member specialization, and it has
911   // an explicit attribute, ignore visibility from the parent.
912   bool considerClassVisibility = true;
913   if (explicitSpecSuppressor &&
914       // optimization: hasDVA() is true only with explicit visibility.
915       LV.isVisibilityExplicit() &&
916       classLV.getVisibility() != DefaultVisibility &&
917       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
918     considerClassVisibility = false;
919   }
920 
921   // Finally, merge in information from the class.
922   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
923   return LV;
924 }
925 
926 void NamedDecl::anchor() { }
927 
928 static LinkageInfo computeLVForDecl(const NamedDecl *D,
929                                     LVComputationKind computation);
930 
931 bool NamedDecl::isLinkageValid() const {
932   if (!hasCachedLinkage())
933     return true;
934 
935   return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
936          getCachedLinkage();
937 }
938 
939 Linkage NamedDecl::getLinkageInternal() const {
940   // We don't care about visibility here, so ask for the cheapest
941   // possible visibility analysis.
942   return getLVForDecl(this, LVForLinkageOnly).getLinkage();
943 }
944 
945 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
946   LVComputationKind computation =
947     (usesTypeVisibility(this) ? LVForType : LVForValue);
948   return getLVForDecl(this, computation);
949 }
950 
951 static Optional<Visibility>
952 getExplicitVisibilityAux(const NamedDecl *ND,
953                          NamedDecl::ExplicitVisibilityKind kind,
954                          bool IsMostRecent) {
955   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
956 
957   // Check the declaration itself first.
958   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
959     return V;
960 
961   // If this is a member class of a specialization of a class template
962   // and the corresponding decl has explicit visibility, use that.
963   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND)) {
964     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
965     if (InstantiatedFrom)
966       return getVisibilityOf(InstantiatedFrom, kind);
967   }
968 
969   // If there wasn't explicit visibility there, and this is a
970   // specialization of a class template, check for visibility
971   // on the pattern.
972   if (const ClassTemplateSpecializationDecl *spec
973         = dyn_cast<ClassTemplateSpecializationDecl>(ND))
974     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
975                            kind);
976 
977   // Use the most recent declaration.
978   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
979     const NamedDecl *MostRecent = ND->getMostRecentDecl();
980     if (MostRecent != ND)
981       return getExplicitVisibilityAux(MostRecent, kind, true);
982   }
983 
984   if (const VarDecl *Var = dyn_cast<VarDecl>(ND)) {
985     if (Var->isStaticDataMember()) {
986       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
987       if (InstantiatedFrom)
988         return getVisibilityOf(InstantiatedFrom, kind);
989     }
990 
991     return None;
992   }
993   // Also handle function template specializations.
994   if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND)) {
995     // If the function is a specialization of a template with an
996     // explicit visibility attribute, use that.
997     if (FunctionTemplateSpecializationInfo *templateInfo
998           = fn->getTemplateSpecializationInfo())
999       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1000                              kind);
1001 
1002     // If the function is a member of a specialization of a class template
1003     // and the corresponding decl has explicit visibility, use that.
1004     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1005     if (InstantiatedFrom)
1006       return getVisibilityOf(InstantiatedFrom, kind);
1007 
1008     return None;
1009   }
1010 
1011   // The visibility of a template is stored in the templated decl.
1012   if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(ND))
1013     return getVisibilityOf(TD->getTemplatedDecl(), kind);
1014 
1015   return None;
1016 }
1017 
1018 Optional<Visibility>
1019 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1020   return getExplicitVisibilityAux(this, kind, false);
1021 }
1022 
1023 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1024                                    LVComputationKind computation) {
1025   // This lambda has its linkage/visibility determined by its owner.
1026   if (ContextDecl) {
1027     if (isa<ParmVarDecl>(ContextDecl))
1028       DC = ContextDecl->getDeclContext()->getRedeclContext();
1029     else
1030       return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1031   }
1032 
1033   if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
1034     return getLVForDecl(ND, computation);
1035 
1036   return LinkageInfo::external();
1037 }
1038 
1039 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1040                                      LVComputationKind computation) {
1041   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1042     if (Function->isInAnonymousNamespace() &&
1043         !Function->isInExternCContext())
1044       return LinkageInfo::uniqueExternal();
1045 
1046     // This is a "void f();" which got merged with a file static.
1047     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1048       return LinkageInfo::internal();
1049 
1050     LinkageInfo LV;
1051     if (!hasExplicitVisibilityAlready(computation)) {
1052       if (Optional<Visibility> Vis =
1053               getExplicitVisibility(Function, computation))
1054         LV.mergeVisibility(*Vis, true);
1055     }
1056 
1057     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1058     // merging storage classes and visibility attributes, so we don't have to
1059     // look at previous decls in here.
1060 
1061     return LV;
1062   }
1063 
1064   if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1065     if (Var->hasExternalStorage()) {
1066       if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1067         return LinkageInfo::uniqueExternal();
1068 
1069       LinkageInfo LV;
1070       if (Var->getStorageClass() == SC_PrivateExtern)
1071         LV.mergeVisibility(HiddenVisibility, true);
1072       else if (!hasExplicitVisibilityAlready(computation)) {
1073         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1074           LV.mergeVisibility(*Vis, true);
1075       }
1076 
1077       if (const VarDecl *Prev = Var->getPreviousDecl()) {
1078         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1079         if (PrevLV.getLinkage())
1080           LV.setLinkage(PrevLV.getLinkage());
1081         LV.mergeVisibility(PrevLV);
1082       }
1083 
1084       return LV;
1085     }
1086 
1087     if (!Var->isStaticLocal())
1088       return LinkageInfo::none();
1089   }
1090 
1091   ASTContext &Context = D->getASTContext();
1092   if (!Context.getLangOpts().CPlusPlus)
1093     return LinkageInfo::none();
1094 
1095   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1096   if (!OuterD)
1097     return LinkageInfo::none();
1098 
1099   LinkageInfo LV;
1100   if (const BlockDecl *BD = dyn_cast<BlockDecl>(OuterD)) {
1101     if (!BD->getBlockManglingNumber())
1102       return LinkageInfo::none();
1103 
1104     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1105                          BD->getBlockManglingContextDecl(), computation);
1106   } else {
1107     const FunctionDecl *FD = cast<FunctionDecl>(OuterD);
1108     if (!FD->isInlined() &&
1109         FD->getTemplateSpecializationKind() == TSK_Undeclared)
1110       return LinkageInfo::none();
1111 
1112     LV = getLVForDecl(FD, computation);
1113   }
1114   if (!isExternallyVisible(LV.getLinkage()))
1115     return LinkageInfo::none();
1116   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1117                      LV.isVisibilityExplicit());
1118 }
1119 
1120 static inline const CXXRecordDecl*
1121 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1122   const CXXRecordDecl *Ret = Record;
1123   while (Record && Record->isLambda()) {
1124     Ret = Record;
1125     if (!Record->getParent()) break;
1126     // Get the Containing Class of this Lambda Class
1127     Record = dyn_cast_or_null<CXXRecordDecl>(
1128       Record->getParent()->getParent());
1129   }
1130   return Ret;
1131 }
1132 
1133 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1134                                     LVComputationKind computation) {
1135   // Objective-C: treat all Objective-C declarations as having external
1136   // linkage.
1137   switch (D->getKind()) {
1138     default:
1139       break;
1140     case Decl::ParmVar:
1141       return LinkageInfo::none();
1142     case Decl::TemplateTemplateParm: // count these as external
1143     case Decl::NonTypeTemplateParm:
1144     case Decl::ObjCAtDefsField:
1145     case Decl::ObjCCategory:
1146     case Decl::ObjCCategoryImpl:
1147     case Decl::ObjCCompatibleAlias:
1148     case Decl::ObjCImplementation:
1149     case Decl::ObjCMethod:
1150     case Decl::ObjCProperty:
1151     case Decl::ObjCPropertyImpl:
1152     case Decl::ObjCProtocol:
1153       return LinkageInfo::external();
1154 
1155     case Decl::CXXRecord: {
1156       const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
1157       if (Record->isLambda()) {
1158         if (!Record->getLambdaManglingNumber()) {
1159           // This lambda has no mangling number, so it's internal.
1160           return LinkageInfo::internal();
1161         }
1162 
1163         // This lambda has its linkage/visibility determined:
1164         //  - either by the outermost lambda if that lambda has no mangling
1165         //    number.
1166         //  - or by the parent of the outer most lambda
1167         // This prevents infinite recursion in settings such as nested lambdas
1168         // used in NSDMI's, for e.g.
1169         //  struct L {
1170         //    int t{};
1171         //    int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1172         //  };
1173         const CXXRecordDecl *OuterMostLambda =
1174             getOutermostEnclosingLambda(Record);
1175         if (!OuterMostLambda->getLambdaManglingNumber())
1176           return LinkageInfo::internal();
1177 
1178         return getLVForClosure(
1179                   OuterMostLambda->getDeclContext()->getRedeclContext(),
1180                   OuterMostLambda->getLambdaContextDecl(), computation);
1181       }
1182 
1183       break;
1184     }
1185   }
1186 
1187   // Handle linkage for namespace-scope names.
1188   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1189     return getLVForNamespaceScopeDecl(D, computation);
1190 
1191   // C++ [basic.link]p5:
1192   //   In addition, a member function, static data member, a named
1193   //   class or enumeration of class scope, or an unnamed class or
1194   //   enumeration defined in a class-scope typedef declaration such
1195   //   that the class or enumeration has the typedef name for linkage
1196   //   purposes (7.1.3), has external linkage if the name of the class
1197   //   has external linkage.
1198   if (D->getDeclContext()->isRecord())
1199     return getLVForClassMember(D, computation);
1200 
1201   // C++ [basic.link]p6:
1202   //   The name of a function declared in block scope and the name of
1203   //   an object declared by a block scope extern declaration have
1204   //   linkage. If there is a visible declaration of an entity with
1205   //   linkage having the same name and type, ignoring entities
1206   //   declared outside the innermost enclosing namespace scope, the
1207   //   block scope declaration declares that same entity and receives
1208   //   the linkage of the previous declaration. If there is more than
1209   //   one such matching entity, the program is ill-formed. Otherwise,
1210   //   if no matching entity is found, the block scope entity receives
1211   //   external linkage.
1212   if (D->getDeclContext()->isFunctionOrMethod())
1213     return getLVForLocalDecl(D, computation);
1214 
1215   // C++ [basic.link]p6:
1216   //   Names not covered by these rules have no linkage.
1217   return LinkageInfo::none();
1218 }
1219 
1220 namespace clang {
1221 class LinkageComputer {
1222 public:
1223   static LinkageInfo getLVForDecl(const NamedDecl *D,
1224                                   LVComputationKind computation) {
1225     if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1226       return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1227 
1228     LinkageInfo LV = computeLVForDecl(D, computation);
1229     if (D->hasCachedLinkage())
1230       assert(D->getCachedLinkage() == LV.getLinkage());
1231 
1232     D->setCachedLinkage(LV.getLinkage());
1233 
1234 #ifndef NDEBUG
1235     // In C (because of gnu inline) and in c++ with microsoft extensions an
1236     // static can follow an extern, so we can have two decls with different
1237     // linkages.
1238     const LangOptions &Opts = D->getASTContext().getLangOpts();
1239     if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1240       return LV;
1241 
1242     // We have just computed the linkage for this decl. By induction we know
1243     // that all other computed linkages match, check that the one we just
1244     // computed also does.
1245     NamedDecl *Old = NULL;
1246     for (auto I : D->redecls()) {
1247       NamedDecl *T = cast<NamedDecl>(I);
1248       if (T == D)
1249         continue;
1250       if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1251         Old = T;
1252         break;
1253       }
1254     }
1255     assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1256 #endif
1257 
1258     return LV;
1259   }
1260 };
1261 }
1262 
1263 static LinkageInfo getLVForDecl(const NamedDecl *D,
1264                                 LVComputationKind computation) {
1265   return clang::LinkageComputer::getLVForDecl(D, computation);
1266 }
1267 
1268 std::string NamedDecl::getQualifiedNameAsString() const {
1269   std::string QualName;
1270   llvm::raw_string_ostream OS(QualName);
1271   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1272   return OS.str();
1273 }
1274 
1275 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1276   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1277 }
1278 
1279 void NamedDecl::printQualifiedName(raw_ostream &OS,
1280                                    const PrintingPolicy &P) const {
1281   const DeclContext *Ctx = getDeclContext();
1282 
1283   if (Ctx->isFunctionOrMethod()) {
1284     printName(OS);
1285     return;
1286   }
1287 
1288   typedef SmallVector<const DeclContext *, 8> ContextsTy;
1289   ContextsTy Contexts;
1290 
1291   // Collect contexts.
1292   while (Ctx && isa<NamedDecl>(Ctx)) {
1293     Contexts.push_back(Ctx);
1294     Ctx = Ctx->getParent();
1295   }
1296 
1297   for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
1298        I != E; ++I) {
1299     if (const ClassTemplateSpecializationDecl *Spec
1300           = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
1301       OS << Spec->getName();
1302       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1303       TemplateSpecializationType::PrintTemplateArgumentList(OS,
1304                                                             TemplateArgs.data(),
1305                                                             TemplateArgs.size(),
1306                                                             P);
1307     } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
1308       if (ND->isAnonymousNamespace())
1309         OS << "<anonymous namespace>";
1310       else
1311         OS << *ND;
1312     } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
1313       if (!RD->getIdentifier())
1314         OS << "<anonymous " << RD->getKindName() << '>';
1315       else
1316         OS << *RD;
1317     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1318       const FunctionProtoType *FT = 0;
1319       if (FD->hasWrittenPrototype())
1320         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1321 
1322       OS << *FD << '(';
1323       if (FT) {
1324         unsigned NumParams = FD->getNumParams();
1325         for (unsigned i = 0; i < NumParams; ++i) {
1326           if (i)
1327             OS << ", ";
1328           OS << FD->getParamDecl(i)->getType().stream(P);
1329         }
1330 
1331         if (FT->isVariadic()) {
1332           if (NumParams > 0)
1333             OS << ", ";
1334           OS << "...";
1335         }
1336       }
1337       OS << ')';
1338     } else {
1339       OS << *cast<NamedDecl>(*I);
1340     }
1341     OS << "::";
1342   }
1343 
1344   if (getDeclName())
1345     OS << *this;
1346   else
1347     OS << "<anonymous>";
1348 }
1349 
1350 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1351                                      const PrintingPolicy &Policy,
1352                                      bool Qualified) const {
1353   if (Qualified)
1354     printQualifiedName(OS, Policy);
1355   else
1356     printName(OS);
1357 }
1358 
1359 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
1360   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1361 
1362   // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1363   // We want to keep it, unless it nominates same namespace.
1364   if (getKind() == Decl::UsingDirective) {
1365     return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
1366              ->getOriginalNamespace() ==
1367            cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1368              ->getOriginalNamespace();
1369   }
1370 
1371   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
1372     // For function declarations, we keep track of redeclarations.
1373     return FD->getPreviousDecl() == OldD;
1374 
1375   // For function templates, the underlying function declarations are linked.
1376   if (const FunctionTemplateDecl *FunctionTemplate
1377         = dyn_cast<FunctionTemplateDecl>(this))
1378     if (const FunctionTemplateDecl *OldFunctionTemplate
1379           = dyn_cast<FunctionTemplateDecl>(OldD))
1380       return FunctionTemplate->getTemplatedDecl()
1381                ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
1382 
1383   // For method declarations, we keep track of redeclarations.
1384   if (isa<ObjCMethodDecl>(this))
1385     return false;
1386 
1387   if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
1388     return true;
1389 
1390   if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
1391     return cast<UsingShadowDecl>(this)->getTargetDecl() ==
1392            cast<UsingShadowDecl>(OldD)->getTargetDecl();
1393 
1394   if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
1395     ASTContext &Context = getASTContext();
1396     return Context.getCanonicalNestedNameSpecifier(
1397                                      cast<UsingDecl>(this)->getQualifier()) ==
1398            Context.getCanonicalNestedNameSpecifier(
1399                                         cast<UsingDecl>(OldD)->getQualifier());
1400   }
1401 
1402   if (isa<UnresolvedUsingValueDecl>(this) &&
1403       isa<UnresolvedUsingValueDecl>(OldD)) {
1404     ASTContext &Context = getASTContext();
1405     return Context.getCanonicalNestedNameSpecifier(
1406                       cast<UnresolvedUsingValueDecl>(this)->getQualifier()) ==
1407            Context.getCanonicalNestedNameSpecifier(
1408                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1409   }
1410 
1411   // A typedef of an Objective-C class type can replace an Objective-C class
1412   // declaration or definition, and vice versa.
1413   if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
1414       (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
1415     return true;
1416 
1417   // For non-function declarations, if the declarations are of the
1418   // same kind then this must be a redeclaration, or semantic analysis
1419   // would not have given us the new declaration.
1420   return this->getKind() == OldD->getKind();
1421 }
1422 
1423 bool NamedDecl::hasLinkage() const {
1424   return getFormalLinkage() != NoLinkage;
1425 }
1426 
1427 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1428   NamedDecl *ND = this;
1429   while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
1430     ND = UD->getTargetDecl();
1431 
1432   if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1433     return AD->getClassInterface();
1434 
1435   return ND;
1436 }
1437 
1438 bool NamedDecl::isCXXInstanceMember() const {
1439   if (!isCXXClassMember())
1440     return false;
1441 
1442   const NamedDecl *D = this;
1443   if (isa<UsingShadowDecl>(D))
1444     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1445 
1446   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1447     return true;
1448   if (const CXXMethodDecl *MD =
1449           dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1450     return MD->isInstance();
1451   return false;
1452 }
1453 
1454 //===----------------------------------------------------------------------===//
1455 // DeclaratorDecl Implementation
1456 //===----------------------------------------------------------------------===//
1457 
1458 template <typename DeclT>
1459 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1460   if (decl->getNumTemplateParameterLists() > 0)
1461     return decl->getTemplateParameterList(0)->getTemplateLoc();
1462   else
1463     return decl->getInnerLocStart();
1464 }
1465 
1466 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1467   TypeSourceInfo *TSI = getTypeSourceInfo();
1468   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1469   return SourceLocation();
1470 }
1471 
1472 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1473   if (QualifierLoc) {
1474     // Make sure the extended decl info is allocated.
1475     if (!hasExtInfo()) {
1476       // Save (non-extended) type source info pointer.
1477       TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1478       // Allocate external info struct.
1479       DeclInfo = new (getASTContext()) ExtInfo;
1480       // Restore savedTInfo into (extended) decl info.
1481       getExtInfo()->TInfo = savedTInfo;
1482     }
1483     // Set qualifier info.
1484     getExtInfo()->QualifierLoc = QualifierLoc;
1485   } else {
1486     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1487     if (hasExtInfo()) {
1488       if (getExtInfo()->NumTemplParamLists == 0) {
1489         // Save type source info pointer.
1490         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1491         // Deallocate the extended decl info.
1492         getASTContext().Deallocate(getExtInfo());
1493         // Restore savedTInfo into (non-extended) decl info.
1494         DeclInfo = savedTInfo;
1495       }
1496       else
1497         getExtInfo()->QualifierLoc = QualifierLoc;
1498     }
1499   }
1500 }
1501 
1502 void
1503 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1504                                               unsigned NumTPLists,
1505                                               TemplateParameterList **TPLists) {
1506   assert(NumTPLists > 0);
1507   // Make sure the extended decl info is allocated.
1508   if (!hasExtInfo()) {
1509     // Save (non-extended) type source info pointer.
1510     TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1511     // Allocate external info struct.
1512     DeclInfo = new (getASTContext()) ExtInfo;
1513     // Restore savedTInfo into (extended) decl info.
1514     getExtInfo()->TInfo = savedTInfo;
1515   }
1516   // Set the template parameter lists info.
1517   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1518 }
1519 
1520 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1521   return getTemplateOrInnerLocStart(this);
1522 }
1523 
1524 namespace {
1525 
1526 // Helper function: returns true if QT is or contains a type
1527 // having a postfix component.
1528 bool typeIsPostfix(clang::QualType QT) {
1529   while (true) {
1530     const Type* T = QT.getTypePtr();
1531     switch (T->getTypeClass()) {
1532     default:
1533       return false;
1534     case Type::Pointer:
1535       QT = cast<PointerType>(T)->getPointeeType();
1536       break;
1537     case Type::BlockPointer:
1538       QT = cast<BlockPointerType>(T)->getPointeeType();
1539       break;
1540     case Type::MemberPointer:
1541       QT = cast<MemberPointerType>(T)->getPointeeType();
1542       break;
1543     case Type::LValueReference:
1544     case Type::RValueReference:
1545       QT = cast<ReferenceType>(T)->getPointeeType();
1546       break;
1547     case Type::PackExpansion:
1548       QT = cast<PackExpansionType>(T)->getPattern();
1549       break;
1550     case Type::Paren:
1551     case Type::ConstantArray:
1552     case Type::DependentSizedArray:
1553     case Type::IncompleteArray:
1554     case Type::VariableArray:
1555     case Type::FunctionProto:
1556     case Type::FunctionNoProto:
1557       return true;
1558     }
1559   }
1560 }
1561 
1562 } // namespace
1563 
1564 SourceRange DeclaratorDecl::getSourceRange() const {
1565   SourceLocation RangeEnd = getLocation();
1566   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1567     // If the declaration has no name or the type extends past the name take the
1568     // end location of the type.
1569     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1570       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1571   }
1572   return SourceRange(getOuterLocStart(), RangeEnd);
1573 }
1574 
1575 void
1576 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1577                                              unsigned NumTPLists,
1578                                              TemplateParameterList **TPLists) {
1579   assert((NumTPLists == 0 || TPLists != 0) &&
1580          "Empty array of template parameters with positive size!");
1581 
1582   // Free previous template parameters (if any).
1583   if (NumTemplParamLists > 0) {
1584     Context.Deallocate(TemplParamLists);
1585     TemplParamLists = 0;
1586     NumTemplParamLists = 0;
1587   }
1588   // Set info on matched template parameter lists (if any).
1589   if (NumTPLists > 0) {
1590     TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1591     NumTemplParamLists = NumTPLists;
1592     for (unsigned i = NumTPLists; i-- > 0; )
1593       TemplParamLists[i] = TPLists[i];
1594   }
1595 }
1596 
1597 //===----------------------------------------------------------------------===//
1598 // VarDecl Implementation
1599 //===----------------------------------------------------------------------===//
1600 
1601 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1602   switch (SC) {
1603   case SC_None:                 break;
1604   case SC_Auto:                 return "auto";
1605   case SC_Extern:               return "extern";
1606   case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1607   case SC_PrivateExtern:        return "__private_extern__";
1608   case SC_Register:             return "register";
1609   case SC_Static:               return "static";
1610   }
1611 
1612   llvm_unreachable("Invalid storage class");
1613 }
1614 
1615 VarDecl::VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
1616                  SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
1617                  TypeSourceInfo *TInfo, StorageClass SC)
1618     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() {
1619   assert(sizeof(VarDeclBitfields) <= sizeof(unsigned));
1620   assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned));
1621   AllBits = 0;
1622   VarDeclBits.SClass = SC;
1623   // Everything else is implicitly initialized to false.
1624 }
1625 
1626 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1627                          SourceLocation StartL, SourceLocation IdL,
1628                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1629                          StorageClass S) {
1630   return new (C, DC) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S);
1631 }
1632 
1633 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1634   return new (C, ID) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1635                              QualType(), 0, SC_None);
1636 }
1637 
1638 void VarDecl::setStorageClass(StorageClass SC) {
1639   assert(isLegalForVariable(SC));
1640   VarDeclBits.SClass = SC;
1641 }
1642 
1643 SourceRange VarDecl::getSourceRange() const {
1644   if (const Expr *Init = getInit()) {
1645     SourceLocation InitEnd = Init->getLocEnd();
1646     // If Init is implicit, ignore its source range and fallback on
1647     // DeclaratorDecl::getSourceRange() to handle postfix elements.
1648     if (InitEnd.isValid() && InitEnd != getLocation())
1649       return SourceRange(getOuterLocStart(), InitEnd);
1650   }
1651   return DeclaratorDecl::getSourceRange();
1652 }
1653 
1654 template<typename T>
1655 static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
1656   // C++ [dcl.link]p1: All function types, function names with external linkage,
1657   // and variable names with external linkage have a language linkage.
1658   if (!D.hasExternalFormalLinkage())
1659     return NoLanguageLinkage;
1660 
1661   // Language linkage is a C++ concept, but saying that everything else in C has
1662   // C language linkage fits the implementation nicely.
1663   ASTContext &Context = D.getASTContext();
1664   if (!Context.getLangOpts().CPlusPlus)
1665     return CLanguageLinkage;
1666 
1667   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1668   // language linkage of the names of class members and the function type of
1669   // class member functions.
1670   const DeclContext *DC = D.getDeclContext();
1671   if (DC->isRecord())
1672     return CXXLanguageLinkage;
1673 
1674   // If the first decl is in an extern "C" context, any other redeclaration
1675   // will have C language linkage. If the first one is not in an extern "C"
1676   // context, we would have reported an error for any other decl being in one.
1677   if (isFirstInExternCContext(&D))
1678     return CLanguageLinkage;
1679   return CXXLanguageLinkage;
1680 }
1681 
1682 template<typename T>
1683 static bool isExternCTemplate(const T &D) {
1684   // Since the context is ignored for class members, they can only have C++
1685   // language linkage or no language linkage.
1686   const DeclContext *DC = D.getDeclContext();
1687   if (DC->isRecord()) {
1688     assert(D.getASTContext().getLangOpts().CPlusPlus);
1689     return false;
1690   }
1691 
1692   return D.getLanguageLinkage() == CLanguageLinkage;
1693 }
1694 
1695 LanguageLinkage VarDecl::getLanguageLinkage() const {
1696   return getLanguageLinkageTemplate(*this);
1697 }
1698 
1699 bool VarDecl::isExternC() const {
1700   return isExternCTemplate(*this);
1701 }
1702 
1703 bool VarDecl::isInExternCContext() const {
1704   return getLexicalDeclContext()->isExternCContext();
1705 }
1706 
1707 bool VarDecl::isInExternCXXContext() const {
1708   return getLexicalDeclContext()->isExternCXXContext();
1709 }
1710 
1711 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1712 
1713 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1714   ASTContext &C) const
1715 {
1716   // C++ [basic.def]p2:
1717   //   A declaration is a definition unless [...] it contains the 'extern'
1718   //   specifier or a linkage-specification and neither an initializer [...],
1719   //   it declares a static data member in a class declaration [...].
1720   // C++1y [temp.expl.spec]p15:
1721   //   An explicit specialization of a static data member or an explicit
1722   //   specialization of a static data member template is a definition if the
1723   //   declaration includes an initializer; otherwise, it is a declaration.
1724   //
1725   // FIXME: How do you declare (but not define) a partial specialization of
1726   // a static data member template outside the containing class?
1727   if (isStaticDataMember()) {
1728     if (isOutOfLine() &&
1729         (hasInit() ||
1730          // If the first declaration is out-of-line, this may be an
1731          // instantiation of an out-of-line partial specialization of a variable
1732          // template for which we have not yet instantiated the initializer.
1733          (getFirstDecl()->isOutOfLine()
1734               ? getTemplateSpecializationKind() == TSK_Undeclared
1735               : getTemplateSpecializationKind() !=
1736                     TSK_ExplicitSpecialization) ||
1737          isa<VarTemplatePartialSpecializationDecl>(this)))
1738       return Definition;
1739     else
1740       return DeclarationOnly;
1741   }
1742   // C99 6.7p5:
1743   //   A definition of an identifier is a declaration for that identifier that
1744   //   [...] causes storage to be reserved for that object.
1745   // Note: that applies for all non-file-scope objects.
1746   // C99 6.9.2p1:
1747   //   If the declaration of an identifier for an object has file scope and an
1748   //   initializer, the declaration is an external definition for the identifier
1749   if (hasInit())
1750     return Definition;
1751 
1752   if (hasAttr<AliasAttr>())
1753     return Definition;
1754 
1755   // A variable template specialization (other than a static data member
1756   // template or an explicit specialization) is a declaration until we
1757   // instantiate its initializer.
1758   if (isa<VarTemplateSpecializationDecl>(this) &&
1759       getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1760     return DeclarationOnly;
1761 
1762   if (hasExternalStorage())
1763     return DeclarationOnly;
1764 
1765   // [dcl.link] p7:
1766   //   A declaration directly contained in a linkage-specification is treated
1767   //   as if it contains the extern specifier for the purpose of determining
1768   //   the linkage of the declared name and whether it is a definition.
1769   if (isSingleLineLanguageLinkage(*this))
1770     return DeclarationOnly;
1771 
1772   // C99 6.9.2p2:
1773   //   A declaration of an object that has file scope without an initializer,
1774   //   and without a storage class specifier or the scs 'static', constitutes
1775   //   a tentative definition.
1776   // No such thing in C++.
1777   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1778     return TentativeDefinition;
1779 
1780   // What's left is (in C, block-scope) declarations without initializers or
1781   // external storage. These are definitions.
1782   return Definition;
1783 }
1784 
1785 VarDecl *VarDecl::getActingDefinition() {
1786   DefinitionKind Kind = isThisDeclarationADefinition();
1787   if (Kind != TentativeDefinition)
1788     return 0;
1789 
1790   VarDecl *LastTentative = 0;
1791   VarDecl *First = getFirstDecl();
1792   for (auto I : First->redecls()) {
1793     Kind = I->isThisDeclarationADefinition();
1794     if (Kind == Definition)
1795       return 0;
1796     else if (Kind == TentativeDefinition)
1797       LastTentative = I;
1798   }
1799   return LastTentative;
1800 }
1801 
1802 VarDecl *VarDecl::getDefinition(ASTContext &C) {
1803   VarDecl *First = getFirstDecl();
1804   for (auto I : First->redecls()) {
1805     if (I->isThisDeclarationADefinition(C) == Definition)
1806       return I;
1807   }
1808   return 0;
1809 }
1810 
1811 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1812   DefinitionKind Kind = DeclarationOnly;
1813 
1814   const VarDecl *First = getFirstDecl();
1815   for (auto I : First->redecls()) {
1816     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
1817     if (Kind == Definition)
1818       break;
1819   }
1820 
1821   return Kind;
1822 }
1823 
1824 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1825   for (auto I : redecls()) {
1826     if (auto Expr = I->getInit()) {
1827       D = I;
1828       return Expr;
1829     }
1830   }
1831   return 0;
1832 }
1833 
1834 bool VarDecl::isOutOfLine() const {
1835   if (Decl::isOutOfLine())
1836     return true;
1837 
1838   if (!isStaticDataMember())
1839     return false;
1840 
1841   // If this static data member was instantiated from a static data member of
1842   // a class template, check whether that static data member was defined
1843   // out-of-line.
1844   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1845     return VD->isOutOfLine();
1846 
1847   return false;
1848 }
1849 
1850 VarDecl *VarDecl::getOutOfLineDefinition() {
1851   if (!isStaticDataMember())
1852     return 0;
1853 
1854   for (auto RD : redecls()) {
1855     if (RD->getLexicalDeclContext()->isFileContext())
1856       return RD;
1857   }
1858 
1859   return 0;
1860 }
1861 
1862 void VarDecl::setInit(Expr *I) {
1863   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1864     Eval->~EvaluatedStmt();
1865     getASTContext().Deallocate(Eval);
1866   }
1867 
1868   Init = I;
1869 }
1870 
1871 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1872   const LangOptions &Lang = C.getLangOpts();
1873 
1874   if (!Lang.CPlusPlus)
1875     return false;
1876 
1877   // In C++11, any variable of reference type can be used in a constant
1878   // expression if it is initialized by a constant expression.
1879   if (Lang.CPlusPlus11 && getType()->isReferenceType())
1880     return true;
1881 
1882   // Only const objects can be used in constant expressions in C++. C++98 does
1883   // not require the variable to be non-volatile, but we consider this to be a
1884   // defect.
1885   if (!getType().isConstQualified() || getType().isVolatileQualified())
1886     return false;
1887 
1888   // In C++, const, non-volatile variables of integral or enumeration types
1889   // can be used in constant expressions.
1890   if (getType()->isIntegralOrEnumerationType())
1891     return true;
1892 
1893   // Additionally, in C++11, non-volatile constexpr variables can be used in
1894   // constant expressions.
1895   return Lang.CPlusPlus11 && isConstexpr();
1896 }
1897 
1898 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1899 /// form, which contains extra information on the evaluated value of the
1900 /// initializer.
1901 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1902   EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1903   if (!Eval) {
1904     Stmt *S = Init.get<Stmt *>();
1905     // Note: EvaluatedStmt contains an APValue, which usually holds
1906     // resources not allocated from the ASTContext.  We need to do some
1907     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
1908     // where we can detect whether there's anything to clean up or not.
1909     Eval = new (getASTContext()) EvaluatedStmt;
1910     Eval->Value = S;
1911     Init = Eval;
1912   }
1913   return Eval;
1914 }
1915 
1916 APValue *VarDecl::evaluateValue() const {
1917   SmallVector<PartialDiagnosticAt, 8> Notes;
1918   return evaluateValue(Notes);
1919 }
1920 
1921 namespace {
1922 // Destroy an APValue that was allocated in an ASTContext.
1923 void DestroyAPValue(void* UntypedValue) {
1924   static_cast<APValue*>(UntypedValue)->~APValue();
1925 }
1926 } // namespace
1927 
1928 APValue *VarDecl::evaluateValue(
1929     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1930   EvaluatedStmt *Eval = ensureEvaluatedStmt();
1931 
1932   // We only produce notes indicating why an initializer is non-constant the
1933   // first time it is evaluated. FIXME: The notes won't always be emitted the
1934   // first time we try evaluation, so might not be produced at all.
1935   if (Eval->WasEvaluated)
1936     return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1937 
1938   const Expr *Init = cast<Expr>(Eval->Value);
1939   assert(!Init->isValueDependent());
1940 
1941   if (Eval->IsEvaluating) {
1942     // FIXME: Produce a diagnostic for self-initialization.
1943     Eval->CheckedICE = true;
1944     Eval->IsICE = false;
1945     return 0;
1946   }
1947 
1948   Eval->IsEvaluating = true;
1949 
1950   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1951                                             this, Notes);
1952 
1953   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
1954   // or that it's empty (so that there's nothing to clean up) if evaluation
1955   // failed.
1956   if (!Result)
1957     Eval->Evaluated = APValue();
1958   else if (Eval->Evaluated.needsCleanup())
1959     getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
1960 
1961   Eval->IsEvaluating = false;
1962   Eval->WasEvaluated = true;
1963 
1964   // In C++11, we have determined whether the initializer was a constant
1965   // expression as a side-effect.
1966   if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
1967     Eval->CheckedICE = true;
1968     Eval->IsICE = Result && Notes.empty();
1969   }
1970 
1971   return Result ? &Eval->Evaluated : 0;
1972 }
1973 
1974 bool VarDecl::checkInitIsICE() const {
1975   // Initializers of weak variables are never ICEs.
1976   if (isWeak())
1977     return false;
1978 
1979   EvaluatedStmt *Eval = ensureEvaluatedStmt();
1980   if (Eval->CheckedICE)
1981     // We have already checked whether this subexpression is an
1982     // integral constant expression.
1983     return Eval->IsICE;
1984 
1985   const Expr *Init = cast<Expr>(Eval->Value);
1986   assert(!Init->isValueDependent());
1987 
1988   // In C++11, evaluate the initializer to check whether it's a constant
1989   // expression.
1990   if (getASTContext().getLangOpts().CPlusPlus11) {
1991     SmallVector<PartialDiagnosticAt, 8> Notes;
1992     evaluateValue(Notes);
1993     return Eval->IsICE;
1994   }
1995 
1996   // It's an ICE whether or not the definition we found is
1997   // out-of-line.  See DR 721 and the discussion in Clang PR
1998   // 6206 for details.
1999 
2000   if (Eval->CheckingICE)
2001     return false;
2002   Eval->CheckingICE = true;
2003 
2004   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2005   Eval->CheckingICE = false;
2006   Eval->CheckedICE = true;
2007   return Eval->IsICE;
2008 }
2009 
2010 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2011   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2012     return cast<VarDecl>(MSI->getInstantiatedFrom());
2013 
2014   return 0;
2015 }
2016 
2017 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2018   if (const VarTemplateSpecializationDecl *Spec =
2019           dyn_cast<VarTemplateSpecializationDecl>(this))
2020     return Spec->getSpecializationKind();
2021 
2022   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2023     return MSI->getTemplateSpecializationKind();
2024 
2025   return TSK_Undeclared;
2026 }
2027 
2028 SourceLocation VarDecl::getPointOfInstantiation() const {
2029   if (const VarTemplateSpecializationDecl *Spec =
2030           dyn_cast<VarTemplateSpecializationDecl>(this))
2031     return Spec->getPointOfInstantiation();
2032 
2033   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2034     return MSI->getPointOfInstantiation();
2035 
2036   return SourceLocation();
2037 }
2038 
2039 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2040   return getASTContext().getTemplateOrSpecializationInfo(this)
2041       .dyn_cast<VarTemplateDecl *>();
2042 }
2043 
2044 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2045   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2046 }
2047 
2048 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2049   if (isStaticDataMember())
2050     // FIXME: Remove ?
2051     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2052     return getASTContext().getTemplateOrSpecializationInfo(this)
2053         .dyn_cast<MemberSpecializationInfo *>();
2054   return 0;
2055 }
2056 
2057 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2058                                          SourceLocation PointOfInstantiation) {
2059   assert((isa<VarTemplateSpecializationDecl>(this) ||
2060           getMemberSpecializationInfo()) &&
2061          "not a variable or static data member template specialization");
2062 
2063   if (VarTemplateSpecializationDecl *Spec =
2064           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2065     Spec->setSpecializationKind(TSK);
2066     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2067         Spec->getPointOfInstantiation().isInvalid())
2068       Spec->setPointOfInstantiation(PointOfInstantiation);
2069   }
2070 
2071   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2072     MSI->setTemplateSpecializationKind(TSK);
2073     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2074         MSI->getPointOfInstantiation().isInvalid())
2075       MSI->setPointOfInstantiation(PointOfInstantiation);
2076   }
2077 }
2078 
2079 void
2080 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2081                                             TemplateSpecializationKind TSK) {
2082   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2083          "Previous template or instantiation?");
2084   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2085 }
2086 
2087 //===----------------------------------------------------------------------===//
2088 // ParmVarDecl Implementation
2089 //===----------------------------------------------------------------------===//
2090 
2091 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2092                                  SourceLocation StartLoc,
2093                                  SourceLocation IdLoc, IdentifierInfo *Id,
2094                                  QualType T, TypeSourceInfo *TInfo,
2095                                  StorageClass S, Expr *DefArg) {
2096   return new (C, DC) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
2097                                  S, DefArg);
2098 }
2099 
2100 QualType ParmVarDecl::getOriginalType() const {
2101   TypeSourceInfo *TSI = getTypeSourceInfo();
2102   QualType T = TSI ? TSI->getType() : getType();
2103   if (const DecayedType *DT = dyn_cast<DecayedType>(T))
2104     return DT->getOriginalType();
2105   return T;
2106 }
2107 
2108 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2109   return new (C, ID) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
2110                                  0, QualType(), 0, SC_None, 0);
2111 }
2112 
2113 SourceRange ParmVarDecl::getSourceRange() const {
2114   if (!hasInheritedDefaultArg()) {
2115     SourceRange ArgRange = getDefaultArgRange();
2116     if (ArgRange.isValid())
2117       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2118   }
2119 
2120   // DeclaratorDecl considers the range of postfix types as overlapping with the
2121   // declaration name, but this is not the case with parameters in ObjC methods.
2122   if (isa<ObjCMethodDecl>(getDeclContext()))
2123     return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2124 
2125   return DeclaratorDecl::getSourceRange();
2126 }
2127 
2128 Expr *ParmVarDecl::getDefaultArg() {
2129   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2130   assert(!hasUninstantiatedDefaultArg() &&
2131          "Default argument is not yet instantiated!");
2132 
2133   Expr *Arg = getInit();
2134   if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2135     return E->getSubExpr();
2136 
2137   return Arg;
2138 }
2139 
2140 SourceRange ParmVarDecl::getDefaultArgRange() const {
2141   if (const Expr *E = getInit())
2142     return E->getSourceRange();
2143 
2144   if (hasUninstantiatedDefaultArg())
2145     return getUninstantiatedDefaultArg()->getSourceRange();
2146 
2147   return SourceRange();
2148 }
2149 
2150 bool ParmVarDecl::isParameterPack() const {
2151   return isa<PackExpansionType>(getType());
2152 }
2153 
2154 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2155   getASTContext().setParameterIndex(this, parameterIndex);
2156   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2157 }
2158 
2159 unsigned ParmVarDecl::getParameterIndexLarge() const {
2160   return getASTContext().getParameterIndex(this);
2161 }
2162 
2163 //===----------------------------------------------------------------------===//
2164 // FunctionDecl Implementation
2165 //===----------------------------------------------------------------------===//
2166 
2167 void FunctionDecl::getNameForDiagnostic(
2168     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2169   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2170   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2171   if (TemplateArgs)
2172     TemplateSpecializationType::PrintTemplateArgumentList(
2173         OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2174 }
2175 
2176 bool FunctionDecl::isVariadic() const {
2177   if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
2178     return FT->isVariadic();
2179   return false;
2180 }
2181 
2182 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2183   for (auto I : redecls()) {
2184     if (I->Body || I->IsLateTemplateParsed) {
2185       Definition = I;
2186       return true;
2187     }
2188   }
2189 
2190   return false;
2191 }
2192 
2193 bool FunctionDecl::hasTrivialBody() const
2194 {
2195   Stmt *S = getBody();
2196   if (!S) {
2197     // Since we don't have a body for this function, we don't know if it's
2198     // trivial or not.
2199     return false;
2200   }
2201 
2202   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2203     return true;
2204   return false;
2205 }
2206 
2207 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2208   for (auto I : redecls()) {
2209     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2210         I->hasAttr<AliasAttr>()) {
2211       Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
2212       return true;
2213     }
2214   }
2215 
2216   return false;
2217 }
2218 
2219 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2220   if (!hasBody(Definition))
2221     return 0;
2222 
2223   if (Definition->Body)
2224     return Definition->Body.get(getASTContext().getExternalSource());
2225 
2226   return 0;
2227 }
2228 
2229 void FunctionDecl::setBody(Stmt *B) {
2230   Body = B;
2231   if (B)
2232     EndRangeLoc = B->getLocEnd();
2233 }
2234 
2235 void FunctionDecl::setPure(bool P) {
2236   IsPure = P;
2237   if (P)
2238     if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2239       Parent->markedVirtualFunctionPure();
2240 }
2241 
2242 template<std::size_t Len>
2243 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2244   IdentifierInfo *II = ND->getIdentifier();
2245   return II && II->isStr(Str);
2246 }
2247 
2248 bool FunctionDecl::isMain() const {
2249   const TranslationUnitDecl *tunit =
2250     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2251   return tunit &&
2252          !tunit->getASTContext().getLangOpts().Freestanding &&
2253          isNamed(this, "main");
2254 }
2255 
2256 bool FunctionDecl::isMSVCRTEntryPoint() const {
2257   const TranslationUnitDecl *TUnit =
2258       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2259   if (!TUnit)
2260     return false;
2261 
2262   // Even though we aren't really targeting MSVCRT if we are freestanding,
2263   // semantic analysis for these functions remains the same.
2264 
2265   // MSVCRT entry points only exist on MSVCRT targets.
2266   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2267     return false;
2268 
2269   // Nameless functions like constructors cannot be entry points.
2270   if (!getIdentifier())
2271     return false;
2272 
2273   return llvm::StringSwitch<bool>(getName())
2274       .Cases("main",     // an ANSI console app
2275              "wmain",    // a Unicode console App
2276              "WinMain",  // an ANSI GUI app
2277              "wWinMain", // a Unicode GUI app
2278              "DllMain",  // a DLL
2279              true)
2280       .Default(false);
2281 }
2282 
2283 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2284   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2285   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2286          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2287          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2288          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2289 
2290   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2291     return false;
2292 
2293   const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
2294   if (proto->getNumParams() != 2 || proto->isVariadic())
2295     return false;
2296 
2297   ASTContext &Context =
2298     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2299       ->getASTContext();
2300 
2301   // The result type and first argument type are constant across all
2302   // these operators.  The second argument must be exactly void*.
2303   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2304 }
2305 
2306 static bool isNamespaceStd(const DeclContext *DC) {
2307   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC->getRedeclContext());
2308   return ND && isNamed(ND, "std") &&
2309          ND->getParent()->getRedeclContext()->isTranslationUnit();
2310 }
2311 
2312 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2313   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2314     return false;
2315   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2316       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2317       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2318       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2319     return false;
2320 
2321   if (isa<CXXRecordDecl>(getDeclContext()))
2322     return false;
2323 
2324   // This can only fail for an invalid 'operator new' declaration.
2325   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2326     return false;
2327 
2328   const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();
2329   if (FPT->getNumParams() > 2 || FPT->isVariadic())
2330     return false;
2331 
2332   // If this is a single-parameter function, it must be a replaceable global
2333   // allocation or deallocation function.
2334   if (FPT->getNumParams() == 1)
2335     return true;
2336 
2337   // Otherwise, we're looking for a second parameter whose type is
2338   // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2339   QualType Ty = FPT->getParamType(1);
2340   ASTContext &Ctx = getASTContext();
2341   if (Ctx.getLangOpts().SizedDeallocation &&
2342       Ctx.hasSameType(Ty, Ctx.getSizeType()))
2343     return true;
2344   if (!Ty->isReferenceType())
2345     return false;
2346   Ty = Ty->getPointeeType();
2347   if (Ty.getCVRQualifiers() != Qualifiers::Const)
2348     return false;
2349   // FIXME: Recognise nothrow_t in an inline namespace inside std?
2350   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2351   return RD && isNamed(RD, "nothrow_t") && isNamespaceStd(RD->getDeclContext());
2352 }
2353 
2354 FunctionDecl *
2355 FunctionDecl::getCorrespondingUnsizedGlobalDeallocationFunction() const {
2356   ASTContext &Ctx = getASTContext();
2357   if (!Ctx.getLangOpts().SizedDeallocation)
2358     return 0;
2359 
2360   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2361     return 0;
2362   if (getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2363       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2364     return 0;
2365   if (isa<CXXRecordDecl>(getDeclContext()))
2366     return 0;
2367 
2368   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2369     return 0;
2370 
2371   if (getNumParams() != 2 || isVariadic() ||
2372       !Ctx.hasSameType(getType()->castAs<FunctionProtoType>()->getParamType(1),
2373                        Ctx.getSizeType()))
2374     return 0;
2375 
2376   // This is a sized deallocation function. Find the corresponding unsized
2377   // deallocation function.
2378   lookup_const_result R = getDeclContext()->lookup(getDeclName());
2379   for (lookup_const_result::iterator RI = R.begin(), RE = R.end(); RI != RE;
2380        ++RI)
2381     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*RI))
2382       if (FD->getNumParams() == 1 && !FD->isVariadic())
2383         return FD;
2384   return 0;
2385 }
2386 
2387 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2388   return getLanguageLinkageTemplate(*this);
2389 }
2390 
2391 bool FunctionDecl::isExternC() const {
2392   return isExternCTemplate(*this);
2393 }
2394 
2395 bool FunctionDecl::isInExternCContext() const {
2396   return getLexicalDeclContext()->isExternCContext();
2397 }
2398 
2399 bool FunctionDecl::isInExternCXXContext() const {
2400   return getLexicalDeclContext()->isExternCXXContext();
2401 }
2402 
2403 bool FunctionDecl::isGlobal() const {
2404   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
2405     return Method->isStatic();
2406 
2407   if (getCanonicalDecl()->getStorageClass() == SC_Static)
2408     return false;
2409 
2410   for (const DeclContext *DC = getDeclContext();
2411        DC->isNamespace();
2412        DC = DC->getParent()) {
2413     if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
2414       if (!Namespace->getDeclName())
2415         return false;
2416       break;
2417     }
2418   }
2419 
2420   return true;
2421 }
2422 
2423 bool FunctionDecl::isNoReturn() const {
2424   return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2425          hasAttr<C11NoReturnAttr>() ||
2426          getType()->getAs<FunctionType>()->getNoReturnAttr();
2427 }
2428 
2429 void
2430 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2431   redeclarable_base::setPreviousDecl(PrevDecl);
2432 
2433   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2434     FunctionTemplateDecl *PrevFunTmpl
2435       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
2436     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2437     FunTmpl->setPreviousDecl(PrevFunTmpl);
2438   }
2439 
2440   if (PrevDecl && PrevDecl->IsInline)
2441     IsInline = true;
2442 }
2443 
2444 const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
2445   return getFirstDecl();
2446 }
2447 
2448 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2449 
2450 /// \brief Returns a value indicating whether this function
2451 /// corresponds to a builtin function.
2452 ///
2453 /// The function corresponds to a built-in function if it is
2454 /// declared at translation scope or within an extern "C" block and
2455 /// its name matches with the name of a builtin. The returned value
2456 /// will be 0 for functions that do not correspond to a builtin, a
2457 /// value of type \c Builtin::ID if in the target-independent range
2458 /// \c [1,Builtin::First), or a target-specific builtin value.
2459 unsigned FunctionDecl::getBuiltinID() const {
2460   if (!getIdentifier())
2461     return 0;
2462 
2463   unsigned BuiltinID = getIdentifier()->getBuiltinID();
2464   if (!BuiltinID)
2465     return 0;
2466 
2467   ASTContext &Context = getASTContext();
2468   if (Context.getLangOpts().CPlusPlus) {
2469     const LinkageSpecDecl *LinkageDecl = dyn_cast<LinkageSpecDecl>(
2470         getFirstDecl()->getDeclContext());
2471     // In C++, the first declaration of a builtin is always inside an implicit
2472     // extern "C".
2473     // FIXME: A recognised library function may not be directly in an extern "C"
2474     // declaration, for instance "extern "C" { namespace std { decl } }".
2475     if (!LinkageDecl || LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2476       return 0;
2477   }
2478 
2479   // If the function is marked "overloadable", it has a different mangled name
2480   // and is not the C library function.
2481   if (hasAttr<OverloadableAttr>())
2482     return 0;
2483 
2484   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2485     return BuiltinID;
2486 
2487   // This function has the name of a known C library
2488   // function. Determine whether it actually refers to the C library
2489   // function or whether it just has the same name.
2490 
2491   // If this is a static function, it's not a builtin.
2492   if (getStorageClass() == SC_Static)
2493     return 0;
2494 
2495   return BuiltinID;
2496 }
2497 
2498 
2499 /// getNumParams - Return the number of parameters this function must have
2500 /// based on its FunctionType.  This is the length of the ParamInfo array
2501 /// after it has been created.
2502 unsigned FunctionDecl::getNumParams() const {
2503   const FunctionProtoType *FPT = getType()->getAs<FunctionProtoType>();
2504   return FPT ? FPT->getNumParams() : 0;
2505 }
2506 
2507 void FunctionDecl::setParams(ASTContext &C,
2508                              ArrayRef<ParmVarDecl *> NewParamInfo) {
2509   assert(ParamInfo == 0 && "Already has param info!");
2510   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2511 
2512   // Zero params -> null pointer.
2513   if (!NewParamInfo.empty()) {
2514     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2515     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2516   }
2517 }
2518 
2519 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2520   assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2521 
2522   if (!NewDecls.empty()) {
2523     NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2524     std::copy(NewDecls.begin(), NewDecls.end(), A);
2525     DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size());
2526   }
2527 }
2528 
2529 /// getMinRequiredArguments - Returns the minimum number of arguments
2530 /// needed to call this function. This may be fewer than the number of
2531 /// function parameters, if some of the parameters have default
2532 /// arguments (in C++) or the last parameter is a parameter pack.
2533 unsigned FunctionDecl::getMinRequiredArguments() const {
2534   if (!getASTContext().getLangOpts().CPlusPlus)
2535     return getNumParams();
2536 
2537   unsigned NumRequiredArgs = getNumParams();
2538 
2539   // If the last parameter is a parameter pack, we don't need an argument for
2540   // it.
2541   if (NumRequiredArgs > 0 &&
2542       getParamDecl(NumRequiredArgs - 1)->isParameterPack())
2543     --NumRequiredArgs;
2544 
2545   // If this parameter has a default argument, we don't need an argument for
2546   // it.
2547   while (NumRequiredArgs > 0 &&
2548          getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
2549     --NumRequiredArgs;
2550 
2551   // We might have parameter packs before the end. These can't be deduced,
2552   // but they can still handle multiple arguments.
2553   unsigned ArgIdx = NumRequiredArgs;
2554   while (ArgIdx > 0) {
2555     if (getParamDecl(ArgIdx - 1)->isParameterPack())
2556       NumRequiredArgs = ArgIdx;
2557 
2558     --ArgIdx;
2559   }
2560 
2561   return NumRequiredArgs;
2562 }
2563 
2564 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2565   // Only consider file-scope declarations in this test.
2566   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2567     return false;
2568 
2569   // Only consider explicit declarations; the presence of a builtin for a
2570   // libcall shouldn't affect whether a definition is externally visible.
2571   if (Redecl->isImplicit())
2572     return false;
2573 
2574   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2575     return true; // Not an inline definition
2576 
2577   return false;
2578 }
2579 
2580 /// \brief For a function declaration in C or C++, determine whether this
2581 /// declaration causes the definition to be externally visible.
2582 ///
2583 /// Specifically, this determines if adding the current declaration to the set
2584 /// of redeclarations of the given functions causes
2585 /// isInlineDefinitionExternallyVisible to change from false to true.
2586 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2587   assert(!doesThisDeclarationHaveABody() &&
2588          "Must have a declaration without a body.");
2589 
2590   ASTContext &Context = getASTContext();
2591 
2592   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2593     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2594     // an externally visible definition.
2595     //
2596     // FIXME: What happens if gnu_inline gets added on after the first
2597     // declaration?
2598     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2599       return false;
2600 
2601     const FunctionDecl *Prev = this;
2602     bool FoundBody = false;
2603     while ((Prev = Prev->getPreviousDecl())) {
2604       FoundBody |= Prev->Body.isValid();
2605 
2606       if (Prev->Body) {
2607         // If it's not the case that both 'inline' and 'extern' are
2608         // specified on the definition, then it is always externally visible.
2609         if (!Prev->isInlineSpecified() ||
2610             Prev->getStorageClass() != SC_Extern)
2611           return false;
2612       } else if (Prev->isInlineSpecified() &&
2613                  Prev->getStorageClass() != SC_Extern) {
2614         return false;
2615       }
2616     }
2617     return FoundBody;
2618   }
2619 
2620   if (Context.getLangOpts().CPlusPlus)
2621     return false;
2622 
2623   // C99 6.7.4p6:
2624   //   [...] If all of the file scope declarations for a function in a
2625   //   translation unit include the inline function specifier without extern,
2626   //   then the definition in that translation unit is an inline definition.
2627   if (isInlineSpecified() && getStorageClass() != SC_Extern)
2628     return false;
2629   const FunctionDecl *Prev = this;
2630   bool FoundBody = false;
2631   while ((Prev = Prev->getPreviousDecl())) {
2632     FoundBody |= Prev->Body.isValid();
2633     if (RedeclForcesDefC99(Prev))
2634       return false;
2635   }
2636   return FoundBody;
2637 }
2638 
2639 /// \brief For an inline function definition in C, or for a gnu_inline function
2640 /// in C++, determine whether the definition will be externally visible.
2641 ///
2642 /// Inline function definitions are always available for inlining optimizations.
2643 /// However, depending on the language dialect, declaration specifiers, and
2644 /// attributes, the definition of an inline function may or may not be
2645 /// "externally" visible to other translation units in the program.
2646 ///
2647 /// In C99, inline definitions are not externally visible by default. However,
2648 /// if even one of the global-scope declarations is marked "extern inline", the
2649 /// inline definition becomes externally visible (C99 6.7.4p6).
2650 ///
2651 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2652 /// definition, we use the GNU semantics for inline, which are nearly the
2653 /// opposite of C99 semantics. In particular, "inline" by itself will create
2654 /// an externally visible symbol, but "extern inline" will not create an
2655 /// externally visible symbol.
2656 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2657   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2658   assert(isInlined() && "Function must be inline");
2659   ASTContext &Context = getASTContext();
2660 
2661   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2662     // Note: If you change the logic here, please change
2663     // doesDeclarationForceExternallyVisibleDefinition as well.
2664     //
2665     // If it's not the case that both 'inline' and 'extern' are
2666     // specified on the definition, then this inline definition is
2667     // externally visible.
2668     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2669       return true;
2670 
2671     // If any declaration is 'inline' but not 'extern', then this definition
2672     // is externally visible.
2673     for (auto Redecl : redecls()) {
2674       if (Redecl->isInlineSpecified() &&
2675           Redecl->getStorageClass() != SC_Extern)
2676         return true;
2677     }
2678 
2679     return false;
2680   }
2681 
2682   // The rest of this function is C-only.
2683   assert(!Context.getLangOpts().CPlusPlus &&
2684          "should not use C inline rules in C++");
2685 
2686   // C99 6.7.4p6:
2687   //   [...] If all of the file scope declarations for a function in a
2688   //   translation unit include the inline function specifier without extern,
2689   //   then the definition in that translation unit is an inline definition.
2690   for (auto Redecl : redecls()) {
2691     if (RedeclForcesDefC99(Redecl))
2692       return true;
2693   }
2694 
2695   // C99 6.7.4p6:
2696   //   An inline definition does not provide an external definition for the
2697   //   function, and does not forbid an external definition in another
2698   //   translation unit.
2699   return false;
2700 }
2701 
2702 /// getOverloadedOperator - Which C++ overloaded operator this
2703 /// function represents, if any.
2704 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2705   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2706     return getDeclName().getCXXOverloadedOperator();
2707   else
2708     return OO_None;
2709 }
2710 
2711 /// getLiteralIdentifier - The literal suffix identifier this function
2712 /// represents, if any.
2713 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2714   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2715     return getDeclName().getCXXLiteralIdentifier();
2716   else
2717     return 0;
2718 }
2719 
2720 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2721   if (TemplateOrSpecialization.isNull())
2722     return TK_NonTemplate;
2723   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2724     return TK_FunctionTemplate;
2725   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2726     return TK_MemberSpecialization;
2727   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2728     return TK_FunctionTemplateSpecialization;
2729   if (TemplateOrSpecialization.is
2730                                <DependentFunctionTemplateSpecializationInfo*>())
2731     return TK_DependentFunctionTemplateSpecialization;
2732 
2733   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2734 }
2735 
2736 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2737   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2738     return cast<FunctionDecl>(Info->getInstantiatedFrom());
2739 
2740   return 0;
2741 }
2742 
2743 void
2744 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2745                                                FunctionDecl *FD,
2746                                                TemplateSpecializationKind TSK) {
2747   assert(TemplateOrSpecialization.isNull() &&
2748          "Member function is already a specialization");
2749   MemberSpecializationInfo *Info
2750     = new (C) MemberSpecializationInfo(FD, TSK);
2751   TemplateOrSpecialization = Info;
2752 }
2753 
2754 bool FunctionDecl::isImplicitlyInstantiable() const {
2755   // If the function is invalid, it can't be implicitly instantiated.
2756   if (isInvalidDecl())
2757     return false;
2758 
2759   switch (getTemplateSpecializationKind()) {
2760   case TSK_Undeclared:
2761   case TSK_ExplicitInstantiationDefinition:
2762     return false;
2763 
2764   case TSK_ImplicitInstantiation:
2765     return true;
2766 
2767   // It is possible to instantiate TSK_ExplicitSpecialization kind
2768   // if the FunctionDecl has a class scope specialization pattern.
2769   case TSK_ExplicitSpecialization:
2770     return getClassScopeSpecializationPattern() != 0;
2771 
2772   case TSK_ExplicitInstantiationDeclaration:
2773     // Handled below.
2774     break;
2775   }
2776 
2777   // Find the actual template from which we will instantiate.
2778   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2779   bool HasPattern = false;
2780   if (PatternDecl)
2781     HasPattern = PatternDecl->hasBody(PatternDecl);
2782 
2783   // C++0x [temp.explicit]p9:
2784   //   Except for inline functions, other explicit instantiation declarations
2785   //   have the effect of suppressing the implicit instantiation of the entity
2786   //   to which they refer.
2787   if (!HasPattern || !PatternDecl)
2788     return true;
2789 
2790   return PatternDecl->isInlined();
2791 }
2792 
2793 bool FunctionDecl::isTemplateInstantiation() const {
2794   switch (getTemplateSpecializationKind()) {
2795     case TSK_Undeclared:
2796     case TSK_ExplicitSpecialization:
2797       return false;
2798     case TSK_ImplicitInstantiation:
2799     case TSK_ExplicitInstantiationDeclaration:
2800     case TSK_ExplicitInstantiationDefinition:
2801       return true;
2802   }
2803   llvm_unreachable("All TSK values handled.");
2804 }
2805 
2806 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2807   // Handle class scope explicit specialization special case.
2808   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2809     return getClassScopeSpecializationPattern();
2810 
2811   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2812     while (Primary->getInstantiatedFromMemberTemplate()) {
2813       // If we have hit a point where the user provided a specialization of
2814       // this template, we're done looking.
2815       if (Primary->isMemberSpecialization())
2816         break;
2817 
2818       Primary = Primary->getInstantiatedFromMemberTemplate();
2819     }
2820 
2821     return Primary->getTemplatedDecl();
2822   }
2823 
2824   return getInstantiatedFromMemberFunction();
2825 }
2826 
2827 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2828   if (FunctionTemplateSpecializationInfo *Info
2829         = TemplateOrSpecialization
2830             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2831     return Info->Template.getPointer();
2832   }
2833   return 0;
2834 }
2835 
2836 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2837     return getASTContext().getClassScopeSpecializationPattern(this);
2838 }
2839 
2840 const TemplateArgumentList *
2841 FunctionDecl::getTemplateSpecializationArgs() const {
2842   if (FunctionTemplateSpecializationInfo *Info
2843         = TemplateOrSpecialization
2844             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2845     return Info->TemplateArguments;
2846   }
2847   return 0;
2848 }
2849 
2850 const ASTTemplateArgumentListInfo *
2851 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2852   if (FunctionTemplateSpecializationInfo *Info
2853         = TemplateOrSpecialization
2854             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2855     return Info->TemplateArgumentsAsWritten;
2856   }
2857   return 0;
2858 }
2859 
2860 void
2861 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2862                                                 FunctionTemplateDecl *Template,
2863                                      const TemplateArgumentList *TemplateArgs,
2864                                                 void *InsertPos,
2865                                                 TemplateSpecializationKind TSK,
2866                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
2867                                           SourceLocation PointOfInstantiation) {
2868   assert(TSK != TSK_Undeclared &&
2869          "Must specify the type of function template specialization");
2870   FunctionTemplateSpecializationInfo *Info
2871     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2872   if (!Info)
2873     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2874                                                       TemplateArgs,
2875                                                       TemplateArgsAsWritten,
2876                                                       PointOfInstantiation);
2877   TemplateOrSpecialization = Info;
2878   Template->addSpecialization(Info, InsertPos);
2879 }
2880 
2881 void
2882 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2883                                     const UnresolvedSetImpl &Templates,
2884                              const TemplateArgumentListInfo &TemplateArgs) {
2885   assert(TemplateOrSpecialization.isNull());
2886   size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2887   Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2888   Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2889   void *Buffer = Context.Allocate(Size);
2890   DependentFunctionTemplateSpecializationInfo *Info =
2891     new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2892                                                              TemplateArgs);
2893   TemplateOrSpecialization = Info;
2894 }
2895 
2896 DependentFunctionTemplateSpecializationInfo::
2897 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2898                                       const TemplateArgumentListInfo &TArgs)
2899   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2900 
2901   d.NumTemplates = Ts.size();
2902   d.NumArgs = TArgs.size();
2903 
2904   FunctionTemplateDecl **TsArray =
2905     const_cast<FunctionTemplateDecl**>(getTemplates());
2906   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2907     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2908 
2909   TemplateArgumentLoc *ArgsArray =
2910     const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2911   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2912     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2913 }
2914 
2915 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2916   // For a function template specialization, query the specialization
2917   // information object.
2918   FunctionTemplateSpecializationInfo *FTSInfo
2919     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2920   if (FTSInfo)
2921     return FTSInfo->getTemplateSpecializationKind();
2922 
2923   MemberSpecializationInfo *MSInfo
2924     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2925   if (MSInfo)
2926     return MSInfo->getTemplateSpecializationKind();
2927 
2928   return TSK_Undeclared;
2929 }
2930 
2931 void
2932 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2933                                           SourceLocation PointOfInstantiation) {
2934   if (FunctionTemplateSpecializationInfo *FTSInfo
2935         = TemplateOrSpecialization.dyn_cast<
2936                                     FunctionTemplateSpecializationInfo*>()) {
2937     FTSInfo->setTemplateSpecializationKind(TSK);
2938     if (TSK != TSK_ExplicitSpecialization &&
2939         PointOfInstantiation.isValid() &&
2940         FTSInfo->getPointOfInstantiation().isInvalid())
2941       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2942   } else if (MemberSpecializationInfo *MSInfo
2943              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2944     MSInfo->setTemplateSpecializationKind(TSK);
2945     if (TSK != TSK_ExplicitSpecialization &&
2946         PointOfInstantiation.isValid() &&
2947         MSInfo->getPointOfInstantiation().isInvalid())
2948       MSInfo->setPointOfInstantiation(PointOfInstantiation);
2949   } else
2950     llvm_unreachable("Function cannot have a template specialization kind");
2951 }
2952 
2953 SourceLocation FunctionDecl::getPointOfInstantiation() const {
2954   if (FunctionTemplateSpecializationInfo *FTSInfo
2955         = TemplateOrSpecialization.dyn_cast<
2956                                         FunctionTemplateSpecializationInfo*>())
2957     return FTSInfo->getPointOfInstantiation();
2958   else if (MemberSpecializationInfo *MSInfo
2959              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2960     return MSInfo->getPointOfInstantiation();
2961 
2962   return SourceLocation();
2963 }
2964 
2965 bool FunctionDecl::isOutOfLine() const {
2966   if (Decl::isOutOfLine())
2967     return true;
2968 
2969   // If this function was instantiated from a member function of a
2970   // class template, check whether that member function was defined out-of-line.
2971   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2972     const FunctionDecl *Definition;
2973     if (FD->hasBody(Definition))
2974       return Definition->isOutOfLine();
2975   }
2976 
2977   // If this function was instantiated from a function template,
2978   // check whether that function template was defined out-of-line.
2979   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2980     const FunctionDecl *Definition;
2981     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2982       return Definition->isOutOfLine();
2983   }
2984 
2985   return false;
2986 }
2987 
2988 SourceRange FunctionDecl::getSourceRange() const {
2989   return SourceRange(getOuterLocStart(), EndRangeLoc);
2990 }
2991 
2992 unsigned FunctionDecl::getMemoryFunctionKind() const {
2993   IdentifierInfo *FnInfo = getIdentifier();
2994 
2995   if (!FnInfo)
2996     return 0;
2997 
2998   // Builtin handling.
2999   switch (getBuiltinID()) {
3000   case Builtin::BI__builtin_memset:
3001   case Builtin::BI__builtin___memset_chk:
3002   case Builtin::BImemset:
3003     return Builtin::BImemset;
3004 
3005   case Builtin::BI__builtin_memcpy:
3006   case Builtin::BI__builtin___memcpy_chk:
3007   case Builtin::BImemcpy:
3008     return Builtin::BImemcpy;
3009 
3010   case Builtin::BI__builtin_memmove:
3011   case Builtin::BI__builtin___memmove_chk:
3012   case Builtin::BImemmove:
3013     return Builtin::BImemmove;
3014 
3015   case Builtin::BIstrlcpy:
3016     return Builtin::BIstrlcpy;
3017   case Builtin::BIstrlcat:
3018     return Builtin::BIstrlcat;
3019 
3020   case Builtin::BI__builtin_memcmp:
3021   case Builtin::BImemcmp:
3022     return Builtin::BImemcmp;
3023 
3024   case Builtin::BI__builtin_strncpy:
3025   case Builtin::BI__builtin___strncpy_chk:
3026   case Builtin::BIstrncpy:
3027     return Builtin::BIstrncpy;
3028 
3029   case Builtin::BI__builtin_strncmp:
3030   case Builtin::BIstrncmp:
3031     return Builtin::BIstrncmp;
3032 
3033   case Builtin::BI__builtin_strncasecmp:
3034   case Builtin::BIstrncasecmp:
3035     return Builtin::BIstrncasecmp;
3036 
3037   case Builtin::BI__builtin_strncat:
3038   case Builtin::BI__builtin___strncat_chk:
3039   case Builtin::BIstrncat:
3040     return Builtin::BIstrncat;
3041 
3042   case Builtin::BI__builtin_strndup:
3043   case Builtin::BIstrndup:
3044     return Builtin::BIstrndup;
3045 
3046   case Builtin::BI__builtin_strlen:
3047   case Builtin::BIstrlen:
3048     return Builtin::BIstrlen;
3049 
3050   default:
3051     if (isExternC()) {
3052       if (FnInfo->isStr("memset"))
3053         return Builtin::BImemset;
3054       else if (FnInfo->isStr("memcpy"))
3055         return Builtin::BImemcpy;
3056       else if (FnInfo->isStr("memmove"))
3057         return Builtin::BImemmove;
3058       else if (FnInfo->isStr("memcmp"))
3059         return Builtin::BImemcmp;
3060       else if (FnInfo->isStr("strncpy"))
3061         return Builtin::BIstrncpy;
3062       else if (FnInfo->isStr("strncmp"))
3063         return Builtin::BIstrncmp;
3064       else if (FnInfo->isStr("strncasecmp"))
3065         return Builtin::BIstrncasecmp;
3066       else if (FnInfo->isStr("strncat"))
3067         return Builtin::BIstrncat;
3068       else if (FnInfo->isStr("strndup"))
3069         return Builtin::BIstrndup;
3070       else if (FnInfo->isStr("strlen"))
3071         return Builtin::BIstrlen;
3072     }
3073     break;
3074   }
3075   return 0;
3076 }
3077 
3078 //===----------------------------------------------------------------------===//
3079 // FieldDecl Implementation
3080 //===----------------------------------------------------------------------===//
3081 
3082 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3083                              SourceLocation StartLoc, SourceLocation IdLoc,
3084                              IdentifierInfo *Id, QualType T,
3085                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3086                              InClassInitStyle InitStyle) {
3087   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3088                                BW, Mutable, InitStyle);
3089 }
3090 
3091 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3092   return new (C, ID) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
3093                                0, QualType(), 0, 0, false, ICIS_NoInit);
3094 }
3095 
3096 bool FieldDecl::isAnonymousStructOrUnion() const {
3097   if (!isImplicit() || getDeclName())
3098     return false;
3099 
3100   if (const RecordType *Record = getType()->getAs<RecordType>())
3101     return Record->getDecl()->isAnonymousStructOrUnion();
3102 
3103   return false;
3104 }
3105 
3106 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3107   assert(isBitField() && "not a bitfield");
3108   Expr *BitWidth = InitializerOrBitWidth.getPointer();
3109   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3110 }
3111 
3112 unsigned FieldDecl::getFieldIndex() const {
3113   const FieldDecl *Canonical = getCanonicalDecl();
3114   if (Canonical != this)
3115     return Canonical->getFieldIndex();
3116 
3117   if (CachedFieldIndex) return CachedFieldIndex - 1;
3118 
3119   unsigned Index = 0;
3120   const RecordDecl *RD = getParent();
3121 
3122   for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
3123        I != E; ++I, ++Index)
3124     I->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3125 
3126   assert(CachedFieldIndex && "failed to find field in parent");
3127   return CachedFieldIndex - 1;
3128 }
3129 
3130 SourceRange FieldDecl::getSourceRange() const {
3131   if (const Expr *E = InitializerOrBitWidth.getPointer())
3132     return SourceRange(getInnerLocStart(), E->getLocEnd());
3133   return DeclaratorDecl::getSourceRange();
3134 }
3135 
3136 void FieldDecl::setBitWidth(Expr *Width) {
3137   assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() &&
3138          "bit width or initializer already set");
3139   InitializerOrBitWidth.setPointer(Width);
3140 }
3141 
3142 void FieldDecl::setInClassInitializer(Expr *Init) {
3143   assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() &&
3144          "bit width or initializer already set");
3145   InitializerOrBitWidth.setPointer(Init);
3146 }
3147 
3148 //===----------------------------------------------------------------------===//
3149 // TagDecl Implementation
3150 //===----------------------------------------------------------------------===//
3151 
3152 SourceLocation TagDecl::getOuterLocStart() const {
3153   return getTemplateOrInnerLocStart(this);
3154 }
3155 
3156 SourceRange TagDecl::getSourceRange() const {
3157   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3158   return SourceRange(getOuterLocStart(), E);
3159 }
3160 
3161 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3162 
3163 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3164   NamedDeclOrQualifier = TDD;
3165   if (TypeForDecl)
3166     assert(TypeForDecl->isLinkageValid());
3167   assert(isLinkageValid());
3168 }
3169 
3170 void TagDecl::startDefinition() {
3171   IsBeingDefined = true;
3172 
3173   if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) {
3174     struct CXXRecordDecl::DefinitionData *Data =
3175       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3176     for (auto I : redecls())
3177       cast<CXXRecordDecl>(I)->DefinitionData = Data;
3178   }
3179 }
3180 
3181 void TagDecl::completeDefinition() {
3182   assert((!isa<CXXRecordDecl>(this) ||
3183           cast<CXXRecordDecl>(this)->hasDefinition()) &&
3184          "definition completed but not started");
3185 
3186   IsCompleteDefinition = true;
3187   IsBeingDefined = false;
3188 
3189   if (ASTMutationListener *L = getASTMutationListener())
3190     L->CompletedTagDefinition(this);
3191 }
3192 
3193 TagDecl *TagDecl::getDefinition() const {
3194   if (isCompleteDefinition())
3195     return const_cast<TagDecl *>(this);
3196 
3197   // If it's possible for us to have an out-of-date definition, check now.
3198   if (MayHaveOutOfDateDef) {
3199     if (IdentifierInfo *II = getIdentifier()) {
3200       if (II->isOutOfDate()) {
3201         updateOutOfDate(*II);
3202       }
3203     }
3204   }
3205 
3206   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
3207     return CXXRD->getDefinition();
3208 
3209   for (auto R : redecls())
3210     if (R->isCompleteDefinition())
3211       return R;
3212 
3213   return 0;
3214 }
3215 
3216 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3217   if (QualifierLoc) {
3218     // Make sure the extended qualifier info is allocated.
3219     if (!hasExtInfo())
3220       NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3221     // Set qualifier info.
3222     getExtInfo()->QualifierLoc = QualifierLoc;
3223   } else {
3224     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3225     if (hasExtInfo()) {
3226       if (getExtInfo()->NumTemplParamLists == 0) {
3227         getASTContext().Deallocate(getExtInfo());
3228         NamedDeclOrQualifier = (TypedefNameDecl*) 0;
3229       }
3230       else
3231         getExtInfo()->QualifierLoc = QualifierLoc;
3232     }
3233   }
3234 }
3235 
3236 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
3237                                             unsigned NumTPLists,
3238                                             TemplateParameterList **TPLists) {
3239   assert(NumTPLists > 0);
3240   // Make sure the extended decl info is allocated.
3241   if (!hasExtInfo())
3242     // Allocate external info struct.
3243     NamedDeclOrQualifier = new (getASTContext()) ExtInfo;
3244   // Set the template parameter lists info.
3245   getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
3246 }
3247 
3248 //===----------------------------------------------------------------------===//
3249 // EnumDecl Implementation
3250 //===----------------------------------------------------------------------===//
3251 
3252 void EnumDecl::anchor() { }
3253 
3254 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3255                            SourceLocation StartLoc, SourceLocation IdLoc,
3256                            IdentifierInfo *Id,
3257                            EnumDecl *PrevDecl, bool IsScoped,
3258                            bool IsScopedUsingClassTag, bool IsFixed) {
3259   EnumDecl *Enum = new (C, DC) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
3260                                         IsScoped, IsScopedUsingClassTag,
3261                                         IsFixed);
3262   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3263   C.getTypeDeclType(Enum, PrevDecl);
3264   return Enum;
3265 }
3266 
3267 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3268   EnumDecl *Enum = new (C, ID) EnumDecl(0, SourceLocation(), SourceLocation(),
3269                                         0, 0, false, false, false);
3270   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3271   return Enum;
3272 }
3273 
3274 SourceRange EnumDecl::getIntegerTypeRange() const {
3275   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3276     return TI->getTypeLoc().getSourceRange();
3277   return SourceRange();
3278 }
3279 
3280 void EnumDecl::completeDefinition(QualType NewType,
3281                                   QualType NewPromotionType,
3282                                   unsigned NumPositiveBits,
3283                                   unsigned NumNegativeBits) {
3284   assert(!isCompleteDefinition() && "Cannot redefine enums!");
3285   if (!IntegerType)
3286     IntegerType = NewType.getTypePtr();
3287   PromotionType = NewPromotionType;
3288   setNumPositiveBits(NumPositiveBits);
3289   setNumNegativeBits(NumNegativeBits);
3290   TagDecl::completeDefinition();
3291 }
3292 
3293 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3294   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3295     return MSI->getTemplateSpecializationKind();
3296 
3297   return TSK_Undeclared;
3298 }
3299 
3300 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3301                                          SourceLocation PointOfInstantiation) {
3302   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3303   assert(MSI && "Not an instantiated member enumeration?");
3304   MSI->setTemplateSpecializationKind(TSK);
3305   if (TSK != TSK_ExplicitSpecialization &&
3306       PointOfInstantiation.isValid() &&
3307       MSI->getPointOfInstantiation().isInvalid())
3308     MSI->setPointOfInstantiation(PointOfInstantiation);
3309 }
3310 
3311 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3312   if (SpecializationInfo)
3313     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3314 
3315   return 0;
3316 }
3317 
3318 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3319                                             TemplateSpecializationKind TSK) {
3320   assert(!SpecializationInfo && "Member enum is already a specialization");
3321   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3322 }
3323 
3324 //===----------------------------------------------------------------------===//
3325 // RecordDecl Implementation
3326 //===----------------------------------------------------------------------===//
3327 
3328 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
3329                        SourceLocation StartLoc, SourceLocation IdLoc,
3330                        IdentifierInfo *Id, RecordDecl *PrevDecl)
3331   : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
3332   HasFlexibleArrayMember = false;
3333   AnonymousStructOrUnion = false;
3334   HasObjectMember = false;
3335   HasVolatileMember = false;
3336   LoadedFieldsFromExternalStorage = false;
3337   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3338 }
3339 
3340 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3341                                SourceLocation StartLoc, SourceLocation IdLoc,
3342                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
3343   RecordDecl* R = new (C, DC) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
3344                                          PrevDecl);
3345   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3346 
3347   C.getTypeDeclType(R, PrevDecl);
3348   return R;
3349 }
3350 
3351 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3352   RecordDecl *R = new (C, ID) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
3353                                          SourceLocation(), 0, 0);
3354   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3355   return R;
3356 }
3357 
3358 bool RecordDecl::isInjectedClassName() const {
3359   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3360     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3361 }
3362 
3363 RecordDecl::field_iterator RecordDecl::field_begin() const {
3364   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3365     LoadFieldsFromExternalStorage();
3366 
3367   return field_iterator(decl_iterator(FirstDecl));
3368 }
3369 
3370 /// completeDefinition - Notes that the definition of this type is now
3371 /// complete.
3372 void RecordDecl::completeDefinition() {
3373   assert(!isCompleteDefinition() && "Cannot redefine record!");
3374   TagDecl::completeDefinition();
3375 }
3376 
3377 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3378 /// This which can be turned on with an attribute, pragma, or the
3379 /// -mms-bitfields command-line option.
3380 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3381   return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1;
3382 }
3383 
3384 static bool isFieldOrIndirectField(Decl::Kind K) {
3385   return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3386 }
3387 
3388 void RecordDecl::LoadFieldsFromExternalStorage() const {
3389   ExternalASTSource *Source = getASTContext().getExternalSource();
3390   assert(hasExternalLexicalStorage() && Source && "No external storage?");
3391 
3392   // Notify that we have a RecordDecl doing some initialization.
3393   ExternalASTSource::Deserializing TheFields(Source);
3394 
3395   SmallVector<Decl*, 64> Decls;
3396   LoadedFieldsFromExternalStorage = true;
3397   switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField,
3398                                            Decls)) {
3399   case ELR_Success:
3400     break;
3401 
3402   case ELR_AlreadyLoaded:
3403   case ELR_Failure:
3404     return;
3405   }
3406 
3407 #ifndef NDEBUG
3408   // Check that all decls we got were FieldDecls.
3409   for (unsigned i=0, e=Decls.size(); i != e; ++i)
3410     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3411 #endif
3412 
3413   if (Decls.empty())
3414     return;
3415 
3416   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3417                                                  /*FieldsAlreadyLoaded=*/false);
3418 }
3419 
3420 //===----------------------------------------------------------------------===//
3421 // BlockDecl Implementation
3422 //===----------------------------------------------------------------------===//
3423 
3424 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3425   assert(ParamInfo == 0 && "Already has param info!");
3426 
3427   // Zero params -> null pointer.
3428   if (!NewParamInfo.empty()) {
3429     NumParams = NewParamInfo.size();
3430     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3431     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3432   }
3433 }
3434 
3435 void BlockDecl::setCaptures(ASTContext &Context,
3436                             const Capture *begin,
3437                             const Capture *end,
3438                             bool capturesCXXThis) {
3439   CapturesCXXThis = capturesCXXThis;
3440 
3441   if (begin == end) {
3442     NumCaptures = 0;
3443     Captures = 0;
3444     return;
3445   }
3446 
3447   NumCaptures = end - begin;
3448 
3449   // Avoid new Capture[] because we don't want to provide a default
3450   // constructor.
3451   size_t allocationSize = NumCaptures * sizeof(Capture);
3452   void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
3453   memcpy(buffer, begin, allocationSize);
3454   Captures = static_cast<Capture*>(buffer);
3455 }
3456 
3457 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3458   for (capture_const_iterator
3459          i = capture_begin(), e = capture_end(); i != e; ++i)
3460     // Only auto vars can be captured, so no redeclaration worries.
3461     if (i->getVariable() == variable)
3462       return true;
3463 
3464   return false;
3465 }
3466 
3467 SourceRange BlockDecl::getSourceRange() const {
3468   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3469 }
3470 
3471 //===----------------------------------------------------------------------===//
3472 // Other Decl Allocation/Deallocation Method Implementations
3473 //===----------------------------------------------------------------------===//
3474 
3475 void TranslationUnitDecl::anchor() { }
3476 
3477 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3478   return new (C, (DeclContext*)0) TranslationUnitDecl(C);
3479 }
3480 
3481 void LabelDecl::anchor() { }
3482 
3483 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3484                              SourceLocation IdentL, IdentifierInfo *II) {
3485   return new (C, DC) LabelDecl(DC, IdentL, II, 0, IdentL);
3486 }
3487 
3488 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3489                              SourceLocation IdentL, IdentifierInfo *II,
3490                              SourceLocation GnuLabelL) {
3491   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3492   return new (C, DC) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
3493 }
3494 
3495 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3496   return new (C, ID) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
3497 }
3498 
3499 void ValueDecl::anchor() { }
3500 
3501 bool ValueDecl::isWeak() const {
3502   for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I)
3503     if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I))
3504       return true;
3505 
3506   return isWeakImported();
3507 }
3508 
3509 void ImplicitParamDecl::anchor() { }
3510 
3511 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
3512                                              SourceLocation IdLoc,
3513                                              IdentifierInfo *Id,
3514                                              QualType Type) {
3515   return new (C, DC) ImplicitParamDecl(DC, IdLoc, Id, Type);
3516 }
3517 
3518 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
3519                                                          unsigned ID) {
3520   return new (C, ID) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
3521 }
3522 
3523 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
3524                                    SourceLocation StartLoc,
3525                                    const DeclarationNameInfo &NameInfo,
3526                                    QualType T, TypeSourceInfo *TInfo,
3527                                    StorageClass SC,
3528                                    bool isInlineSpecified,
3529                                    bool hasWrittenPrototype,
3530                                    bool isConstexprSpecified) {
3531   FunctionDecl *New =
3532       new (C, DC) FunctionDecl(Function, DC, StartLoc, NameInfo, T, TInfo, SC,
3533                                isInlineSpecified, isConstexprSpecified);
3534   New->HasWrittenPrototype = hasWrittenPrototype;
3535   return New;
3536 }
3537 
3538 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3539   return new (C, ID) FunctionDecl(Function, 0, SourceLocation(),
3540                                   DeclarationNameInfo(), QualType(), 0,
3541                                   SC_None, false, false);
3542 }
3543 
3544 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3545   return new (C, DC) BlockDecl(DC, L);
3546 }
3547 
3548 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3549   return new (C, ID) BlockDecl(0, SourceLocation());
3550 }
3551 
3552 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
3553                                    unsigned NumParams) {
3554   return new (C, DC, NumParams * sizeof(ImplicitParamDecl *))
3555       CapturedDecl(DC, NumParams);
3556 }
3557 
3558 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3559                                                unsigned NumParams) {
3560   return new (C, ID, NumParams * sizeof(ImplicitParamDecl *))
3561       CapturedDecl(0, NumParams);
3562 }
3563 
3564 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
3565                                            SourceLocation L,
3566                                            IdentifierInfo *Id, QualType T,
3567                                            Expr *E, const llvm::APSInt &V) {
3568   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
3569 }
3570 
3571 EnumConstantDecl *
3572 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3573   return new (C, ID) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
3574                                       llvm::APSInt());
3575 }
3576 
3577 void IndirectFieldDecl::anchor() { }
3578 
3579 IndirectFieldDecl *
3580 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
3581                           IdentifierInfo *Id, QualType T, NamedDecl **CH,
3582                           unsigned CHS) {
3583   return new (C, DC) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
3584 }
3585 
3586 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
3587                                                          unsigned ID) {
3588   return new (C, ID) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
3589                                        QualType(), 0, 0);
3590 }
3591 
3592 SourceRange EnumConstantDecl::getSourceRange() const {
3593   SourceLocation End = getLocation();
3594   if (Init)
3595     End = Init->getLocEnd();
3596   return SourceRange(getLocation(), End);
3597 }
3598 
3599 void TypeDecl::anchor() { }
3600 
3601 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
3602                                  SourceLocation StartLoc, SourceLocation IdLoc,
3603                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
3604   return new (C, DC) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
3605 }
3606 
3607 void TypedefNameDecl::anchor() { }
3608 
3609 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3610   return new (C, ID) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3611 }
3612 
3613 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
3614                                      SourceLocation StartLoc,
3615                                      SourceLocation IdLoc, IdentifierInfo *Id,
3616                                      TypeSourceInfo *TInfo) {
3617   return new (C, DC) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
3618 }
3619 
3620 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3621   return new (C, ID) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
3622 }
3623 
3624 SourceRange TypedefDecl::getSourceRange() const {
3625   SourceLocation RangeEnd = getLocation();
3626   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
3627     if (typeIsPostfix(TInfo->getType()))
3628       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3629   }
3630   return SourceRange(getLocStart(), RangeEnd);
3631 }
3632 
3633 SourceRange TypeAliasDecl::getSourceRange() const {
3634   SourceLocation RangeEnd = getLocStart();
3635   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
3636     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
3637   return SourceRange(getLocStart(), RangeEnd);
3638 }
3639 
3640 void FileScopeAsmDecl::anchor() { }
3641 
3642 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
3643                                            StringLiteral *Str,
3644                                            SourceLocation AsmLoc,
3645                                            SourceLocation RParenLoc) {
3646   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
3647 }
3648 
3649 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
3650                                                        unsigned ID) {
3651   return new (C, ID) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
3652 }
3653 
3654 void EmptyDecl::anchor() {}
3655 
3656 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
3657   return new (C, DC) EmptyDecl(DC, L);
3658 }
3659 
3660 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3661   return new (C, ID) EmptyDecl(0, SourceLocation());
3662 }
3663 
3664 //===----------------------------------------------------------------------===//
3665 // ImportDecl Implementation
3666 //===----------------------------------------------------------------------===//
3667 
3668 /// \brief Retrieve the number of module identifiers needed to name the given
3669 /// module.
3670 static unsigned getNumModuleIdentifiers(Module *Mod) {
3671   unsigned Result = 1;
3672   while (Mod->Parent) {
3673     Mod = Mod->Parent;
3674     ++Result;
3675   }
3676   return Result;
3677 }
3678 
3679 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3680                        Module *Imported,
3681                        ArrayRef<SourceLocation> IdentifierLocs)
3682   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3683     NextLocalImport()
3684 {
3685   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3686   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3687   memcpy(StoredLocs, IdentifierLocs.data(),
3688          IdentifierLocs.size() * sizeof(SourceLocation));
3689 }
3690 
3691 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3692                        Module *Imported, SourceLocation EndLoc)
3693   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3694     NextLocalImport()
3695 {
3696   *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3697 }
3698 
3699 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3700                                SourceLocation StartLoc, Module *Imported,
3701                                ArrayRef<SourceLocation> IdentifierLocs) {
3702   return new (C, DC, IdentifierLocs.size() * sizeof(SourceLocation))
3703       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3704 }
3705 
3706 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3707                                        SourceLocation StartLoc,
3708                                        Module *Imported,
3709                                        SourceLocation EndLoc) {
3710   ImportDecl *Import =
3711       new (C, DC, sizeof(SourceLocation)) ImportDecl(DC, StartLoc,
3712                                                      Imported, EndLoc);
3713   Import->setImplicit();
3714   return Import;
3715 }
3716 
3717 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3718                                            unsigned NumLocations) {
3719   return new (C, ID, NumLocations * sizeof(SourceLocation))
3720       ImportDecl(EmptyShell());
3721 }
3722 
3723 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3724   if (!ImportedAndComplete.getInt())
3725     return None;
3726 
3727   const SourceLocation *StoredLocs
3728     = reinterpret_cast<const SourceLocation *>(this + 1);
3729   return ArrayRef<SourceLocation>(StoredLocs,
3730                                   getNumModuleIdentifiers(getImportedModule()));
3731 }
3732 
3733 SourceRange ImportDecl::getSourceRange() const {
3734   if (!ImportedAndComplete.getInt())
3735     return SourceRange(getLocation(),
3736                        *reinterpret_cast<const SourceLocation *>(this + 1));
3737 
3738   return SourceRange(getLocation(), getIdentifierLocs().back());
3739 }
3740