SemaTemplateInstantiateDecl.cpp revision 57907e56191adea0fa870c052054eb0fe0c4681f
1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
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//  This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "clang/Sema/SemaInternal.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
17#include "clang/AST/DependentDiagnostic.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/TypeLoc.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
25
26using namespace clang;
27
28static bool isDeclWithinFunction(const Decl *D) {
29  const DeclContext *DC = D->getDeclContext();
30  if (DC->isFunctionOrMethod())
31    return true;
32
33  if (DC->isRecord())
34    return cast<CXXRecordDecl>(DC)->isLocalClass();
35
36  return false;
37}
38
39bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
40                                              DeclaratorDecl *NewDecl) {
41  if (!OldDecl->getQualifierLoc())
42    return false;
43
44  NestedNameSpecifierLoc NewQualifierLoc
45    = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
46                                          TemplateArgs);
47
48  if (!NewQualifierLoc)
49    return true;
50
51  NewDecl->setQualifierInfo(NewQualifierLoc);
52  return false;
53}
54
55bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
56                                              TagDecl *NewDecl) {
57  if (!OldDecl->getQualifierLoc())
58    return false;
59
60  NestedNameSpecifierLoc NewQualifierLoc
61  = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
62                                        TemplateArgs);
63
64  if (!NewQualifierLoc)
65    return true;
66
67  NewDecl->setQualifierInfo(NewQualifierLoc);
68  return false;
69}
70
71// Include attribute instantiation code.
72#include "clang/Sema/AttrTemplateInstantiate.inc"
73
74static void instantiateDependentAlignedAttr(
75    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
76    const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
77  if (Aligned->isAlignmentExpr()) {
78    // The alignment expression is a constant expression.
79    EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
80    ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
81    if (!Result.isInvalid())
82      S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83                       Aligned->getSpellingListIndex(), IsPackExpansion);
84  } else {
85    TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
86                                         TemplateArgs, Aligned->getLocation(),
87                                         DeclarationName());
88    if (Result)
89      S.AddAlignedAttr(Aligned->getLocation(), New, Result,
90                       Aligned->getSpellingListIndex(), IsPackExpansion);
91  }
92}
93
94static void instantiateDependentAlignedAttr(
95    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
96    const AlignedAttr *Aligned, Decl *New) {
97  if (!Aligned->isPackExpansion()) {
98    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
99    return;
100  }
101
102  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
103  if (Aligned->isAlignmentExpr())
104    S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
105                                      Unexpanded);
106  else
107    S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
108                                      Unexpanded);
109  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
110
111  // Determine whether we can expand this attribute pack yet.
112  bool Expand = true, RetainExpansion = false;
113  Optional<unsigned> NumExpansions;
114  // FIXME: Use the actual location of the ellipsis.
115  SourceLocation EllipsisLoc = Aligned->getLocation();
116  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
117                                        Unexpanded, TemplateArgs, Expand,
118                                        RetainExpansion, NumExpansions))
119    return;
120
121  if (!Expand) {
122    Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
123    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
124  } else {
125    for (unsigned I = 0; I != *NumExpansions; ++I) {
126      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
127      instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
128    }
129  }
130}
131
132void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
133                            const Decl *Tmpl, Decl *New,
134                            LateInstantiatedAttrVec *LateAttrs,
135                            LocalInstantiationScope *OuterMostScope) {
136  for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
137       i != e; ++i) {
138    const Attr *TmplAttr = *i;
139
140    // FIXME: This should be generalized to more than just the AlignedAttr.
141    const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
142    if (Aligned && Aligned->isAlignmentDependent()) {
143      instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
144      continue;
145    }
146
147    assert(!TmplAttr->isPackExpansion());
148    if (TmplAttr->isLateParsed() && LateAttrs) {
149      // Late parsed attributes must be instantiated and attached after the
150      // enclosing class has been instantiated.  See Sema::InstantiateClass.
151      LocalInstantiationScope *Saved = 0;
152      if (CurrentInstantiationScope)
153        Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
154      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
155    } else {
156      // Allow 'this' within late-parsed attributes.
157      NamedDecl *ND = dyn_cast<NamedDecl>(New);
158      CXXRecordDecl *ThisContext =
159          dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
160      CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
161                                 ND && ND->isCXXInstanceMember());
162
163      Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
164                                                         *this, TemplateArgs);
165      if (NewAttr)
166        New->addAttr(NewAttr);
167    }
168  }
169}
170
171Decl *
172TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
173  llvm_unreachable("Translation units cannot be instantiated");
174}
175
176Decl *
177TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
178  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
179                                      D->getIdentifier());
180  Owner->addDecl(Inst);
181  return Inst;
182}
183
184Decl *
185TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
186  llvm_unreachable("Namespaces cannot be instantiated");
187}
188
189Decl *
190TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
191  NamespaceAliasDecl *Inst
192    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
193                                 D->getNamespaceLoc(),
194                                 D->getAliasLoc(),
195                                 D->getIdentifier(),
196                                 D->getQualifierLoc(),
197                                 D->getTargetNameLoc(),
198                                 D->getNamespace());
199  Owner->addDecl(Inst);
200  return Inst;
201}
202
203Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
204                                                           bool IsTypeAlias) {
205  bool Invalid = false;
206  TypeSourceInfo *DI = D->getTypeSourceInfo();
207  if (DI->getType()->isInstantiationDependentType() ||
208      DI->getType()->isVariablyModifiedType()) {
209    DI = SemaRef.SubstType(DI, TemplateArgs,
210                           D->getLocation(), D->getDeclName());
211    if (!DI) {
212      Invalid = true;
213      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
214    }
215  } else {
216    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
217  }
218
219  // HACK: g++ has a bug where it gets the value kind of ?: wrong.
220  // libstdc++ relies upon this bug in its implementation of common_type.
221  // If we happen to be processing that implementation, fake up the g++ ?:
222  // semantics. See LWG issue 2141 for more information on the bug.
223  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
224  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
225  if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
226      DT->isReferenceType() &&
227      RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
228      RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
229      D->getIdentifier() && D->getIdentifier()->isStr("type") &&
230      SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
231    // Fold it to the (non-reference) type which g++ would have produced.
232    DI = SemaRef.Context.getTrivialTypeSourceInfo(
233      DI->getType().getNonReferenceType());
234
235  // Create the new typedef
236  TypedefNameDecl *Typedef;
237  if (IsTypeAlias)
238    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
239                                    D->getLocation(), D->getIdentifier(), DI);
240  else
241    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
242                                  D->getLocation(), D->getIdentifier(), DI);
243  if (Invalid)
244    Typedef->setInvalidDecl();
245
246  // If the old typedef was the name for linkage purposes of an anonymous
247  // tag decl, re-establish that relationship for the new typedef.
248  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
249    TagDecl *oldTag = oldTagType->getDecl();
250    if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
251      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
252      assert(!newTag->hasNameForLinkage());
253      newTag->setTypedefNameForAnonDecl(Typedef);
254    }
255  }
256
257  if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
258    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
259                                                       TemplateArgs);
260    if (!InstPrev)
261      return 0;
262
263    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
264
265    // If the typedef types are not identical, reject them.
266    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
267
268    Typedef->setPreviousDecl(InstPrevTypedef);
269  }
270
271  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
272
273  Typedef->setAccess(D->getAccess());
274
275  return Typedef;
276}
277
278Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
279  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
280  Owner->addDecl(Typedef);
281  return Typedef;
282}
283
284Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
285  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
286  Owner->addDecl(Typedef);
287  return Typedef;
288}
289
290Decl *
291TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
292  // Create a local instantiation scope for this type alias template, which
293  // will contain the instantiations of the template parameters.
294  LocalInstantiationScope Scope(SemaRef);
295
296  TemplateParameterList *TempParams = D->getTemplateParameters();
297  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
298  if (!InstParams)
299    return 0;
300
301  TypeAliasDecl *Pattern = D->getTemplatedDecl();
302
303  TypeAliasTemplateDecl *PrevAliasTemplate = 0;
304  if (Pattern->getPreviousDecl()) {
305    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
306    if (!Found.empty()) {
307      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
308    }
309  }
310
311  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
312    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
313  if (!AliasInst)
314    return 0;
315
316  TypeAliasTemplateDecl *Inst
317    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
318                                    D->getDeclName(), InstParams, AliasInst);
319  if (PrevAliasTemplate)
320    Inst->setPreviousDecl(PrevAliasTemplate);
321
322  Inst->setAccess(D->getAccess());
323
324  if (!PrevAliasTemplate)
325    Inst->setInstantiatedFromMemberTemplate(D);
326
327  Owner->addDecl(Inst);
328
329  return Inst;
330}
331
332Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
333  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
334}
335
336Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
337                                             bool InstantiatingVarTemplate) {
338
339  // If this is the variable for an anonymous struct or union,
340  // instantiate the anonymous struct/union type first.
341  if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
342    if (RecordTy->getDecl()->isAnonymousStructOrUnion())
343      if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
344        return 0;
345
346  // Do substitution on the type of the declaration
347  TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
348                                         TemplateArgs,
349                                         D->getTypeSpecStartLoc(),
350                                         D->getDeclName());
351  if (!DI)
352    return 0;
353
354  if (DI->getType()->isFunctionType()) {
355    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
356      << D->isStaticDataMember() << DI->getType();
357    return 0;
358  }
359
360  DeclContext *DC = Owner;
361  if (D->isLocalExternDecl())
362    SemaRef.adjustContextForLocalExternDecl(DC);
363
364  // Build the instantiated declaration.
365  VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
366                                 D->getLocation(), D->getIdentifier(),
367                                 DI->getType(), DI, D->getStorageClass());
368
369  // In ARC, infer 'retaining' for variables of retainable type.
370  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
371      SemaRef.inferObjCARCLifetime(Var))
372    Var->setInvalidDecl();
373
374  // Substitute the nested name specifier, if any.
375  if (SubstQualifier(D, Var))
376    return 0;
377
378  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
379                                     StartingScope, InstantiatingVarTemplate);
380  return Var;
381}
382
383Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
384  AccessSpecDecl* AD
385    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
386                             D->getAccessSpecifierLoc(), D->getColonLoc());
387  Owner->addHiddenDecl(AD);
388  return AD;
389}
390
391Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
392  bool Invalid = false;
393  TypeSourceInfo *DI = D->getTypeSourceInfo();
394  if (DI->getType()->isInstantiationDependentType() ||
395      DI->getType()->isVariablyModifiedType())  {
396    DI = SemaRef.SubstType(DI, TemplateArgs,
397                           D->getLocation(), D->getDeclName());
398    if (!DI) {
399      DI = D->getTypeSourceInfo();
400      Invalid = true;
401    } else if (DI->getType()->isFunctionType()) {
402      // C++ [temp.arg.type]p3:
403      //   If a declaration acquires a function type through a type
404      //   dependent on a template-parameter and this causes a
405      //   declaration that does not use the syntactic form of a
406      //   function declarator to have function type, the program is
407      //   ill-formed.
408      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
409        << DI->getType();
410      Invalid = true;
411    }
412  } else {
413    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
414  }
415
416  Expr *BitWidth = D->getBitWidth();
417  if (Invalid)
418    BitWidth = 0;
419  else if (BitWidth) {
420    // The bit-width expression is a constant expression.
421    EnterExpressionEvaluationContext Unevaluated(SemaRef,
422                                                 Sema::ConstantEvaluated);
423
424    ExprResult InstantiatedBitWidth
425      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
426    if (InstantiatedBitWidth.isInvalid()) {
427      Invalid = true;
428      BitWidth = 0;
429    } else
430      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
431  }
432
433  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
434                                            DI->getType(), DI,
435                                            cast<RecordDecl>(Owner),
436                                            D->getLocation(),
437                                            D->isMutable(),
438                                            BitWidth,
439                                            D->getInClassInitStyle(),
440                                            D->getInnerLocStart(),
441                                            D->getAccess(),
442                                            0);
443  if (!Field) {
444    cast<Decl>(Owner)->setInvalidDecl();
445    return 0;
446  }
447
448  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
449
450  if (Field->hasAttrs())
451    SemaRef.CheckAlignasUnderalignment(Field);
452
453  if (Invalid)
454    Field->setInvalidDecl();
455
456  if (!Field->getDeclName()) {
457    // Keep track of where this decl came from.
458    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
459  }
460  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
461    if (Parent->isAnonymousStructOrUnion() &&
462        Parent->getRedeclContext()->isFunctionOrMethod())
463      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
464  }
465
466  Field->setImplicit(D->isImplicit());
467  Field->setAccess(D->getAccess());
468  Owner->addDecl(Field);
469
470  return Field;
471}
472
473Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
474  bool Invalid = false;
475  TypeSourceInfo *DI = D->getTypeSourceInfo();
476
477  if (DI->getType()->isVariablyModifiedType()) {
478    SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
479    << D->getName();
480    Invalid = true;
481  } else if (DI->getType()->isInstantiationDependentType())  {
482    DI = SemaRef.SubstType(DI, TemplateArgs,
483                           D->getLocation(), D->getDeclName());
484    if (!DI) {
485      DI = D->getTypeSourceInfo();
486      Invalid = true;
487    } else if (DI->getType()->isFunctionType()) {
488      // C++ [temp.arg.type]p3:
489      //   If a declaration acquires a function type through a type
490      //   dependent on a template-parameter and this causes a
491      //   declaration that does not use the syntactic form of a
492      //   function declarator to have function type, the program is
493      //   ill-formed.
494      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
495      << DI->getType();
496      Invalid = true;
497    }
498  } else {
499    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
500  }
501
502  MSPropertyDecl *Property = new (SemaRef.Context)
503      MSPropertyDecl(Owner, D->getLocation(),
504                     D->getDeclName(), DI->getType(), DI,
505                     D->getLocStart(),
506                     D->getGetterId(), D->getSetterId());
507
508  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
509                           StartingScope);
510
511  if (Invalid)
512    Property->setInvalidDecl();
513
514  Property->setAccess(D->getAccess());
515  Owner->addDecl(Property);
516
517  return Property;
518}
519
520Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
521  NamedDecl **NamedChain =
522    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
523
524  int i = 0;
525  for (IndirectFieldDecl::chain_iterator PI =
526       D->chain_begin(), PE = D->chain_end();
527       PI != PE; ++PI) {
528    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
529                                              TemplateArgs);
530    if (!Next)
531      return 0;
532
533    NamedChain[i++] = Next;
534  }
535
536  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
537  IndirectFieldDecl* IndirectField
538    = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
539                                D->getIdentifier(), T,
540                                NamedChain, D->getChainingSize());
541
542
543  IndirectField->setImplicit(D->isImplicit());
544  IndirectField->setAccess(D->getAccess());
545  Owner->addDecl(IndirectField);
546  return IndirectField;
547}
548
549Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
550  // Handle friend type expressions by simply substituting template
551  // parameters into the pattern type and checking the result.
552  if (TypeSourceInfo *Ty = D->getFriendType()) {
553    TypeSourceInfo *InstTy;
554    // If this is an unsupported friend, don't bother substituting template
555    // arguments into it. The actual type referred to won't be used by any
556    // parts of Clang, and may not be valid for instantiating. Just use the
557    // same info for the instantiated friend.
558    if (D->isUnsupportedFriend()) {
559      InstTy = Ty;
560    } else {
561      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
562                                 D->getLocation(), DeclarationName());
563    }
564    if (!InstTy)
565      return 0;
566
567    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
568                                                 D->getFriendLoc(), InstTy);
569    if (!FD)
570      return 0;
571
572    FD->setAccess(AS_public);
573    FD->setUnsupportedFriend(D->isUnsupportedFriend());
574    Owner->addDecl(FD);
575    return FD;
576  }
577
578  NamedDecl *ND = D->getFriendDecl();
579  assert(ND && "friend decl must be a decl or a type!");
580
581  // All of the Visit implementations for the various potential friend
582  // declarations have to be carefully written to work for friend
583  // objects, with the most important detail being that the target
584  // decl should almost certainly not be placed in Owner.
585  Decl *NewND = Visit(ND);
586  if (!NewND) return 0;
587
588  FriendDecl *FD =
589    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
590                       cast<NamedDecl>(NewND), D->getFriendLoc());
591  FD->setAccess(AS_public);
592  FD->setUnsupportedFriend(D->isUnsupportedFriend());
593  Owner->addDecl(FD);
594  return FD;
595}
596
597Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
598  Expr *AssertExpr = D->getAssertExpr();
599
600  // The expression in a static assertion is a constant expression.
601  EnterExpressionEvaluationContext Unevaluated(SemaRef,
602                                               Sema::ConstantEvaluated);
603
604  ExprResult InstantiatedAssertExpr
605    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
606  if (InstantiatedAssertExpr.isInvalid())
607    return 0;
608
609  return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
610                                              InstantiatedAssertExpr.get(),
611                                              D->getMessage(),
612                                              D->getRParenLoc(),
613                                              D->isFailed());
614}
615
616Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
617  EnumDecl *PrevDecl = 0;
618  if (D->getPreviousDecl()) {
619    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
620                                                   D->getPreviousDecl(),
621                                                   TemplateArgs);
622    if (!Prev) return 0;
623    PrevDecl = cast<EnumDecl>(Prev);
624  }
625
626  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
627                                    D->getLocation(), D->getIdentifier(),
628                                    PrevDecl, D->isScoped(),
629                                    D->isScopedUsingClassTag(), D->isFixed());
630  if (D->isFixed()) {
631    if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
632      // If we have type source information for the underlying type, it means it
633      // has been explicitly set by the user. Perform substitution on it before
634      // moving on.
635      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
636      TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
637                                                DeclarationName());
638      if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
639        Enum->setIntegerType(SemaRef.Context.IntTy);
640      else
641        Enum->setIntegerTypeSourceInfo(NewTI);
642    } else {
643      assert(!D->getIntegerType()->isDependentType()
644             && "Dependent type without type source info");
645      Enum->setIntegerType(D->getIntegerType());
646    }
647  }
648
649  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
650
651  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
652  Enum->setAccess(D->getAccess());
653  if (SubstQualifier(D, Enum)) return 0;
654  Owner->addDecl(Enum);
655
656  EnumDecl *Def = D->getDefinition();
657  if (Def && Def != D) {
658    // If this is an out-of-line definition of an enum member template, check
659    // that the underlying types match in the instantiation of both
660    // declarations.
661    if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
662      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
663      QualType DefnUnderlying =
664        SemaRef.SubstType(TI->getType(), TemplateArgs,
665                          UnderlyingLoc, DeclarationName());
666      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
667                                     DefnUnderlying, Enum);
668    }
669  }
670
671  // C++11 [temp.inst]p1: The implicit instantiation of a class template
672  // specialization causes the implicit instantiation of the declarations, but
673  // not the definitions of scoped member enumerations.
674  //
675  // DR1484 clarifies that enumeration definitions inside of a template
676  // declaration aren't considered entities that can be separately instantiated
677  // from the rest of the entity they are declared inside of.
678  if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
679    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
680    InstantiateEnumDefinition(Enum, Def);
681  }
682
683  return Enum;
684}
685
686void TemplateDeclInstantiator::InstantiateEnumDefinition(
687    EnumDecl *Enum, EnumDecl *Pattern) {
688  Enum->startDefinition();
689
690  // Update the location to refer to the definition.
691  Enum->setLocation(Pattern->getLocation());
692
693  SmallVector<Decl*, 4> Enumerators;
694
695  EnumConstantDecl *LastEnumConst = 0;
696  for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
697         ECEnd = Pattern->enumerator_end();
698       EC != ECEnd; ++EC) {
699    // The specified value for the enumerator.
700    ExprResult Value = SemaRef.Owned((Expr *)0);
701    if (Expr *UninstValue = EC->getInitExpr()) {
702      // The enumerator's value expression is a constant expression.
703      EnterExpressionEvaluationContext Unevaluated(SemaRef,
704                                                   Sema::ConstantEvaluated);
705
706      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
707    }
708
709    // Drop the initial value and continue.
710    bool isInvalid = false;
711    if (Value.isInvalid()) {
712      Value = SemaRef.Owned((Expr *)0);
713      isInvalid = true;
714    }
715
716    EnumConstantDecl *EnumConst
717      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
718                                  EC->getLocation(), EC->getIdentifier(),
719                                  Value.get());
720
721    if (isInvalid) {
722      if (EnumConst)
723        EnumConst->setInvalidDecl();
724      Enum->setInvalidDecl();
725    }
726
727    if (EnumConst) {
728      SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
729
730      EnumConst->setAccess(Enum->getAccess());
731      Enum->addDecl(EnumConst);
732      Enumerators.push_back(EnumConst);
733      LastEnumConst = EnumConst;
734
735      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
736          !Enum->isScoped()) {
737        // If the enumeration is within a function or method, record the enum
738        // constant as a local.
739        SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
740      }
741    }
742  }
743
744  // FIXME: Fixup LBraceLoc
745  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
746                        Enum->getRBraceLoc(), Enum,
747                        Enumerators,
748                        0, 0);
749}
750
751Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
752  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
753}
754
755Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
756  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
757
758  // Create a local instantiation scope for this class template, which
759  // will contain the instantiations of the template parameters.
760  LocalInstantiationScope Scope(SemaRef);
761  TemplateParameterList *TempParams = D->getTemplateParameters();
762  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
763  if (!InstParams)
764    return NULL;
765
766  CXXRecordDecl *Pattern = D->getTemplatedDecl();
767
768  // Instantiate the qualifier.  We have to do this first in case
769  // we're a friend declaration, because if we are then we need to put
770  // the new declaration in the appropriate context.
771  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
772  if (QualifierLoc) {
773    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
774                                                       TemplateArgs);
775    if (!QualifierLoc)
776      return 0;
777  }
778
779  CXXRecordDecl *PrevDecl = 0;
780  ClassTemplateDecl *PrevClassTemplate = 0;
781
782  if (!isFriend && Pattern->getPreviousDecl()) {
783    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
784    if (!Found.empty()) {
785      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
786      if (PrevClassTemplate)
787        PrevDecl = PrevClassTemplate->getTemplatedDecl();
788    }
789  }
790
791  // If this isn't a friend, then it's a member template, in which
792  // case we just want to build the instantiation in the
793  // specialization.  If it is a friend, we want to build it in
794  // the appropriate context.
795  DeclContext *DC = Owner;
796  if (isFriend) {
797    if (QualifierLoc) {
798      CXXScopeSpec SS;
799      SS.Adopt(QualifierLoc);
800      DC = SemaRef.computeDeclContext(SS);
801      if (!DC) return 0;
802    } else {
803      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
804                                           Pattern->getDeclContext(),
805                                           TemplateArgs);
806    }
807
808    // Look for a previous declaration of the template in the owning
809    // context.
810    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
811                   Sema::LookupOrdinaryName, Sema::ForRedeclaration);
812    SemaRef.LookupQualifiedName(R, DC);
813
814    if (R.isSingleResult()) {
815      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
816      if (PrevClassTemplate)
817        PrevDecl = PrevClassTemplate->getTemplatedDecl();
818    }
819
820    if (!PrevClassTemplate && QualifierLoc) {
821      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
822        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
823        << QualifierLoc.getSourceRange();
824      return 0;
825    }
826
827    bool AdoptedPreviousTemplateParams = false;
828    if (PrevClassTemplate) {
829      bool Complain = true;
830
831      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
832      // template for struct std::tr1::__detail::_Map_base, where the
833      // template parameters of the friend declaration don't match the
834      // template parameters of the original declaration. In this one
835      // case, we don't complain about the ill-formed friend
836      // declaration.
837      if (isFriend && Pattern->getIdentifier() &&
838          Pattern->getIdentifier()->isStr("_Map_base") &&
839          DC->isNamespace() &&
840          cast<NamespaceDecl>(DC)->getIdentifier() &&
841          cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
842        DeclContext *DCParent = DC->getParent();
843        if (DCParent->isNamespace() &&
844            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
845            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
846          DeclContext *DCParent2 = DCParent->getParent();
847          if (DCParent2->isNamespace() &&
848              cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
849              cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
850              DCParent2->getParent()->isTranslationUnit())
851            Complain = false;
852        }
853      }
854
855      TemplateParameterList *PrevParams
856        = PrevClassTemplate->getTemplateParameters();
857
858      // Make sure the parameter lists match.
859      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
860                                                  Complain,
861                                                  Sema::TPL_TemplateMatch)) {
862        if (Complain)
863          return 0;
864
865        AdoptedPreviousTemplateParams = true;
866        InstParams = PrevParams;
867      }
868
869      // Do some additional validation, then merge default arguments
870      // from the existing declarations.
871      if (!AdoptedPreviousTemplateParams &&
872          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
873                                             Sema::TPC_ClassTemplate))
874        return 0;
875    }
876  }
877
878  CXXRecordDecl *RecordInst
879    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
880                            Pattern->getLocStart(), Pattern->getLocation(),
881                            Pattern->getIdentifier(), PrevDecl,
882                            /*DelayTypeCreation=*/true);
883
884  if (QualifierLoc)
885    RecordInst->setQualifierInfo(QualifierLoc);
886
887  ClassTemplateDecl *Inst
888    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
889                                D->getIdentifier(), InstParams, RecordInst,
890                                PrevClassTemplate);
891  RecordInst->setDescribedClassTemplate(Inst);
892
893  if (isFriend) {
894    if (PrevClassTemplate)
895      Inst->setAccess(PrevClassTemplate->getAccess());
896    else
897      Inst->setAccess(D->getAccess());
898
899    Inst->setObjectOfFriendDecl();
900    // TODO: do we want to track the instantiation progeny of this
901    // friend target decl?
902  } else {
903    Inst->setAccess(D->getAccess());
904    if (!PrevClassTemplate)
905      Inst->setInstantiatedFromMemberTemplate(D);
906  }
907
908  // Trigger creation of the type for the instantiation.
909  SemaRef.Context.getInjectedClassNameType(RecordInst,
910                                    Inst->getInjectedClassNameSpecialization());
911
912  // Finish handling of friends.
913  if (isFriend) {
914    DC->makeDeclVisibleInContext(Inst);
915    Inst->setLexicalDeclContext(Owner);
916    RecordInst->setLexicalDeclContext(Owner);
917    return Inst;
918  }
919
920  if (D->isOutOfLine()) {
921    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
922    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
923  }
924
925  Owner->addDecl(Inst);
926
927  if (!PrevClassTemplate) {
928    // Queue up any out-of-line partial specializations of this member
929    // class template; the client will force their instantiation once
930    // the enclosing class has been instantiated.
931    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
932    D->getPartialSpecializations(PartialSpecs);
933    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
934      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
935        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
936  }
937
938  return Inst;
939}
940
941Decl *
942TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
943                                   ClassTemplatePartialSpecializationDecl *D) {
944  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
945
946  // Lookup the already-instantiated declaration in the instantiation
947  // of the class template and return that.
948  DeclContext::lookup_result Found
949    = Owner->lookup(ClassTemplate->getDeclName());
950  if (Found.empty())
951    return 0;
952
953  ClassTemplateDecl *InstClassTemplate
954    = dyn_cast<ClassTemplateDecl>(Found.front());
955  if (!InstClassTemplate)
956    return 0;
957
958  if (ClassTemplatePartialSpecializationDecl *Result
959        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
960    return Result;
961
962  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
963}
964
965Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
966  assert(D->getTemplatedDecl()->isStaticDataMember() &&
967         "Only static data member templates are allowed.");
968
969  // Create a local instantiation scope for this variable template, which
970  // will contain the instantiations of the template parameters.
971  LocalInstantiationScope Scope(SemaRef);
972  TemplateParameterList *TempParams = D->getTemplateParameters();
973  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
974  if (!InstParams)
975    return NULL;
976
977  VarDecl *Pattern = D->getTemplatedDecl();
978  VarTemplateDecl *PrevVarTemplate = 0;
979
980  if (Pattern->getPreviousDecl()) {
981    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
982    if (!Found.empty())
983      PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
984  }
985
986  VarDecl *VarInst =
987      cast_or_null<VarDecl>(VisitVarDecl(Pattern,
988                                         /*InstantiatingVarTemplate=*/true));
989
990  DeclContext *DC = Owner;
991
992  VarTemplateDecl *Inst = VarTemplateDecl::Create(
993      SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
994      VarInst, PrevVarTemplate);
995  VarInst->setDescribedVarTemplate(Inst);
996
997  Inst->setAccess(D->getAccess());
998  if (!PrevVarTemplate)
999    Inst->setInstantiatedFromMemberTemplate(D);
1000
1001  if (D->isOutOfLine()) {
1002    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1003    VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1004  }
1005
1006  Owner->addDecl(Inst);
1007
1008  if (!PrevVarTemplate) {
1009    // Queue up any out-of-line partial specializations of this member
1010    // variable template; the client will force their instantiation once
1011    // the enclosing class has been instantiated.
1012    SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1013    D->getPartialSpecializations(PartialSpecs);
1014    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1015      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1016        OutOfLineVarPartialSpecs.push_back(
1017            std::make_pair(Inst, PartialSpecs[I]));
1018  }
1019
1020  return Inst;
1021}
1022
1023Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1024    VarTemplatePartialSpecializationDecl *D) {
1025  assert(D->isStaticDataMember() &&
1026         "Only static data member templates are allowed.");
1027
1028  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1029
1030  // Lookup the already-instantiated declaration and return that.
1031  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1032  assert(!Found.empty() && "Instantiation found nothing?");
1033
1034  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1035  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1036
1037  if (VarTemplatePartialSpecializationDecl *Result =
1038          InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1039    return Result;
1040
1041  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1042}
1043
1044Decl *
1045TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1046  // Create a local instantiation scope for this function template, which
1047  // will contain the instantiations of the template parameters and then get
1048  // merged with the local instantiation scope for the function template
1049  // itself.
1050  LocalInstantiationScope Scope(SemaRef);
1051
1052  TemplateParameterList *TempParams = D->getTemplateParameters();
1053  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1054  if (!InstParams)
1055    return NULL;
1056
1057  FunctionDecl *Instantiated = 0;
1058  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1059    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1060                                                                 InstParams));
1061  else
1062    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1063                                                          D->getTemplatedDecl(),
1064                                                                InstParams));
1065
1066  if (!Instantiated)
1067    return 0;
1068
1069  // Link the instantiated function template declaration to the function
1070  // template from which it was instantiated.
1071  FunctionTemplateDecl *InstTemplate
1072    = Instantiated->getDescribedFunctionTemplate();
1073  InstTemplate->setAccess(D->getAccess());
1074  assert(InstTemplate &&
1075         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1076
1077  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1078
1079  // Link the instantiation back to the pattern *unless* this is a
1080  // non-definition friend declaration.
1081  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1082      !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1083    InstTemplate->setInstantiatedFromMemberTemplate(D);
1084
1085  // Make declarations visible in the appropriate context.
1086  if (!isFriend) {
1087    Owner->addDecl(InstTemplate);
1088  } else if (InstTemplate->getDeclContext()->isRecord() &&
1089             !D->getPreviousDecl()) {
1090    SemaRef.CheckFriendAccess(InstTemplate);
1091  }
1092
1093  return InstTemplate;
1094}
1095
1096Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1097  CXXRecordDecl *PrevDecl = 0;
1098  if (D->isInjectedClassName())
1099    PrevDecl = cast<CXXRecordDecl>(Owner);
1100  else if (D->getPreviousDecl()) {
1101    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1102                                                   D->getPreviousDecl(),
1103                                                   TemplateArgs);
1104    if (!Prev) return 0;
1105    PrevDecl = cast<CXXRecordDecl>(Prev);
1106  }
1107
1108  CXXRecordDecl *Record
1109    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1110                            D->getLocStart(), D->getLocation(),
1111                            D->getIdentifier(), PrevDecl);
1112
1113  // Substitute the nested name specifier, if any.
1114  if (SubstQualifier(D, Record))
1115    return 0;
1116
1117  Record->setImplicit(D->isImplicit());
1118  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1119  // the tag decls introduced by friend class declarations don't have an access
1120  // specifier. Remove once this area of the code gets sorted out.
1121  if (D->getAccess() != AS_none)
1122    Record->setAccess(D->getAccess());
1123  if (!D->isInjectedClassName())
1124    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1125
1126  // If the original function was part of a friend declaration,
1127  // inherit its namespace state.
1128  if (D->getFriendObjectKind())
1129    Record->setObjectOfFriendDecl();
1130
1131  // Make sure that anonymous structs and unions are recorded.
1132  if (D->isAnonymousStructOrUnion())
1133    Record->setAnonymousStructOrUnion(true);
1134
1135  if (D->isLocalClass())
1136    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1137
1138  Owner->addDecl(Record);
1139
1140  // DR1484 clarifies that the members of a local class are instantiated as part
1141  // of the instantiation of their enclosing entity.
1142  if (D->isCompleteDefinition() && D->isLocalClass()) {
1143    if (SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1144                                 TSK_ImplicitInstantiation,
1145                                 /*Complain=*/true)) {
1146      llvm_unreachable("InstantiateClass shouldn't fail here!");
1147    } else {
1148      SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1149                                      TSK_ImplicitInstantiation);
1150    }
1151  }
1152  return Record;
1153}
1154
1155/// \brief Adjust the given function type for an instantiation of the
1156/// given declaration, to cope with modifications to the function's type that
1157/// aren't reflected in the type-source information.
1158///
1159/// \param D The declaration we're instantiating.
1160/// \param TInfo The already-instantiated type.
1161static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1162                                                   FunctionDecl *D,
1163                                                   TypeSourceInfo *TInfo) {
1164  const FunctionProtoType *OrigFunc
1165    = D->getType()->castAs<FunctionProtoType>();
1166  const FunctionProtoType *NewFunc
1167    = TInfo->getType()->castAs<FunctionProtoType>();
1168  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1169    return TInfo->getType();
1170
1171  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1172  NewEPI.ExtInfo = OrigFunc->getExtInfo();
1173  return Context.getFunctionType(NewFunc->getResultType(),
1174                                 NewFunc->getArgTypes(), NewEPI);
1175}
1176
1177/// Normal class members are of more specific types and therefore
1178/// don't make it here.  This function serves two purposes:
1179///   1) instantiating function templates
1180///   2) substituting friend declarations
1181/// FIXME: preserve function definitions in case #2
1182Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1183                                       TemplateParameterList *TemplateParams) {
1184  // Check whether there is already a function template specialization for
1185  // this declaration.
1186  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1187  if (FunctionTemplate && !TemplateParams) {
1188    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1189
1190    void *InsertPos = 0;
1191    FunctionDecl *SpecFunc
1192      = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
1193                                             InsertPos);
1194
1195    // If we already have a function template specialization, return it.
1196    if (SpecFunc)
1197      return SpecFunc;
1198  }
1199
1200  bool isFriend;
1201  if (FunctionTemplate)
1202    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1203  else
1204    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1205
1206  bool MergeWithParentScope = (TemplateParams != 0) ||
1207    Owner->isFunctionOrMethod() ||
1208    !(isa<Decl>(Owner) &&
1209      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1210  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1211
1212  SmallVector<ParmVarDecl *, 4> Params;
1213  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1214  if (!TInfo)
1215    return 0;
1216  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1217
1218  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1219  if (QualifierLoc) {
1220    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1221                                                       TemplateArgs);
1222    if (!QualifierLoc)
1223      return 0;
1224  }
1225
1226  // If we're instantiating a local function declaration, put the result
1227  // in the enclosing namespace; otherwise we need to find the instantiated
1228  // context.
1229  DeclContext *DC;
1230  if (D->isLocalExternDecl()) {
1231    DC = Owner;
1232    SemaRef.adjustContextForLocalExternDecl(DC);
1233  } else if (isFriend && QualifierLoc) {
1234    CXXScopeSpec SS;
1235    SS.Adopt(QualifierLoc);
1236    DC = SemaRef.computeDeclContext(SS);
1237    if (!DC) return 0;
1238  } else {
1239    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1240                                         TemplateArgs);
1241  }
1242
1243  FunctionDecl *Function =
1244      FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1245                           D->getNameInfo(), T, TInfo,
1246                           D->getCanonicalDecl()->getStorageClass(),
1247                           D->isInlineSpecified(), D->hasWrittenPrototype(),
1248                           D->isConstexpr());
1249  Function->setRangeEnd(D->getSourceRange().getEnd());
1250
1251  if (D->isInlined())
1252    Function->setImplicitlyInline();
1253
1254  if (QualifierLoc)
1255    Function->setQualifierInfo(QualifierLoc);
1256
1257  if (D->isLocalExternDecl())
1258    Function->setLocalExternDecl();
1259
1260  DeclContext *LexicalDC = Owner;
1261  if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1262    assert(D->getDeclContext()->isFileContext());
1263    LexicalDC = D->getDeclContext();
1264  }
1265
1266  Function->setLexicalDeclContext(LexicalDC);
1267
1268  // Attach the parameters
1269  for (unsigned P = 0; P < Params.size(); ++P)
1270    if (Params[P])
1271      Params[P]->setOwningFunction(Function);
1272  Function->setParams(Params);
1273
1274  SourceLocation InstantiateAtPOI;
1275  if (TemplateParams) {
1276    // Our resulting instantiation is actually a function template, since we
1277    // are substituting only the outer template parameters. For example, given
1278    //
1279    //   template<typename T>
1280    //   struct X {
1281    //     template<typename U> friend void f(T, U);
1282    //   };
1283    //
1284    //   X<int> x;
1285    //
1286    // We are instantiating the friend function template "f" within X<int>,
1287    // which means substituting int for T, but leaving "f" as a friend function
1288    // template.
1289    // Build the function template itself.
1290    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1291                                                    Function->getLocation(),
1292                                                    Function->getDeclName(),
1293                                                    TemplateParams, Function);
1294    Function->setDescribedFunctionTemplate(FunctionTemplate);
1295
1296    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1297
1298    if (isFriend && D->isThisDeclarationADefinition()) {
1299      // TODO: should we remember this connection regardless of whether
1300      // the friend declaration provided a body?
1301      FunctionTemplate->setInstantiatedFromMemberTemplate(
1302                                           D->getDescribedFunctionTemplate());
1303    }
1304  } else if (FunctionTemplate) {
1305    // Record this function template specialization.
1306    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1307    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1308                            TemplateArgumentList::CreateCopy(SemaRef.Context,
1309                                                             Innermost.begin(),
1310                                                             Innermost.size()),
1311                                                /*InsertPos=*/0);
1312  } else if (isFriend) {
1313    // Note, we need this connection even if the friend doesn't have a body.
1314    // Its body may exist but not have been attached yet due to deferred
1315    // parsing.
1316    // FIXME: It might be cleaner to set this when attaching the body to the
1317    // friend function declaration, however that would require finding all the
1318    // instantiations and modifying them.
1319    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1320  }
1321
1322  if (InitFunctionInstantiation(Function, D))
1323    Function->setInvalidDecl();
1324
1325  bool isExplicitSpecialization = false;
1326
1327  LookupResult Previous(
1328      SemaRef, Function->getDeclName(), SourceLocation(),
1329      D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1330                             : Sema::LookupOrdinaryName,
1331      Sema::ForRedeclaration);
1332
1333  if (DependentFunctionTemplateSpecializationInfo *Info
1334        = D->getDependentSpecializationInfo()) {
1335    assert(isFriend && "non-friend has dependent specialization info?");
1336
1337    // This needs to be set now for future sanity.
1338    Function->setObjectOfFriendDecl();
1339
1340    // Instantiate the explicit template arguments.
1341    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1342                                          Info->getRAngleLoc());
1343    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1344                      ExplicitArgs, TemplateArgs))
1345      return 0;
1346
1347    // Map the candidate templates to their instantiations.
1348    for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1349      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1350                                                Info->getTemplate(I),
1351                                                TemplateArgs);
1352      if (!Temp) return 0;
1353
1354      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1355    }
1356
1357    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1358                                                    &ExplicitArgs,
1359                                                    Previous))
1360      Function->setInvalidDecl();
1361
1362    isExplicitSpecialization = true;
1363
1364  } else if (TemplateParams || !FunctionTemplate) {
1365    // Look only into the namespace where the friend would be declared to
1366    // find a previous declaration. This is the innermost enclosing namespace,
1367    // as described in ActOnFriendFunctionDecl.
1368    SemaRef.LookupQualifiedName(Previous, DC);
1369
1370    // In C++, the previous declaration we find might be a tag type
1371    // (class or enum). In this case, the new declaration will hide the
1372    // tag type. Note that this does does not apply if we're declaring a
1373    // typedef (C++ [dcl.typedef]p4).
1374    if (Previous.isSingleTagDecl())
1375      Previous.clear();
1376  }
1377
1378  SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1379                                   isExplicitSpecialization);
1380
1381  NamedDecl *PrincipalDecl = (TemplateParams
1382                              ? cast<NamedDecl>(FunctionTemplate)
1383                              : Function);
1384
1385  // If the original function was part of a friend declaration,
1386  // inherit its namespace state and add it to the owner.
1387  if (isFriend) {
1388    PrincipalDecl->setObjectOfFriendDecl();
1389    DC->makeDeclVisibleInContext(PrincipalDecl);
1390
1391    bool queuedInstantiation = false;
1392
1393    // C++98 [temp.friend]p5: When a function is defined in a friend function
1394    //   declaration in a class template, the function is defined at each
1395    //   instantiation of the class template. The function is defined even if it
1396    //   is never used.
1397    // C++11 [temp.friend]p4: When a function is defined in a friend function
1398    //   declaration in a class template, the function is instantiated when the
1399    //   function is odr-used.
1400    //
1401    // If -Wc++98-compat is enabled, we go through the motions of checking for a
1402    // redefinition, but don't instantiate the function.
1403    if ((!SemaRef.getLangOpts().CPlusPlus11 ||
1404         SemaRef.Diags.getDiagnosticLevel(
1405             diag::warn_cxx98_compat_friend_redefinition,
1406             Function->getLocation())
1407           != DiagnosticsEngine::Ignored) &&
1408        D->isThisDeclarationADefinition()) {
1409      // Check for a function body.
1410      const FunctionDecl *Definition = 0;
1411      if (Function->isDefined(Definition) &&
1412          Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1413        SemaRef.Diag(Function->getLocation(),
1414                     SemaRef.getLangOpts().CPlusPlus11 ?
1415                       diag::warn_cxx98_compat_friend_redefinition :
1416                       diag::err_redefinition) << Function->getDeclName();
1417        SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1418        if (!SemaRef.getLangOpts().CPlusPlus11)
1419          Function->setInvalidDecl();
1420      }
1421      // Check for redefinitions due to other instantiations of this or
1422      // a similar friend function.
1423      else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1424                                           REnd = Function->redecls_end();
1425                R != REnd; ++R) {
1426        if (*R == Function)
1427          continue;
1428        switch (R->getFriendObjectKind()) {
1429        case Decl::FOK_None:
1430          if (!SemaRef.getLangOpts().CPlusPlus11 &&
1431              !queuedInstantiation && R->isUsed(false)) {
1432            if (MemberSpecializationInfo *MSInfo
1433                = Function->getMemberSpecializationInfo()) {
1434              if (MSInfo->getPointOfInstantiation().isInvalid()) {
1435                SourceLocation Loc = R->getLocation(); // FIXME
1436                MSInfo->setPointOfInstantiation(Loc);
1437                SemaRef.PendingLocalImplicitInstantiations.push_back(
1438                                                 std::make_pair(Function, Loc));
1439                queuedInstantiation = true;
1440              }
1441            }
1442          }
1443          break;
1444        default:
1445          if (const FunctionDecl *RPattern
1446              = R->getTemplateInstantiationPattern())
1447            if (RPattern->isDefined(RPattern)) {
1448              SemaRef.Diag(Function->getLocation(),
1449                           SemaRef.getLangOpts().CPlusPlus11 ?
1450                             diag::warn_cxx98_compat_friend_redefinition :
1451                             diag::err_redefinition)
1452                << Function->getDeclName();
1453              SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1454              if (!SemaRef.getLangOpts().CPlusPlus11)
1455                Function->setInvalidDecl();
1456              break;
1457            }
1458        }
1459      }
1460    }
1461  }
1462
1463  if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1464    DC->makeDeclVisibleInContext(PrincipalDecl);
1465
1466  if (Function->isOverloadedOperator() && !DC->isRecord() &&
1467      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1468    PrincipalDecl->setNonMemberOperator();
1469
1470  assert(!D->isDefaulted() && "only methods should be defaulted");
1471  return Function;
1472}
1473
1474Decl *
1475TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1476                                      TemplateParameterList *TemplateParams,
1477                                      bool IsClassScopeSpecialization) {
1478  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1479  if (FunctionTemplate && !TemplateParams) {
1480    // We are creating a function template specialization from a function
1481    // template. Check whether there is already a function template
1482    // specialization for this particular set of template arguments.
1483    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1484
1485    void *InsertPos = 0;
1486    FunctionDecl *SpecFunc
1487      = FunctionTemplate->findSpecialization(Innermost.begin(),
1488                                             Innermost.size(),
1489                                             InsertPos);
1490
1491    // If we already have a function template specialization, return it.
1492    if (SpecFunc)
1493      return SpecFunc;
1494  }
1495
1496  bool isFriend;
1497  if (FunctionTemplate)
1498    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1499  else
1500    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1501
1502  bool MergeWithParentScope = (TemplateParams != 0) ||
1503    !(isa<Decl>(Owner) &&
1504      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1505  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1506
1507  // Instantiate enclosing template arguments for friends.
1508  SmallVector<TemplateParameterList *, 4> TempParamLists;
1509  unsigned NumTempParamLists = 0;
1510  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1511    TempParamLists.set_size(NumTempParamLists);
1512    for (unsigned I = 0; I != NumTempParamLists; ++I) {
1513      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1514      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1515      if (!InstParams)
1516        return NULL;
1517      TempParamLists[I] = InstParams;
1518    }
1519  }
1520
1521  SmallVector<ParmVarDecl *, 4> Params;
1522  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1523  if (!TInfo)
1524    return 0;
1525  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1526
1527  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1528  if (QualifierLoc) {
1529    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1530                                                 TemplateArgs);
1531    if (!QualifierLoc)
1532      return 0;
1533  }
1534
1535  DeclContext *DC = Owner;
1536  if (isFriend) {
1537    if (QualifierLoc) {
1538      CXXScopeSpec SS;
1539      SS.Adopt(QualifierLoc);
1540      DC = SemaRef.computeDeclContext(SS);
1541
1542      if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1543        return 0;
1544    } else {
1545      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1546                                           D->getDeclContext(),
1547                                           TemplateArgs);
1548    }
1549    if (!DC) return 0;
1550  }
1551
1552  // Build the instantiated method declaration.
1553  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1554  CXXMethodDecl *Method = 0;
1555
1556  SourceLocation StartLoc = D->getInnerLocStart();
1557  DeclarationNameInfo NameInfo
1558    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1559  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1560    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1561                                        StartLoc, NameInfo, T, TInfo,
1562                                        Constructor->isExplicit(),
1563                                        Constructor->isInlineSpecified(),
1564                                        false, Constructor->isConstexpr());
1565
1566    // Claim that the instantiation of a constructor or constructor template
1567    // inherits the same constructor that the template does.
1568    if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1569            Constructor->getInheritedConstructor())) {
1570      // If we're instantiating a specialization of a function template, our
1571      // "inherited constructor" will actually itself be a function template.
1572      // Instantiate a declaration of it, too.
1573      if (FunctionTemplate) {
1574        assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1575               !Inh->getParent()->isDependentContext() &&
1576               "inheriting constructor template in dependent context?");
1577        Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1578                                         Inh);
1579        if (Inst.isInvalid())
1580          return 0;
1581        Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1582        LocalInstantiationScope LocalScope(SemaRef);
1583
1584        // Use the same template arguments that we deduced for the inheriting
1585        // constructor. There's no way they could be deduced differently.
1586        MultiLevelTemplateArgumentList InheritedArgs;
1587        InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1588        Inh = cast_or_null<CXXConstructorDecl>(
1589            SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1590        if (!Inh)
1591          return 0;
1592      }
1593      cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1594    }
1595  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1596    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1597                                       StartLoc, NameInfo, T, TInfo,
1598                                       Destructor->isInlineSpecified(),
1599                                       false);
1600  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1601    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1602                                       StartLoc, NameInfo, T, TInfo,
1603                                       Conversion->isInlineSpecified(),
1604                                       Conversion->isExplicit(),
1605                                       Conversion->isConstexpr(),
1606                                       Conversion->getLocEnd());
1607  } else {
1608    StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1609    Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1610                                   StartLoc, NameInfo, T, TInfo,
1611                                   SC, D->isInlineSpecified(),
1612                                   D->isConstexpr(), D->getLocEnd());
1613  }
1614
1615  if (D->isInlined())
1616    Method->setImplicitlyInline();
1617
1618  if (QualifierLoc)
1619    Method->setQualifierInfo(QualifierLoc);
1620
1621  if (TemplateParams) {
1622    // Our resulting instantiation is actually a function template, since we
1623    // are substituting only the outer template parameters. For example, given
1624    //
1625    //   template<typename T>
1626    //   struct X {
1627    //     template<typename U> void f(T, U);
1628    //   };
1629    //
1630    //   X<int> x;
1631    //
1632    // We are instantiating the member template "f" within X<int>, which means
1633    // substituting int for T, but leaving "f" as a member function template.
1634    // Build the function template itself.
1635    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1636                                                    Method->getLocation(),
1637                                                    Method->getDeclName(),
1638                                                    TemplateParams, Method);
1639    if (isFriend) {
1640      FunctionTemplate->setLexicalDeclContext(Owner);
1641      FunctionTemplate->setObjectOfFriendDecl();
1642    } else if (D->isOutOfLine())
1643      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1644    Method->setDescribedFunctionTemplate(FunctionTemplate);
1645  } else if (FunctionTemplate) {
1646    // Record this function template specialization.
1647    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1648    Method->setFunctionTemplateSpecialization(FunctionTemplate,
1649                         TemplateArgumentList::CreateCopy(SemaRef.Context,
1650                                                          Innermost.begin(),
1651                                                          Innermost.size()),
1652                                              /*InsertPos=*/0);
1653  } else if (!isFriend) {
1654    // Record that this is an instantiation of a member function.
1655    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1656  }
1657
1658  // If we are instantiating a member function defined
1659  // out-of-line, the instantiation will have the same lexical
1660  // context (which will be a namespace scope) as the template.
1661  if (isFriend) {
1662    if (NumTempParamLists)
1663      Method->setTemplateParameterListsInfo(SemaRef.Context,
1664                                            NumTempParamLists,
1665                                            TempParamLists.data());
1666
1667    Method->setLexicalDeclContext(Owner);
1668    Method->setObjectOfFriendDecl();
1669  } else if (D->isOutOfLine())
1670    Method->setLexicalDeclContext(D->getLexicalDeclContext());
1671
1672  // Attach the parameters
1673  for (unsigned P = 0; P < Params.size(); ++P)
1674    Params[P]->setOwningFunction(Method);
1675  Method->setParams(Params);
1676
1677  if (InitMethodInstantiation(Method, D))
1678    Method->setInvalidDecl();
1679
1680  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1681                        Sema::ForRedeclaration);
1682
1683  if (!FunctionTemplate || TemplateParams || isFriend) {
1684    SemaRef.LookupQualifiedName(Previous, Record);
1685
1686    // In C++, the previous declaration we find might be a tag type
1687    // (class or enum). In this case, the new declaration will hide the
1688    // tag type. Note that this does does not apply if we're declaring a
1689    // typedef (C++ [dcl.typedef]p4).
1690    if (Previous.isSingleTagDecl())
1691      Previous.clear();
1692  }
1693
1694  if (!IsClassScopeSpecialization)
1695    SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1696
1697  if (D->isPure())
1698    SemaRef.CheckPureMethod(Method, SourceRange());
1699
1700  // Propagate access.  For a non-friend declaration, the access is
1701  // whatever we're propagating from.  For a friend, it should be the
1702  // previous declaration we just found.
1703  if (isFriend && Method->getPreviousDecl())
1704    Method->setAccess(Method->getPreviousDecl()->getAccess());
1705  else
1706    Method->setAccess(D->getAccess());
1707  if (FunctionTemplate)
1708    FunctionTemplate->setAccess(Method->getAccess());
1709
1710  SemaRef.CheckOverrideControl(Method);
1711
1712  // If a function is defined as defaulted or deleted, mark it as such now.
1713  if (D->isExplicitlyDefaulted())
1714    SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1715  if (D->isDeletedAsWritten())
1716    SemaRef.SetDeclDeleted(Method, Method->getLocation());
1717
1718  // If there's a function template, let our caller handle it.
1719  if (FunctionTemplate) {
1720    // do nothing
1721
1722  // Don't hide a (potentially) valid declaration with an invalid one.
1723  } else if (Method->isInvalidDecl() && !Previous.empty()) {
1724    // do nothing
1725
1726  // Otherwise, check access to friends and make them visible.
1727  } else if (isFriend) {
1728    // We only need to re-check access for methods which we didn't
1729    // manage to match during parsing.
1730    if (!D->getPreviousDecl())
1731      SemaRef.CheckFriendAccess(Method);
1732
1733    Record->makeDeclVisibleInContext(Method);
1734
1735  // Otherwise, add the declaration.  We don't need to do this for
1736  // class-scope specializations because we'll have matched them with
1737  // the appropriate template.
1738  } else if (!IsClassScopeSpecialization) {
1739    Owner->addDecl(Method);
1740  }
1741
1742  return Method;
1743}
1744
1745Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1746  return VisitCXXMethodDecl(D);
1747}
1748
1749Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1750  return VisitCXXMethodDecl(D);
1751}
1752
1753Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1754  return VisitCXXMethodDecl(D);
1755}
1756
1757Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1758  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1759                                  /*ExpectParameterPack=*/ false);
1760}
1761
1762Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1763                                                    TemplateTypeParmDecl *D) {
1764  // TODO: don't always clone when decls are refcounted.
1765  assert(D->getTypeForDecl()->isTemplateTypeParmType());
1766
1767  TemplateTypeParmDecl *Inst =
1768    TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1769                                 D->getLocStart(), D->getLocation(),
1770                                 D->getDepth() - TemplateArgs.getNumLevels(),
1771                                 D->getIndex(), D->getIdentifier(),
1772                                 D->wasDeclaredWithTypename(),
1773                                 D->isParameterPack());
1774  Inst->setAccess(AS_public);
1775
1776  if (D->hasDefaultArgument()) {
1777    TypeSourceInfo *InstantiatedDefaultArg =
1778        SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1779                          D->getDefaultArgumentLoc(), D->getDeclName());
1780    if (InstantiatedDefaultArg)
1781      Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1782  }
1783
1784  // Introduce this template parameter's instantiation into the instantiation
1785  // scope.
1786  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1787
1788  return Inst;
1789}
1790
1791Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1792                                                 NonTypeTemplateParmDecl *D) {
1793  // Substitute into the type of the non-type template parameter.
1794  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1795  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1796  SmallVector<QualType, 4> ExpandedParameterPackTypes;
1797  bool IsExpandedParameterPack = false;
1798  TypeSourceInfo *DI;
1799  QualType T;
1800  bool Invalid = false;
1801
1802  if (D->isExpandedParameterPack()) {
1803    // The non-type template parameter pack is an already-expanded pack
1804    // expansion of types. Substitute into each of the expanded types.
1805    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1806    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1807    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1808      TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1809                                               TemplateArgs,
1810                                               D->getLocation(),
1811                                               D->getDeclName());
1812      if (!NewDI)
1813        return 0;
1814
1815      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1816      QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1817                                                              D->getLocation());
1818      if (NewT.isNull())
1819        return 0;
1820      ExpandedParameterPackTypes.push_back(NewT);
1821    }
1822
1823    IsExpandedParameterPack = true;
1824    DI = D->getTypeSourceInfo();
1825    T = DI->getType();
1826  } else if (D->isPackExpansion()) {
1827    // The non-type template parameter pack's type is a pack expansion of types.
1828    // Determine whether we need to expand this parameter pack into separate
1829    // types.
1830    PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
1831    TypeLoc Pattern = Expansion.getPatternLoc();
1832    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1833    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1834
1835    // Determine whether the set of unexpanded parameter packs can and should
1836    // be expanded.
1837    bool Expand = true;
1838    bool RetainExpansion = false;
1839    Optional<unsigned> OrigNumExpansions
1840      = Expansion.getTypePtr()->getNumExpansions();
1841    Optional<unsigned> NumExpansions = OrigNumExpansions;
1842    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1843                                                Pattern.getSourceRange(),
1844                                                Unexpanded,
1845                                                TemplateArgs,
1846                                                Expand, RetainExpansion,
1847                                                NumExpansions))
1848      return 0;
1849
1850    if (Expand) {
1851      for (unsigned I = 0; I != *NumExpansions; ++I) {
1852        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1853        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1854                                                  D->getLocation(),
1855                                                  D->getDeclName());
1856        if (!NewDI)
1857          return 0;
1858
1859        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1860        QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1861                                                              NewDI->getType(),
1862                                                              D->getLocation());
1863        if (NewT.isNull())
1864          return 0;
1865        ExpandedParameterPackTypes.push_back(NewT);
1866      }
1867
1868      // Note that we have an expanded parameter pack. The "type" of this
1869      // expanded parameter pack is the original expansion type, but callers
1870      // will end up using the expanded parameter pack types for type-checking.
1871      IsExpandedParameterPack = true;
1872      DI = D->getTypeSourceInfo();
1873      T = DI->getType();
1874    } else {
1875      // We cannot fully expand the pack expansion now, so substitute into the
1876      // pattern and create a new pack expansion type.
1877      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1878      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1879                                                     D->getLocation(),
1880                                                     D->getDeclName());
1881      if (!NewPattern)
1882        return 0;
1883
1884      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1885                                      NumExpansions);
1886      if (!DI)
1887        return 0;
1888
1889      T = DI->getType();
1890    }
1891  } else {
1892    // Simple case: substitution into a parameter that is not a parameter pack.
1893    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1894                           D->getLocation(), D->getDeclName());
1895    if (!DI)
1896      return 0;
1897
1898    // Check that this type is acceptable for a non-type template parameter.
1899    T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1900                                                  D->getLocation());
1901    if (T.isNull()) {
1902      T = SemaRef.Context.IntTy;
1903      Invalid = true;
1904    }
1905  }
1906
1907  NonTypeTemplateParmDecl *Param;
1908  if (IsExpandedParameterPack)
1909    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1910                                            D->getInnerLocStart(),
1911                                            D->getLocation(),
1912                                    D->getDepth() - TemplateArgs.getNumLevels(),
1913                                            D->getPosition(),
1914                                            D->getIdentifier(), T,
1915                                            DI,
1916                                            ExpandedParameterPackTypes.data(),
1917                                            ExpandedParameterPackTypes.size(),
1918                                    ExpandedParameterPackTypesAsWritten.data());
1919  else
1920    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1921                                            D->getInnerLocStart(),
1922                                            D->getLocation(),
1923                                    D->getDepth() - TemplateArgs.getNumLevels(),
1924                                            D->getPosition(),
1925                                            D->getIdentifier(), T,
1926                                            D->isParameterPack(), DI);
1927
1928  Param->setAccess(AS_public);
1929  if (Invalid)
1930    Param->setInvalidDecl();
1931
1932  if (D->hasDefaultArgument()) {
1933    ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1934    if (!Value.isInvalid())
1935      Param->setDefaultArgument(Value.get(), false);
1936  }
1937
1938  // Introduce this template parameter's instantiation into the instantiation
1939  // scope.
1940  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1941  return Param;
1942}
1943
1944static void collectUnexpandedParameterPacks(
1945    Sema &S,
1946    TemplateParameterList *Params,
1947    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1948  for (TemplateParameterList::const_iterator I = Params->begin(),
1949                                             E = Params->end(); I != E; ++I) {
1950    if ((*I)->isTemplateParameterPack())
1951      continue;
1952    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1953      S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1954                                        Unexpanded);
1955    if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1956      collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1957                                      Unexpanded);
1958  }
1959}
1960
1961Decl *
1962TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1963                                                  TemplateTemplateParmDecl *D) {
1964  // Instantiate the template parameter list of the template template parameter.
1965  TemplateParameterList *TempParams = D->getTemplateParameters();
1966  TemplateParameterList *InstParams;
1967  SmallVector<TemplateParameterList*, 8> ExpandedParams;
1968
1969  bool IsExpandedParameterPack = false;
1970
1971  if (D->isExpandedParameterPack()) {
1972    // The template template parameter pack is an already-expanded pack
1973    // expansion of template parameters. Substitute into each of the expanded
1974    // parameters.
1975    ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1976    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1977         I != N; ++I) {
1978      LocalInstantiationScope Scope(SemaRef);
1979      TemplateParameterList *Expansion =
1980        SubstTemplateParams(D->getExpansionTemplateParameters(I));
1981      if (!Expansion)
1982        return 0;
1983      ExpandedParams.push_back(Expansion);
1984    }
1985
1986    IsExpandedParameterPack = true;
1987    InstParams = TempParams;
1988  } else if (D->isPackExpansion()) {
1989    // The template template parameter pack expands to a pack of template
1990    // template parameters. Determine whether we need to expand this parameter
1991    // pack into separate parameters.
1992    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1993    collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1994                                    Unexpanded);
1995
1996    // Determine whether the set of unexpanded parameter packs can and should
1997    // be expanded.
1998    bool Expand = true;
1999    bool RetainExpansion = false;
2000    Optional<unsigned> NumExpansions;
2001    if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2002                                                TempParams->getSourceRange(),
2003                                                Unexpanded,
2004                                                TemplateArgs,
2005                                                Expand, RetainExpansion,
2006                                                NumExpansions))
2007      return 0;
2008
2009    if (Expand) {
2010      for (unsigned I = 0; I != *NumExpansions; ++I) {
2011        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2012        LocalInstantiationScope Scope(SemaRef);
2013        TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2014        if (!Expansion)
2015          return 0;
2016        ExpandedParams.push_back(Expansion);
2017      }
2018
2019      // Note that we have an expanded parameter pack. The "type" of this
2020      // expanded parameter pack is the original expansion type, but callers
2021      // will end up using the expanded parameter pack types for type-checking.
2022      IsExpandedParameterPack = true;
2023      InstParams = TempParams;
2024    } else {
2025      // We cannot fully expand the pack expansion now, so just substitute
2026      // into the pattern.
2027      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2028
2029      LocalInstantiationScope Scope(SemaRef);
2030      InstParams = SubstTemplateParams(TempParams);
2031      if (!InstParams)
2032        return 0;
2033    }
2034  } else {
2035    // Perform the actual substitution of template parameters within a new,
2036    // local instantiation scope.
2037    LocalInstantiationScope Scope(SemaRef);
2038    InstParams = SubstTemplateParams(TempParams);
2039    if (!InstParams)
2040      return 0;
2041  }
2042
2043  // Build the template template parameter.
2044  TemplateTemplateParmDecl *Param;
2045  if (IsExpandedParameterPack)
2046    Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2047                                             D->getLocation(),
2048                                   D->getDepth() - TemplateArgs.getNumLevels(),
2049                                             D->getPosition(),
2050                                             D->getIdentifier(), InstParams,
2051                                             ExpandedParams);
2052  else
2053    Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2054                                             D->getLocation(),
2055                                   D->getDepth() - TemplateArgs.getNumLevels(),
2056                                             D->getPosition(),
2057                                             D->isParameterPack(),
2058                                             D->getIdentifier(), InstParams);
2059  if (D->hasDefaultArgument()) {
2060    NestedNameSpecifierLoc QualifierLoc =
2061        D->getDefaultArgument().getTemplateQualifierLoc();
2062    QualifierLoc =
2063        SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2064    TemplateName TName = SemaRef.SubstTemplateName(
2065        QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2066        D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2067    if (!TName.isNull())
2068      Param->setDefaultArgument(
2069          TemplateArgumentLoc(TemplateArgument(TName),
2070                              D->getDefaultArgument().getTemplateQualifierLoc(),
2071                              D->getDefaultArgument().getTemplateNameLoc()),
2072          false);
2073  }
2074  Param->setAccess(AS_public);
2075
2076  // Introduce this template parameter's instantiation into the instantiation
2077  // scope.
2078  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2079
2080  return Param;
2081}
2082
2083Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2084  // Using directives are never dependent (and never contain any types or
2085  // expressions), so they require no explicit instantiation work.
2086
2087  UsingDirectiveDecl *Inst
2088    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2089                                 D->getNamespaceKeyLocation(),
2090                                 D->getQualifierLoc(),
2091                                 D->getIdentLocation(),
2092                                 D->getNominatedNamespace(),
2093                                 D->getCommonAncestor());
2094
2095  // Add the using directive to its declaration context
2096  // only if this is not a function or method.
2097  if (!Owner->isFunctionOrMethod())
2098    Owner->addDecl(Inst);
2099
2100  return Inst;
2101}
2102
2103Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2104
2105  // The nested name specifier may be dependent, for example
2106  //     template <typename T> struct t {
2107  //       struct s1 { T f1(); };
2108  //       struct s2 : s1 { using s1::f1; };
2109  //     };
2110  //     template struct t<int>;
2111  // Here, in using s1::f1, s1 refers to t<T>::s1;
2112  // we need to substitute for t<int>::s1.
2113  NestedNameSpecifierLoc QualifierLoc
2114    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2115                                          TemplateArgs);
2116  if (!QualifierLoc)
2117    return 0;
2118
2119  // The name info is non-dependent, so no transformation
2120  // is required.
2121  DeclarationNameInfo NameInfo = D->getNameInfo();
2122
2123  // We only need to do redeclaration lookups if we're in a class
2124  // scope (in fact, it's not really even possible in non-class
2125  // scopes).
2126  bool CheckRedeclaration = Owner->isRecord();
2127
2128  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2129                    Sema::ForRedeclaration);
2130
2131  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2132                                       D->getUsingLoc(),
2133                                       QualifierLoc,
2134                                       NameInfo,
2135                                       D->hasTypename());
2136
2137  CXXScopeSpec SS;
2138  SS.Adopt(QualifierLoc);
2139  if (CheckRedeclaration) {
2140    Prev.setHideTags(false);
2141    SemaRef.LookupQualifiedName(Prev, Owner);
2142
2143    // Check for invalid redeclarations.
2144    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2145                                            D->hasTypename(), SS,
2146                                            D->getLocation(), Prev))
2147      NewUD->setInvalidDecl();
2148
2149  }
2150
2151  if (!NewUD->isInvalidDecl() &&
2152      SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
2153                                      D->getLocation()))
2154    NewUD->setInvalidDecl();
2155
2156  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2157  NewUD->setAccess(D->getAccess());
2158  Owner->addDecl(NewUD);
2159
2160  // Don't process the shadow decls for an invalid decl.
2161  if (NewUD->isInvalidDecl())
2162    return NewUD;
2163
2164  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2165    if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2166      NewUD->setInvalidDecl();
2167    return NewUD;
2168  }
2169
2170  bool isFunctionScope = Owner->isFunctionOrMethod();
2171
2172  // Process the shadow decls.
2173  for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2174         I != E; ++I) {
2175    UsingShadowDecl *Shadow = *I;
2176    NamedDecl *InstTarget =
2177        cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2178            Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
2179    if (!InstTarget)
2180      return 0;
2181
2182    UsingShadowDecl *PrevDecl = 0;
2183    if (CheckRedeclaration) {
2184      if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2185        continue;
2186    } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2187      PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2188          Shadow->getLocation(), OldPrev, TemplateArgs));
2189    }
2190
2191    UsingShadowDecl *InstShadow =
2192        SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl);
2193    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2194
2195    if (isFunctionScope)
2196      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2197  }
2198
2199  return NewUD;
2200}
2201
2202Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2203  // Ignore these;  we handle them in bulk when processing the UsingDecl.
2204  return 0;
2205}
2206
2207Decl * TemplateDeclInstantiator
2208    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2209  NestedNameSpecifierLoc QualifierLoc
2210    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2211                                          TemplateArgs);
2212  if (!QualifierLoc)
2213    return 0;
2214
2215  CXXScopeSpec SS;
2216  SS.Adopt(QualifierLoc);
2217
2218  // Since NameInfo refers to a typename, it cannot be a C++ special name.
2219  // Hence, no transformation is required for it.
2220  DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2221  NamedDecl *UD =
2222    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2223                                  D->getUsingLoc(), SS, NameInfo, 0,
2224                                  /*instantiation*/ true,
2225                                  /*typename*/ true, D->getTypenameLoc());
2226  if (UD)
2227    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2228
2229  return UD;
2230}
2231
2232Decl * TemplateDeclInstantiator
2233    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2234  NestedNameSpecifierLoc QualifierLoc
2235      = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2236  if (!QualifierLoc)
2237    return 0;
2238
2239  CXXScopeSpec SS;
2240  SS.Adopt(QualifierLoc);
2241
2242  DeclarationNameInfo NameInfo
2243    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2244
2245  NamedDecl *UD =
2246    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2247                                  D->getUsingLoc(), SS, NameInfo, 0,
2248                                  /*instantiation*/ true,
2249                                  /*typename*/ false, SourceLocation());
2250  if (UD)
2251    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2252
2253  return UD;
2254}
2255
2256
2257Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2258                                     ClassScopeFunctionSpecializationDecl *Decl) {
2259  CXXMethodDecl *OldFD = Decl->getSpecialization();
2260  CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2261                                                                0, true));
2262
2263  LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2264                        Sema::ForRedeclaration);
2265
2266  TemplateArgumentListInfo TemplateArgs;
2267  TemplateArgumentListInfo* TemplateArgsPtr = 0;
2268  if (Decl->hasExplicitTemplateArgs()) {
2269    TemplateArgs = Decl->templateArgs();
2270    TemplateArgsPtr = &TemplateArgs;
2271  }
2272
2273  SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2274  if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2275                                                  Previous)) {
2276    NewFD->setInvalidDecl();
2277    return NewFD;
2278  }
2279
2280  // Associate the specialization with the pattern.
2281  FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2282  assert(Specialization && "Class scope Specialization is null");
2283  SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2284
2285  return NewFD;
2286}
2287
2288Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2289                                     OMPThreadPrivateDecl *D) {
2290  SmallVector<Expr *, 5> Vars;
2291  for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2292                                  E = D->varlist_end();
2293       I != E; ++I) {
2294    Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2295    assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2296    Vars.push_back(Var);
2297  }
2298
2299  OMPThreadPrivateDecl *TD =
2300    SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2301
2302  return TD;
2303}
2304
2305Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2306  return VisitFunctionDecl(D, 0);
2307}
2308
2309Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2310  return VisitCXXMethodDecl(D, 0);
2311}
2312
2313Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2314  llvm_unreachable("There are only CXXRecordDecls in C++");
2315}
2316
2317Decl *
2318TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2319    ClassTemplateSpecializationDecl *D) {
2320  llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2321                   "inside templates");
2322}
2323
2324Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2325    VarTemplateSpecializationDecl *D) {
2326
2327  TemplateArgumentListInfo VarTemplateArgsInfo;
2328  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2329  assert(VarTemplate &&
2330         "A template specialization without specialized template?");
2331
2332  // Substitute the current template arguments.
2333  const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2334  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2335  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2336
2337  if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2338                    TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2339    return 0;
2340
2341  // Check that the template argument list is well-formed for this template.
2342  SmallVector<TemplateArgument, 4> Converted;
2343  bool ExpansionIntoFixedList = false;
2344  if (SemaRef.CheckTemplateArgumentList(
2345          VarTemplate, VarTemplate->getLocStart(),
2346          const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2347          Converted, &ExpansionIntoFixedList))
2348    return 0;
2349
2350  // Find the variable template specialization declaration that
2351  // corresponds to these arguments.
2352  void *InsertPos = 0;
2353  if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2354          Converted.data(), Converted.size(), InsertPos))
2355    // If we already have a variable template specialization, return it.
2356    return VarSpec;
2357
2358  return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2359                                            VarTemplateArgsInfo, Converted);
2360}
2361
2362Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2363    VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2364    const TemplateArgumentListInfo &TemplateArgsInfo,
2365    llvm::ArrayRef<TemplateArgument> Converted) {
2366
2367  // If this is the variable for an anonymous struct or union,
2368  // instantiate the anonymous struct/union type first.
2369  if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2370    if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2371      if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2372        return 0;
2373
2374  // Do substitution on the type of the declaration
2375  TypeSourceInfo *DI =
2376      SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2377                        D->getTypeSpecStartLoc(), D->getDeclName());
2378  if (!DI)
2379    return 0;
2380
2381  if (DI->getType()->isFunctionType()) {
2382    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2383        << D->isStaticDataMember() << DI->getType();
2384    return 0;
2385  }
2386
2387  // Build the instantiated declaration
2388  VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2389      SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2390      VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2391      Converted.size());
2392  Var->setTemplateArgsInfo(TemplateArgsInfo);
2393  if (InsertPos)
2394    VarTemplate->AddSpecialization(Var, InsertPos);
2395
2396  // Substitute the nested name specifier, if any.
2397  if (SubstQualifier(D, Var))
2398    return 0;
2399
2400  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2401                                     Owner, StartingScope);
2402
2403  return Var;
2404}
2405
2406Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2407  llvm_unreachable("@defs is not supported in Objective-C++");
2408}
2409
2410Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2411  // FIXME: We need to be able to instantiate FriendTemplateDecls.
2412  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2413                                               DiagnosticsEngine::Error,
2414                                               "cannot instantiate %0 yet");
2415  SemaRef.Diag(D->getLocation(), DiagID)
2416    << D->getDeclKindName();
2417
2418  return 0;
2419}
2420
2421Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2422  llvm_unreachable("Unexpected decl");
2423}
2424
2425Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2426                      const MultiLevelTemplateArgumentList &TemplateArgs) {
2427  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2428  if (D->isInvalidDecl())
2429    return 0;
2430
2431  return Instantiator.Visit(D);
2432}
2433
2434/// \brief Instantiates a nested template parameter list in the current
2435/// instantiation context.
2436///
2437/// \param L The parameter list to instantiate
2438///
2439/// \returns NULL if there was an error
2440TemplateParameterList *
2441TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2442  // Get errors for all the parameters before bailing out.
2443  bool Invalid = false;
2444
2445  unsigned N = L->size();
2446  typedef SmallVector<NamedDecl *, 8> ParamVector;
2447  ParamVector Params;
2448  Params.reserve(N);
2449  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2450       PI != PE; ++PI) {
2451    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2452    Params.push_back(D);
2453    Invalid = Invalid || !D || D->isInvalidDecl();
2454  }
2455
2456  // Clean up if we had an error.
2457  if (Invalid)
2458    return NULL;
2459
2460  TemplateParameterList *InstL
2461    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2462                                    L->getLAngleLoc(), &Params.front(), N,
2463                                    L->getRAngleLoc());
2464  return InstL;
2465}
2466
2467/// \brief Instantiate the declaration of a class template partial
2468/// specialization.
2469///
2470/// \param ClassTemplate the (instantiated) class template that is partially
2471// specialized by the instantiation of \p PartialSpec.
2472///
2473/// \param PartialSpec the (uninstantiated) class template partial
2474/// specialization that we are instantiating.
2475///
2476/// \returns The instantiated partial specialization, if successful; otherwise,
2477/// NULL to indicate an error.
2478ClassTemplatePartialSpecializationDecl *
2479TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2480                                            ClassTemplateDecl *ClassTemplate,
2481                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
2482  // Create a local instantiation scope for this class template partial
2483  // specialization, which will contain the instantiations of the template
2484  // parameters.
2485  LocalInstantiationScope Scope(SemaRef);
2486
2487  // Substitute into the template parameters of the class template partial
2488  // specialization.
2489  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2490  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2491  if (!InstParams)
2492    return 0;
2493
2494  // Substitute into the template arguments of the class template partial
2495  // specialization.
2496  const ASTTemplateArgumentListInfo *TemplArgInfo
2497    = PartialSpec->getTemplateArgsAsWritten();
2498  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2499                                            TemplArgInfo->RAngleLoc);
2500  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2501                    TemplArgInfo->NumTemplateArgs,
2502                    InstTemplateArgs, TemplateArgs))
2503    return 0;
2504
2505  // Check that the template argument list is well-formed for this
2506  // class template.
2507  SmallVector<TemplateArgument, 4> Converted;
2508  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2509                                        PartialSpec->getLocation(),
2510                                        InstTemplateArgs,
2511                                        false,
2512                                        Converted))
2513    return 0;
2514
2515  // Figure out where to insert this class template partial specialization
2516  // in the member template's set of class template partial specializations.
2517  void *InsertPos = 0;
2518  ClassTemplateSpecializationDecl *PrevDecl
2519    = ClassTemplate->findPartialSpecialization(Converted.data(),
2520                                               Converted.size(), InsertPos);
2521
2522  // Build the canonical type that describes the converted template
2523  // arguments of the class template partial specialization.
2524  QualType CanonType
2525    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2526                                                    Converted.data(),
2527                                                    Converted.size());
2528
2529  // Build the fully-sugared type for this class template
2530  // specialization as the user wrote in the specialization
2531  // itself. This means that we'll pretty-print the type retrieved
2532  // from the specialization's declaration the way that the user
2533  // actually wrote the specialization, rather than formatting the
2534  // name based on the "canonical" representation used to store the
2535  // template arguments in the specialization.
2536  TypeSourceInfo *WrittenTy
2537    = SemaRef.Context.getTemplateSpecializationTypeInfo(
2538                                                    TemplateName(ClassTemplate),
2539                                                    PartialSpec->getLocation(),
2540                                                    InstTemplateArgs,
2541                                                    CanonType);
2542
2543  if (PrevDecl) {
2544    // We've already seen a partial specialization with the same template
2545    // parameters and template arguments. This can happen, for example, when
2546    // substituting the outer template arguments ends up causing two
2547    // class template partial specializations of a member class template
2548    // to have identical forms, e.g.,
2549    //
2550    //   template<typename T, typename U>
2551    //   struct Outer {
2552    //     template<typename X, typename Y> struct Inner;
2553    //     template<typename Y> struct Inner<T, Y>;
2554    //     template<typename Y> struct Inner<U, Y>;
2555    //   };
2556    //
2557    //   Outer<int, int> outer; // error: the partial specializations of Inner
2558    //                          // have the same signature.
2559    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2560      << WrittenTy->getType();
2561    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2562      << SemaRef.Context.getTypeDeclType(PrevDecl);
2563    return 0;
2564  }
2565
2566
2567  // Create the class template partial specialization declaration.
2568  ClassTemplatePartialSpecializationDecl *InstPartialSpec
2569    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2570                                                     PartialSpec->getTagKind(),
2571                                                     Owner,
2572                                                     PartialSpec->getLocStart(),
2573                                                     PartialSpec->getLocation(),
2574                                                     InstParams,
2575                                                     ClassTemplate,
2576                                                     Converted.data(),
2577                                                     Converted.size(),
2578                                                     InstTemplateArgs,
2579                                                     CanonType,
2580                                                     0);
2581  // Substitute the nested name specifier, if any.
2582  if (SubstQualifier(PartialSpec, InstPartialSpec))
2583    return 0;
2584
2585  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2586  InstPartialSpec->setTypeAsWritten(WrittenTy);
2587
2588  // Add this partial specialization to the set of class template partial
2589  // specializations.
2590  ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2591  return InstPartialSpec;
2592}
2593
2594/// \brief Instantiate the declaration of a variable template partial
2595/// specialization.
2596///
2597/// \param VarTemplate the (instantiated) variable template that is partially
2598/// specialized by the instantiation of \p PartialSpec.
2599///
2600/// \param PartialSpec the (uninstantiated) variable template partial
2601/// specialization that we are instantiating.
2602///
2603/// \returns The instantiated partial specialization, if successful; otherwise,
2604/// NULL to indicate an error.
2605VarTemplatePartialSpecializationDecl *
2606TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2607    VarTemplateDecl *VarTemplate,
2608    VarTemplatePartialSpecializationDecl *PartialSpec) {
2609  // Create a local instantiation scope for this variable template partial
2610  // specialization, which will contain the instantiations of the template
2611  // parameters.
2612  LocalInstantiationScope Scope(SemaRef);
2613
2614  // Substitute into the template parameters of the variable template partial
2615  // specialization.
2616  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2617  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2618  if (!InstParams)
2619    return 0;
2620
2621  // Substitute into the template arguments of the variable template partial
2622  // specialization.
2623  const ASTTemplateArgumentListInfo *TemplArgInfo
2624    = PartialSpec->getTemplateArgsAsWritten();
2625  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2626                                            TemplArgInfo->RAngleLoc);
2627  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2628                    TemplArgInfo->NumTemplateArgs,
2629                    InstTemplateArgs, TemplateArgs))
2630    return 0;
2631
2632  // Check that the template argument list is well-formed for this
2633  // class template.
2634  SmallVector<TemplateArgument, 4> Converted;
2635  if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2636                                        InstTemplateArgs, false, Converted))
2637    return 0;
2638
2639  // Figure out where to insert this variable template partial specialization
2640  // in the member template's set of variable template partial specializations.
2641  void *InsertPos = 0;
2642  VarTemplateSpecializationDecl *PrevDecl =
2643      VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2644                                             InsertPos);
2645
2646  // Build the canonical type that describes the converted template
2647  // arguments of the variable template partial specialization.
2648  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2649      TemplateName(VarTemplate), Converted.data(), Converted.size());
2650
2651  // Build the fully-sugared type for this variable template
2652  // specialization as the user wrote in the specialization
2653  // itself. This means that we'll pretty-print the type retrieved
2654  // from the specialization's declaration the way that the user
2655  // actually wrote the specialization, rather than formatting the
2656  // name based on the "canonical" representation used to store the
2657  // template arguments in the specialization.
2658  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2659      TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2660      CanonType);
2661
2662  if (PrevDecl) {
2663    // We've already seen a partial specialization with the same template
2664    // parameters and template arguments. This can happen, for example, when
2665    // substituting the outer template arguments ends up causing two
2666    // variable template partial specializations of a member variable template
2667    // to have identical forms, e.g.,
2668    //
2669    //   template<typename T, typename U>
2670    //   struct Outer {
2671    //     template<typename X, typename Y> pair<X,Y> p;
2672    //     template<typename Y> pair<T, Y> p;
2673    //     template<typename Y> pair<U, Y> p;
2674    //   };
2675    //
2676    //   Outer<int, int> outer; // error: the partial specializations of Inner
2677    //                          // have the same signature.
2678    SemaRef.Diag(PartialSpec->getLocation(),
2679                 diag::err_var_partial_spec_redeclared)
2680        << WrittenTy->getType();
2681    SemaRef.Diag(PrevDecl->getLocation(),
2682                 diag::note_var_prev_partial_spec_here);
2683    return 0;
2684  }
2685
2686  // Do substitution on the type of the declaration
2687  TypeSourceInfo *DI = SemaRef.SubstType(
2688      PartialSpec->getTypeSourceInfo(), TemplateArgs,
2689      PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2690  if (!DI)
2691    return 0;
2692
2693  if (DI->getType()->isFunctionType()) {
2694    SemaRef.Diag(PartialSpec->getLocation(),
2695                 diag::err_variable_instantiates_to_function)
2696        << PartialSpec->isStaticDataMember() << DI->getType();
2697    return 0;
2698  }
2699
2700  // Create the variable template partial specialization declaration.
2701  VarTemplatePartialSpecializationDecl *InstPartialSpec =
2702      VarTemplatePartialSpecializationDecl::Create(
2703          SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2704          PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2705          DI, PartialSpec->getStorageClass(), Converted.data(),
2706          Converted.size(), InstTemplateArgs);
2707
2708  // Substitute the nested name specifier, if any.
2709  if (SubstQualifier(PartialSpec, InstPartialSpec))
2710    return 0;
2711
2712  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2713  InstPartialSpec->setTypeAsWritten(WrittenTy);
2714
2715  // Add this partial specialization to the set of variable template partial
2716  // specializations. The instantiation of the initializer is not necessary.
2717  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2718
2719  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
2720                                     LateAttrs, Owner, StartingScope);
2721
2722  return InstPartialSpec;
2723}
2724
2725TypeSourceInfo*
2726TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2727                              SmallVectorImpl<ParmVarDecl *> &Params) {
2728  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2729  assert(OldTInfo && "substituting function without type source info");
2730  assert(Params.empty() && "parameter vector is non-empty at start");
2731
2732  CXXRecordDecl *ThisContext = 0;
2733  unsigned ThisTypeQuals = 0;
2734  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2735    ThisContext = cast<CXXRecordDecl>(Owner);
2736    ThisTypeQuals = Method->getTypeQualifiers();
2737  }
2738
2739  TypeSourceInfo *NewTInfo
2740    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2741                                    D->getTypeSpecStartLoc(),
2742                                    D->getDeclName(),
2743                                    ThisContext, ThisTypeQuals);
2744  if (!NewTInfo)
2745    return 0;
2746
2747  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2748  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2749    if (NewTInfo != OldTInfo) {
2750      // Get parameters from the new type info.
2751      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2752      FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
2753      unsigned NewIdx = 0;
2754      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
2755           OldIdx != NumOldParams; ++OldIdx) {
2756        ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
2757        LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2758
2759        Optional<unsigned> NumArgumentsInExpansion;
2760        if (OldParam->isParameterPack())
2761          NumArgumentsInExpansion =
2762              SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2763                                                 TemplateArgs);
2764        if (!NumArgumentsInExpansion) {
2765          // Simple case: normal parameter, or a parameter pack that's
2766          // instantiated to a (still-dependent) parameter pack.
2767          ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
2768          Params.push_back(NewParam);
2769          Scope->InstantiatedLocal(OldParam, NewParam);
2770        } else {
2771          // Parameter pack expansion: make the instantiation an argument pack.
2772          Scope->MakeInstantiatedLocalArgPack(OldParam);
2773          for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
2774            ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
2775            Params.push_back(NewParam);
2776            Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2777          }
2778        }
2779      }
2780    } else {
2781      // The function type itself was not dependent and therefore no
2782      // substitution occurred. However, we still need to instantiate
2783      // the function parameters themselves.
2784      const FunctionProtoType *OldProto =
2785          cast<FunctionProtoType>(OldProtoLoc.getType());
2786      for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
2787        ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2788        if (!OldParam) {
2789          Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2790              D, D->getLocation(), OldProto->getArgType(i)));
2791          continue;
2792        }
2793
2794        ParmVarDecl *Parm =
2795            cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
2796        if (!Parm)
2797          return 0;
2798        Params.push_back(Parm);
2799      }
2800    }
2801  } else {
2802    // If the type of this function, after ignoring parentheses, is not
2803    // *directly* a function type, then we're instantiating a function that
2804    // was declared via a typedef or with attributes, e.g.,
2805    //
2806    //   typedef int functype(int, int);
2807    //   functype func;
2808    //   int __cdecl meth(int, int);
2809    //
2810    // In this case, we'll just go instantiate the ParmVarDecls that we
2811    // synthesized in the method declaration.
2812    SmallVector<QualType, 4> ParamTypes;
2813    if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2814                               D->getNumParams(), TemplateArgs, ParamTypes,
2815                               &Params))
2816      return 0;
2817  }
2818
2819  return NewTInfo;
2820}
2821
2822/// Introduce the instantiated function parameters into the local
2823/// instantiation scope, and set the parameter names to those used
2824/// in the template.
2825static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2826                                             const FunctionDecl *PatternDecl,
2827                                             LocalInstantiationScope &Scope,
2828                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2829  unsigned FParamIdx = 0;
2830  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2831    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2832    if (!PatternParam->isParameterPack()) {
2833      // Simple case: not a parameter pack.
2834      assert(FParamIdx < Function->getNumParams());
2835      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2836      FunctionParam->setDeclName(PatternParam->getDeclName());
2837      Scope.InstantiatedLocal(PatternParam, FunctionParam);
2838      ++FParamIdx;
2839      continue;
2840    }
2841
2842    // Expand the parameter pack.
2843    Scope.MakeInstantiatedLocalArgPack(PatternParam);
2844    Optional<unsigned> NumArgumentsInExpansion
2845      = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
2846    assert(NumArgumentsInExpansion &&
2847           "should only be called when all template arguments are known");
2848    for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
2849      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2850      FunctionParam->setDeclName(PatternParam->getDeclName());
2851      Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2852      ++FParamIdx;
2853    }
2854  }
2855}
2856
2857static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2858                                     const FunctionProtoType *Proto,
2859                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2860  assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2861
2862  // C++11 [expr.prim.general]p3:
2863  //   If a declaration declares a member function or member function
2864  //   template of a class X, the expression this is a prvalue of type
2865  //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2866  //   and the end of the function-definition, member-declarator, or
2867  //   declarator.
2868  CXXRecordDecl *ThisContext = 0;
2869  unsigned ThisTypeQuals = 0;
2870  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2871    ThisContext = Method->getParent();
2872    ThisTypeQuals = Method->getTypeQualifiers();
2873  }
2874  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
2875                                   SemaRef.getLangOpts().CPlusPlus11);
2876
2877  // The function has an exception specification or a "noreturn"
2878  // attribute. Substitute into each of the exception types.
2879  SmallVector<QualType, 4> Exceptions;
2880  for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2881    // FIXME: Poor location information!
2882    if (const PackExpansionType *PackExpansion
2883          = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2884      // We have a pack expansion. Instantiate it.
2885      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2886      SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2887                                              Unexpanded);
2888      assert(!Unexpanded.empty() &&
2889             "Pack expansion without parameter packs?");
2890
2891      bool Expand = false;
2892      bool RetainExpansion = false;
2893      Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
2894      if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2895                                                  SourceRange(),
2896                                                  Unexpanded,
2897                                                  TemplateArgs,
2898                                                  Expand,
2899                                                  RetainExpansion,
2900                                                  NumExpansions))
2901        break;
2902
2903      if (!Expand) {
2904        // We can't expand this pack expansion into separate arguments yet;
2905        // just substitute into the pattern and create a new pack expansion
2906        // type.
2907        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2908        QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2909                                       TemplateArgs,
2910                                     New->getLocation(), New->getDeclName());
2911        if (T.isNull())
2912          break;
2913
2914        T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2915        Exceptions.push_back(T);
2916        continue;
2917      }
2918
2919      // Substitute into the pack expansion pattern for each template
2920      bool Invalid = false;
2921      for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2922        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2923
2924        QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2925                                       TemplateArgs,
2926                                     New->getLocation(), New->getDeclName());
2927        if (T.isNull()) {
2928          Invalid = true;
2929          break;
2930        }
2931
2932        Exceptions.push_back(T);
2933      }
2934
2935      if (Invalid)
2936        break;
2937
2938      continue;
2939    }
2940
2941    QualType T
2942      = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2943                          New->getLocation(), New->getDeclName());
2944    if (T.isNull() ||
2945        SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2946      continue;
2947
2948    Exceptions.push_back(T);
2949  }
2950  Expr *NoexceptExpr = 0;
2951  if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2952    EnterExpressionEvaluationContext Unevaluated(SemaRef,
2953                                                 Sema::ConstantEvaluated);
2954    ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2955    if (E.isUsable())
2956      E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2957
2958    if (E.isUsable()) {
2959      NoexceptExpr = E.take();
2960      if (!NoexceptExpr->isTypeDependent() &&
2961          !NoexceptExpr->isValueDependent())
2962        NoexceptExpr
2963          = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2964              0, diag::err_noexcept_needs_constant_expression,
2965              /*AllowFold*/ false).take();
2966    }
2967  }
2968
2969  // Rebuild the function type
2970  const FunctionProtoType *NewProto
2971    = New->getType()->getAs<FunctionProtoType>();
2972  assert(NewProto && "Template instantiation without function prototype?");
2973
2974  FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2975  EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2976  EPI.NumExceptions = Exceptions.size();
2977  EPI.Exceptions = Exceptions.data();
2978  EPI.NoexceptExpr = NoexceptExpr;
2979
2980  New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2981                                               NewProto->getArgTypes(), EPI));
2982}
2983
2984void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2985                                    FunctionDecl *Decl) {
2986  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2987  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
2988    return;
2989
2990  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2991                             InstantiatingTemplate::ExceptionSpecification());
2992  if (Inst.isInvalid()) {
2993    // We hit the instantiation depth limit. Clear the exception specification
2994    // so that our callers don't have to cope with EST_Uninstantiated.
2995    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2996    EPI.ExceptionSpecType = EST_None;
2997    Decl->setType(Context.getFunctionType(Proto->getResultType(),
2998                                          Proto->getArgTypes(), EPI));
2999    return;
3000  }
3001
3002  // Enter the scope of this instantiation. We don't use
3003  // PushDeclContext because we don't have a scope.
3004  Sema::ContextRAII savedContext(*this, Decl);
3005  LocalInstantiationScope Scope(*this);
3006
3007  MultiLevelTemplateArgumentList TemplateArgs =
3008    getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
3009
3010  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3011  addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
3012
3013  ::InstantiateExceptionSpec(*this, Decl,
3014                             Template->getType()->castAs<FunctionProtoType>(),
3015                             TemplateArgs);
3016}
3017
3018/// \brief Initializes the common fields of an instantiation function
3019/// declaration (New) from the corresponding fields of its template (Tmpl).
3020///
3021/// \returns true if there was an error
3022bool
3023TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3024                                                    FunctionDecl *Tmpl) {
3025  if (Tmpl->isDeleted())
3026    New->setDeletedAsWritten();
3027
3028  // If we are performing substituting explicitly-specified template arguments
3029  // or deduced template arguments into a function template and we reach this
3030  // point, we are now past the point where SFINAE applies and have committed
3031  // to keeping the new function template specialization. We therefore
3032  // convert the active template instantiation for the function template
3033  // into a template instantiation for this specific function template
3034  // specialization, which is not a SFINAE context, so that we diagnose any
3035  // further errors in the declaration itself.
3036  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3037  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3038  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3039      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3040    if (FunctionTemplateDecl *FunTmpl
3041          = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3042      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3043             "Deduction from the wrong function template?");
3044      (void) FunTmpl;
3045      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3046      ActiveInst.Entity = New;
3047    }
3048  }
3049
3050  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3051  assert(Proto && "Function template without prototype?");
3052
3053  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3054    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3055
3056    // DR1330: In C++11, defer instantiation of a non-trivial
3057    // exception specification.
3058    if (SemaRef.getLangOpts().CPlusPlus11 &&
3059        EPI.ExceptionSpecType != EST_None &&
3060        EPI.ExceptionSpecType != EST_DynamicNone &&
3061        EPI.ExceptionSpecType != EST_BasicNoexcept) {
3062      FunctionDecl *ExceptionSpecTemplate = Tmpl;
3063      if (EPI.ExceptionSpecType == EST_Uninstantiated)
3064        ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
3065      ExceptionSpecificationType NewEST = EST_Uninstantiated;
3066      if (EPI.ExceptionSpecType == EST_Unevaluated)
3067        NewEST = EST_Unevaluated;
3068
3069      // Mark the function has having an uninstantiated exception specification.
3070      const FunctionProtoType *NewProto
3071        = New->getType()->getAs<FunctionProtoType>();
3072      assert(NewProto && "Template instantiation without function prototype?");
3073      EPI = NewProto->getExtProtoInfo();
3074      EPI.ExceptionSpecType = NewEST;
3075      EPI.ExceptionSpecDecl = New;
3076      EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
3077      New->setType(SemaRef.Context.getFunctionType(
3078          NewProto->getResultType(), NewProto->getArgTypes(), EPI));
3079    } else {
3080      ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3081    }
3082  }
3083
3084  // Get the definition. Leaves the variable unchanged if undefined.
3085  const FunctionDecl *Definition = Tmpl;
3086  Tmpl->isDefined(Definition);
3087
3088  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3089                           LateAttrs, StartingScope);
3090
3091  return false;
3092}
3093
3094/// \brief Initializes common fields of an instantiated method
3095/// declaration (New) from the corresponding fields of its template
3096/// (Tmpl).
3097///
3098/// \returns true if there was an error
3099bool
3100TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3101                                                  CXXMethodDecl *Tmpl) {
3102  if (InitFunctionInstantiation(New, Tmpl))
3103    return true;
3104
3105  New->setAccess(Tmpl->getAccess());
3106  if (Tmpl->isVirtualAsWritten())
3107    New->setVirtualAsWritten(true);
3108
3109  // FIXME: New needs a pointer to Tmpl
3110  return false;
3111}
3112
3113/// \brief Instantiate the definition of the given function from its
3114/// template.
3115///
3116/// \param PointOfInstantiation the point at which the instantiation was
3117/// required. Note that this is not precisely a "point of instantiation"
3118/// for the function, but it's close.
3119///
3120/// \param Function the already-instantiated declaration of a
3121/// function template specialization or member function of a class template
3122/// specialization.
3123///
3124/// \param Recursive if true, recursively instantiates any functions that
3125/// are required by this instantiation.
3126///
3127/// \param DefinitionRequired if true, then we are performing an explicit
3128/// instantiation where the body of the function is required. Complain if
3129/// there is no such body.
3130void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3131                                         FunctionDecl *Function,
3132                                         bool Recursive,
3133                                         bool DefinitionRequired) {
3134  if (Function->isInvalidDecl() || Function->isDefined())
3135    return;
3136
3137  // Never instantiate an explicit specialization except if it is a class scope
3138  // explicit specialization.
3139  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3140      !Function->getClassScopeSpecializationPattern())
3141    return;
3142
3143  // Find the function body that we'll be substituting.
3144  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3145  assert(PatternDecl && "instantiating a non-template");
3146
3147  Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3148  assert(PatternDecl && "template definition is not a template");
3149  if (!Pattern) {
3150    // Try to find a defaulted definition
3151    PatternDecl->isDefined(PatternDecl);
3152  }
3153  assert(PatternDecl && "template definition is not a template");
3154
3155  // Postpone late parsed template instantiations.
3156  if (PatternDecl->isLateTemplateParsed() &&
3157      !LateTemplateParser) {
3158    PendingInstantiations.push_back(
3159      std::make_pair(Function, PointOfInstantiation));
3160    return;
3161  }
3162
3163  // Call the LateTemplateParser callback if there is a need to late parse
3164  // a templated function definition.
3165  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3166      LateTemplateParser) {
3167    // FIXME: Optimize to allow individual templates to be deserialized.
3168    if (PatternDecl->isFromASTFile())
3169      ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3170
3171    LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3172    assert(LPT && "missing LateParsedTemplate");
3173    LateTemplateParser(OpaqueParser, *LPT);
3174    Pattern = PatternDecl->getBody(PatternDecl);
3175  }
3176
3177  if (!Pattern && !PatternDecl->isDefaulted()) {
3178    if (DefinitionRequired) {
3179      if (Function->getPrimaryTemplate())
3180        Diag(PointOfInstantiation,
3181             diag::err_explicit_instantiation_undefined_func_template)
3182          << Function->getPrimaryTemplate();
3183      else
3184        Diag(PointOfInstantiation,
3185             diag::err_explicit_instantiation_undefined_member)
3186          << 1 << Function->getDeclName() << Function->getDeclContext();
3187
3188      if (PatternDecl)
3189        Diag(PatternDecl->getLocation(),
3190             diag::note_explicit_instantiation_here);
3191      Function->setInvalidDecl();
3192    } else if (Function->getTemplateSpecializationKind()
3193                 == TSK_ExplicitInstantiationDefinition) {
3194      PendingInstantiations.push_back(
3195        std::make_pair(Function, PointOfInstantiation));
3196    }
3197
3198    return;
3199  }
3200
3201  // C++1y [temp.explicit]p10:
3202  //   Except for inline functions, declarations with types deduced from their
3203  //   initializer or return value, and class template specializations, other
3204  //   explicit instantiation declarations have the effect of suppressing the
3205  //   implicit instantiation of the entity to which they refer.
3206  if (Function->getTemplateSpecializationKind()
3207        == TSK_ExplicitInstantiationDeclaration &&
3208      !PatternDecl->isInlined() &&
3209      !PatternDecl->getResultType()->getContainedAutoType())
3210    return;
3211
3212  if (PatternDecl->isInlined())
3213    Function->setImplicitlyInline();
3214
3215  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3216  if (Inst.isInvalid())
3217    return;
3218
3219  // Copy the inner loc start from the pattern.
3220  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3221
3222  // If we're performing recursive template instantiation, create our own
3223  // queue of pending implicit instantiations that we will instantiate later,
3224  // while we're still within our own instantiation context.
3225  SmallVector<VTableUse, 16> SavedVTableUses;
3226  std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3227  std::deque<PendingImplicitInstantiation>
3228                              SavedPendingLocalImplicitInstantiations;
3229  SavedPendingLocalImplicitInstantiations.swap(
3230                                  PendingLocalImplicitInstantiations);
3231  if (Recursive) {
3232    VTableUses.swap(SavedVTableUses);
3233    PendingInstantiations.swap(SavedPendingInstantiations);
3234  }
3235
3236  EnterExpressionEvaluationContext EvalContext(*this,
3237                                               Sema::PotentiallyEvaluated);
3238
3239  // Introduce a new scope where local variable instantiations will be
3240  // recorded, unless we're actually a member function within a local
3241  // class, in which case we need to merge our results with the parent
3242  // scope (of the enclosing function).
3243  bool MergeWithParentScope = false;
3244  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3245    MergeWithParentScope = Rec->isLocalClass();
3246
3247  LocalInstantiationScope Scope(*this, MergeWithParentScope);
3248
3249  if (PatternDecl->isDefaulted())
3250    SetDeclDefaulted(Function, PatternDecl->getLocation());
3251  else {
3252    ActOnStartOfFunctionDef(0, Function);
3253
3254    // Enter the scope of this instantiation. We don't use
3255    // PushDeclContext because we don't have a scope.
3256    Sema::ContextRAII savedContext(*this, Function);
3257
3258    MultiLevelTemplateArgumentList TemplateArgs =
3259      getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3260
3261    addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3262                                     TemplateArgs);
3263
3264    // If this is a constructor, instantiate the member initializers.
3265    if (const CXXConstructorDecl *Ctor =
3266          dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3267      InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3268                                 TemplateArgs);
3269    }
3270
3271    // Instantiate the function body.
3272    StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3273
3274    if (Body.isInvalid())
3275      Function->setInvalidDecl();
3276
3277    ActOnFinishFunctionBody(Function, Body.get(),
3278                            /*IsInstantiation=*/true);
3279
3280    PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3281
3282    savedContext.pop();
3283  }
3284
3285  DeclGroupRef DG(Function);
3286  Consumer.HandleTopLevelDecl(DG);
3287
3288  // This class may have local implicit instantiations that need to be
3289  // instantiation within this scope.
3290  PerformPendingInstantiations(/*LocalOnly=*/true);
3291  Scope.Exit();
3292
3293  if (Recursive) {
3294    // Define any pending vtables.
3295    DefineUsedVTables();
3296
3297    // Instantiate any pending implicit instantiations found during the
3298    // instantiation of this template.
3299    PerformPendingInstantiations();
3300
3301    // Restore the set of pending vtables.
3302    assert(VTableUses.empty() &&
3303           "VTableUses should be empty before it is discarded.");
3304    VTableUses.swap(SavedVTableUses);
3305
3306    // Restore the set of pending implicit instantiations.
3307    assert(PendingInstantiations.empty() &&
3308           "PendingInstantiations should be empty before it is discarded.");
3309    PendingInstantiations.swap(SavedPendingInstantiations);
3310  }
3311  SavedPendingLocalImplicitInstantiations.swap(
3312                            PendingLocalImplicitInstantiations);
3313}
3314
3315VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3316    VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3317    const TemplateArgumentList &TemplateArgList,
3318    const TemplateArgumentListInfo &TemplateArgsInfo,
3319    SmallVectorImpl<TemplateArgument> &Converted,
3320    SourceLocation PointOfInstantiation, void *InsertPos,
3321    LateInstantiatedAttrVec *LateAttrs,
3322    LocalInstantiationScope *StartingScope) {
3323  if (FromVar->isInvalidDecl())
3324    return 0;
3325
3326  InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3327  if (Inst.isInvalid())
3328    return 0;
3329
3330  MultiLevelTemplateArgumentList TemplateArgLists;
3331  TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3332
3333  // Instantiate the first declaration of the variable template: for a partial
3334  // specialization of a static data member template, the first declaration may
3335  // or may not be the declaration in the class; if it's in the class, we want
3336  // to instantiate a member in the class (a declaration), and if it's outside,
3337  // we want to instantiate a definition.
3338  FromVar = FromVar->getFirstDecl();
3339
3340  MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3341  TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3342                                        MultiLevelList);
3343
3344  // TODO: Set LateAttrs and StartingScope ...
3345
3346  return cast_or_null<VarTemplateSpecializationDecl>(
3347      Instantiator.VisitVarTemplateSpecializationDecl(
3348          VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3349}
3350
3351/// \brief Instantiates a variable template specialization by completing it
3352/// with appropriate type information and initializer.
3353VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3354    VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3355    const MultiLevelTemplateArgumentList &TemplateArgs) {
3356
3357  // Do substitution on the type of the declaration
3358  TypeSourceInfo *DI =
3359      SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3360                PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3361  if (!DI)
3362    return 0;
3363
3364  // Update the type of this variable template specialization.
3365  VarSpec->setType(DI->getType());
3366
3367  // Instantiate the initializer.
3368  InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3369
3370  return VarSpec;
3371}
3372
3373/// BuildVariableInstantiation - Used after a new variable has been created.
3374/// Sets basic variable data and decides whether to postpone the
3375/// variable instantiation.
3376void Sema::BuildVariableInstantiation(
3377    VarDecl *NewVar, VarDecl *OldVar,
3378    const MultiLevelTemplateArgumentList &TemplateArgs,
3379    LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3380    LocalInstantiationScope *StartingScope,
3381    bool InstantiatingVarTemplate) {
3382
3383  // If we are instantiating a local extern declaration, the
3384  // instantiation belongs lexically to the containing function.
3385  // If we are instantiating a static data member defined
3386  // out-of-line, the instantiation will have the same lexical
3387  // context (which will be a namespace scope) as the template.
3388  if (OldVar->isLocalExternDecl()) {
3389    NewVar->setLocalExternDecl();
3390    NewVar->setLexicalDeclContext(Owner);
3391  } else if (OldVar->isOutOfLine())
3392    NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3393  NewVar->setTSCSpec(OldVar->getTSCSpec());
3394  NewVar->setInitStyle(OldVar->getInitStyle());
3395  NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3396  NewVar->setConstexpr(OldVar->isConstexpr());
3397  NewVar->setInitCapture(OldVar->isInitCapture());
3398  NewVar->setPreviousDeclInSameBlockScope(
3399      OldVar->isPreviousDeclInSameBlockScope());
3400  NewVar->setAccess(OldVar->getAccess());
3401
3402  if (!OldVar->isStaticDataMember()) {
3403    if (OldVar->isUsed(false))
3404      NewVar->setIsUsed();
3405    NewVar->setReferenced(OldVar->isReferenced());
3406  }
3407
3408  // See if the old variable had a type-specifier that defined an anonymous tag.
3409  // If it did, mark the new variable as being the declarator for the new
3410  // anonymous tag.
3411  if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3412    TagDecl *OldTag = OldTagType->getDecl();
3413    if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3414      TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3415      assert(!NewTag->hasNameForLinkage() &&
3416             !NewTag->hasDeclaratorForAnonDecl());
3417      NewTag->setDeclaratorForAnonDecl(NewVar);
3418    }
3419  }
3420
3421  InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3422
3423  if (NewVar->hasAttrs())
3424    CheckAlignasUnderalignment(NewVar);
3425
3426  LookupResult Previous(
3427      *this, NewVar->getDeclName(), NewVar->getLocation(),
3428      NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3429                                  : Sema::LookupOrdinaryName,
3430      Sema::ForRedeclaration);
3431
3432  if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl()) {
3433    // We have a previous declaration. Use that one, so we merge with the
3434    // right type.
3435    if (NamedDecl *NewPrev = FindInstantiatedDecl(
3436            NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3437      Previous.addDecl(NewPrev);
3438  } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3439             OldVar->hasLinkage())
3440    LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3441  CheckVariableDeclaration(NewVar, Previous);
3442
3443  if (!InstantiatingVarTemplate) {
3444    NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3445    if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3446      NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3447  }
3448
3449  if (!OldVar->isOutOfLine()) {
3450    if (NewVar->getDeclContext()->isFunctionOrMethod())
3451      CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3452  }
3453
3454  // Link instantiations of static data members back to the template from
3455  // which they were instantiated.
3456  if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3457    NewVar->setInstantiationOfStaticDataMember(OldVar,
3458                                               TSK_ImplicitInstantiation);
3459
3460  // Delay instantiation of the initializer for variable templates until a
3461  // definition of the variable is needed.
3462  if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate)
3463    InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3464
3465  // Diagnose unused local variables with dependent types, where the diagnostic
3466  // will have been deferred.
3467  if (!NewVar->isInvalidDecl() &&
3468      NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3469      OldVar->getType()->isDependentType())
3470    DiagnoseUnusedDecl(NewVar);
3471}
3472
3473/// \brief Instantiate the initializer of a variable.
3474void Sema::InstantiateVariableInitializer(
3475    VarDecl *Var, VarDecl *OldVar,
3476    const MultiLevelTemplateArgumentList &TemplateArgs) {
3477
3478  if (Var->getAnyInitializer())
3479    // We already have an initializer in the class.
3480    return;
3481
3482  if (OldVar->getInit()) {
3483    if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3484      PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3485    else
3486      PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3487
3488    // Instantiate the initializer.
3489    ExprResult Init =
3490        SubstInitializer(OldVar->getInit(), TemplateArgs,
3491                         OldVar->getInitStyle() == VarDecl::CallInit);
3492    if (!Init.isInvalid()) {
3493      bool TypeMayContainAuto = true;
3494      if (Init.get()) {
3495        bool DirectInit = OldVar->isDirectInit();
3496        AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3497      } else
3498        ActOnUninitializedDecl(Var, TypeMayContainAuto);
3499    } else {
3500      // FIXME: Not too happy about invalidating the declaration
3501      // because of a bogus initializer.
3502      Var->setInvalidDecl();
3503    }
3504
3505    PopExpressionEvaluationContext();
3506  } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3507             !Var->isCXXForRangeDecl())
3508    ActOnUninitializedDecl(Var, false);
3509}
3510
3511/// \brief Instantiate the definition of the given variable from its
3512/// template.
3513///
3514/// \param PointOfInstantiation the point at which the instantiation was
3515/// required. Note that this is not precisely a "point of instantiation"
3516/// for the function, but it's close.
3517///
3518/// \param Var the already-instantiated declaration of a static member
3519/// variable of a class template specialization.
3520///
3521/// \param Recursive if true, recursively instantiates any functions that
3522/// are required by this instantiation.
3523///
3524/// \param DefinitionRequired if true, then we are performing an explicit
3525/// instantiation where an out-of-line definition of the member variable
3526/// is required. Complain if there is no such definition.
3527void Sema::InstantiateStaticDataMemberDefinition(
3528                                          SourceLocation PointOfInstantiation,
3529                                                 VarDecl *Var,
3530                                                 bool Recursive,
3531                                                 bool DefinitionRequired) {
3532  InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3533                                DefinitionRequired);
3534}
3535
3536void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3537                                         VarDecl *Var, bool Recursive,
3538                                         bool DefinitionRequired) {
3539  if (Var->isInvalidDecl())
3540    return;
3541
3542  VarTemplateSpecializationDecl *VarSpec =
3543      dyn_cast<VarTemplateSpecializationDecl>(Var);
3544  VarDecl *PatternDecl = 0, *Def = 0;
3545  MultiLevelTemplateArgumentList TemplateArgs =
3546      getTemplateInstantiationArgs(Var);
3547
3548  if (VarSpec) {
3549    // If this is a variable template specialization, make sure that it is
3550    // non-dependent, then find its instantiation pattern.
3551    bool InstantiationDependent = false;
3552    assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3553               VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3554           "Only instantiate variable template specializations that are "
3555           "not type-dependent");
3556    (void)InstantiationDependent;
3557
3558    // Find the variable initialization that we'll be substituting. If the
3559    // pattern was instantiated from a member template, look back further to
3560    // find the real pattern.
3561    assert(VarSpec->getSpecializedTemplate() &&
3562           "Specialization without specialized template?");
3563    llvm::PointerUnion<VarTemplateDecl *,
3564                       VarTemplatePartialSpecializationDecl *> PatternPtr =
3565        VarSpec->getSpecializedTemplateOrPartial();
3566    if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3567      VarTemplatePartialSpecializationDecl *Tmpl =
3568          PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3569      while (VarTemplatePartialSpecializationDecl *From =
3570                 Tmpl->getInstantiatedFromMember()) {
3571        if (Tmpl->isMemberSpecialization())
3572          break;
3573
3574        Tmpl = From;
3575      }
3576      PatternDecl = Tmpl;
3577    } else {
3578      VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3579      while (VarTemplateDecl *From =
3580                 Tmpl->getInstantiatedFromMemberTemplate()) {
3581        if (Tmpl->isMemberSpecialization())
3582          break;
3583
3584        Tmpl = From;
3585      }
3586      PatternDecl = Tmpl->getTemplatedDecl();
3587    }
3588
3589    // If this is a static data member template, there might be an
3590    // uninstantiated initializer on the declaration. If so, instantiate
3591    // it now.
3592    if (PatternDecl->isStaticDataMember() &&
3593        (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
3594        !Var->hasInit()) {
3595      // FIXME: Factor out the duplicated instantiation context setup/tear down
3596      // code here.
3597      InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3598      if (Inst.isInvalid())
3599        return;
3600
3601      // If we're performing recursive template instantiation, create our own
3602      // queue of pending implicit instantiations that we will instantiate
3603      // later, while we're still within our own instantiation context.
3604      SmallVector<VTableUse, 16> SavedVTableUses;
3605      std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3606      if (Recursive) {
3607        VTableUses.swap(SavedVTableUses);
3608        PendingInstantiations.swap(SavedPendingInstantiations);
3609      }
3610
3611      LocalInstantiationScope Local(*this);
3612
3613      // Enter the scope of this instantiation. We don't use
3614      // PushDeclContext because we don't have a scope.
3615      ContextRAII PreviousContext(*this, Var->getDeclContext());
3616      InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3617      PreviousContext.pop();
3618
3619      // FIXME: Need to inform the ASTConsumer that we instantiated the
3620      // initializer?
3621
3622      // This variable may have local implicit instantiations that need to be
3623      // instantiated within this scope.
3624      PerformPendingInstantiations(/*LocalOnly=*/true);
3625
3626      Local.Exit();
3627
3628      if (Recursive) {
3629        // Define any newly required vtables.
3630        DefineUsedVTables();
3631
3632        // Instantiate any pending implicit instantiations found during the
3633        // instantiation of this template.
3634        PerformPendingInstantiations();
3635
3636        // Restore the set of pending vtables.
3637        assert(VTableUses.empty() &&
3638               "VTableUses should be empty before it is discarded.");
3639        VTableUses.swap(SavedVTableUses);
3640
3641        // Restore the set of pending implicit instantiations.
3642        assert(PendingInstantiations.empty() &&
3643               "PendingInstantiations should be empty before it is discarded.");
3644        PendingInstantiations.swap(SavedPendingInstantiations);
3645      }
3646    }
3647
3648    // Find actual definition
3649    Def = PatternDecl->getDefinition(getASTContext());
3650  } else {
3651    // If this is a static data member, find its out-of-line definition.
3652    assert(Var->isStaticDataMember() && "not a static data member?");
3653    PatternDecl = Var->getInstantiatedFromStaticDataMember();
3654
3655    assert(PatternDecl && "data member was not instantiated from a template?");
3656    assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3657    Def = PatternDecl->getOutOfLineDefinition();
3658  }
3659
3660  // If we don't have a definition of the variable template, we won't perform
3661  // any instantiation. Rather, we rely on the user to instantiate this
3662  // definition (or provide a specialization for it) in another translation
3663  // unit.
3664  if (!Def) {
3665    if (DefinitionRequired) {
3666      if (VarSpec)
3667        Diag(PointOfInstantiation,
3668             diag::err_explicit_instantiation_undefined_var_template) << Var;
3669      else
3670        Diag(PointOfInstantiation,
3671             diag::err_explicit_instantiation_undefined_member)
3672            << 2 << Var->getDeclName() << Var->getDeclContext();
3673      Diag(PatternDecl->getLocation(),
3674           diag::note_explicit_instantiation_here);
3675      if (VarSpec)
3676        Var->setInvalidDecl();
3677    } else if (Var->getTemplateSpecializationKind()
3678                 == TSK_ExplicitInstantiationDefinition) {
3679      PendingInstantiations.push_back(
3680        std::make_pair(Var, PointOfInstantiation));
3681    }
3682
3683    return;
3684  }
3685
3686  TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3687
3688  // Never instantiate an explicit specialization.
3689  if (TSK == TSK_ExplicitSpecialization)
3690    return;
3691
3692  // C++11 [temp.explicit]p10:
3693  //   Except for inline functions, [...] explicit instantiation declarations
3694  //   have the effect of suppressing the implicit instantiation of the entity
3695  //   to which they refer.
3696  if (TSK == TSK_ExplicitInstantiationDeclaration)
3697    return;
3698
3699  // Make sure to pass the instantiated variable to the consumer at the end.
3700  struct PassToConsumerRAII {
3701    ASTConsumer &Consumer;
3702    VarDecl *Var;
3703
3704    PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3705      : Consumer(Consumer), Var(Var) { }
3706
3707    ~PassToConsumerRAII() {
3708      Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3709    }
3710  } PassToConsumerRAII(Consumer, Var);
3711
3712  // If we already have a definition, we're done.
3713  if (VarDecl *Def = Var->getDefinition()) {
3714    // We may be explicitly instantiating something we've already implicitly
3715    // instantiated.
3716    Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3717                                       PointOfInstantiation);
3718    return;
3719  }
3720
3721  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3722  if (Inst.isInvalid())
3723    return;
3724
3725  // If we're performing recursive template instantiation, create our own
3726  // queue of pending implicit instantiations that we will instantiate later,
3727  // while we're still within our own instantiation context.
3728  SmallVector<VTableUse, 16> SavedVTableUses;
3729  std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3730  if (Recursive) {
3731    VTableUses.swap(SavedVTableUses);
3732    PendingInstantiations.swap(SavedPendingInstantiations);
3733  }
3734
3735  // Enter the scope of this instantiation. We don't use
3736  // PushDeclContext because we don't have a scope.
3737  ContextRAII PreviousContext(*this, Var->getDeclContext());
3738  LocalInstantiationScope Local(*this);
3739
3740  VarDecl *OldVar = Var;
3741  if (!VarSpec)
3742    Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3743                                          TemplateArgs));
3744  else if (Var->isStaticDataMember() &&
3745           Var->getLexicalDeclContext()->isRecord()) {
3746    // We need to instantiate the definition of a static data member template,
3747    // and all we have is the in-class declaration of it. Instantiate a separate
3748    // declaration of the definition.
3749    TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3750                                          TemplateArgs);
3751    Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3752        VarSpec->getSpecializedTemplate(), Def, 0,
3753        VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3754    if (Var) {
3755      llvm::PointerUnion<VarTemplateDecl *,
3756                         VarTemplatePartialSpecializationDecl *> PatternPtr =
3757          VarSpec->getSpecializedTemplateOrPartial();
3758      if (VarTemplatePartialSpecializationDecl *Partial =
3759          PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3760        cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3761            Partial, &VarSpec->getTemplateInstantiationArgs());
3762
3763      // Merge the definition with the declaration.
3764      LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3765                     LookupOrdinaryName, ForRedeclaration);
3766      R.addDecl(OldVar);
3767      MergeVarDecl(Var, R);
3768
3769      // Attach the initializer.
3770      InstantiateVariableInitializer(Var, Def, TemplateArgs);
3771    }
3772  } else
3773    // Complete the existing variable's definition with an appropriately
3774    // substituted type and initializer.
3775    Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
3776
3777  PreviousContext.pop();
3778
3779  if (Var) {
3780    PassToConsumerRAII.Var = Var;
3781    Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3782                                       OldVar->getPointOfInstantiation());
3783  }
3784
3785  // This variable may have local implicit instantiations that need to be
3786  // instantiated within this scope.
3787  PerformPendingInstantiations(/*LocalOnly=*/true);
3788
3789  Local.Exit();
3790
3791  if (Recursive) {
3792    // Define any newly required vtables.
3793    DefineUsedVTables();
3794
3795    // Instantiate any pending implicit instantiations found during the
3796    // instantiation of this template.
3797    PerformPendingInstantiations();
3798
3799    // Restore the set of pending vtables.
3800    assert(VTableUses.empty() &&
3801           "VTableUses should be empty before it is discarded.");
3802    VTableUses.swap(SavedVTableUses);
3803
3804    // Restore the set of pending implicit instantiations.
3805    assert(PendingInstantiations.empty() &&
3806           "PendingInstantiations should be empty before it is discarded.");
3807    PendingInstantiations.swap(SavedPendingInstantiations);
3808  }
3809}
3810
3811void
3812Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3813                                 const CXXConstructorDecl *Tmpl,
3814                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3815
3816  SmallVector<CXXCtorInitializer*, 4> NewInits;
3817  bool AnyErrors = Tmpl->isInvalidDecl();
3818
3819  // Instantiate all the initializers.
3820  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
3821                                            InitsEnd = Tmpl->init_end();
3822       Inits != InitsEnd; ++Inits) {
3823    CXXCtorInitializer *Init = *Inits;
3824
3825    // Only instantiate written initializers, let Sema re-construct implicit
3826    // ones.
3827    if (!Init->isWritten())
3828      continue;
3829
3830    SourceLocation EllipsisLoc;
3831
3832    if (Init->isPackExpansion()) {
3833      // This is a pack expansion. We should expand it now.
3834      TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
3835      SmallVector<UnexpandedParameterPack, 4> Unexpanded;
3836      collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3837      collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
3838      bool ShouldExpand = false;
3839      bool RetainExpansion = false;
3840      Optional<unsigned> NumExpansions;
3841      if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
3842                                          BaseTL.getSourceRange(),
3843                                          Unexpanded,
3844                                          TemplateArgs, ShouldExpand,
3845                                          RetainExpansion,
3846                                          NumExpansions)) {
3847        AnyErrors = true;
3848        New->setInvalidDecl();
3849        continue;
3850      }
3851      assert(ShouldExpand && "Partial instantiation of base initializer?");
3852
3853      // Loop over all of the arguments in the argument pack(s),
3854      for (unsigned I = 0; I != *NumExpansions; ++I) {
3855        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3856
3857        // Instantiate the initializer.
3858        ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3859                                               /*CXXDirectInit=*/true);
3860        if (TempInit.isInvalid()) {
3861          AnyErrors = true;
3862          break;
3863        }
3864
3865        // Instantiate the base type.
3866        TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
3867                                              TemplateArgs,
3868                                              Init->getSourceLocation(),
3869                                              New->getDeclName());
3870        if (!BaseTInfo) {
3871          AnyErrors = true;
3872          break;
3873        }
3874
3875        // Build the initializer.
3876        MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
3877                                                     BaseTInfo, TempInit.take(),
3878                                                     New->getParent(),
3879                                                     SourceLocation());
3880        if (NewInit.isInvalid()) {
3881          AnyErrors = true;
3882          break;
3883        }
3884
3885        NewInits.push_back(NewInit.get());
3886      }
3887
3888      continue;
3889    }
3890
3891    // Instantiate the initializer.
3892    ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3893                                           /*CXXDirectInit=*/true);
3894    if (TempInit.isInvalid()) {
3895      AnyErrors = true;
3896      continue;
3897    }
3898
3899    MemInitResult NewInit;
3900    if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3901      TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3902                                        TemplateArgs,
3903                                        Init->getSourceLocation(),
3904                                        New->getDeclName());
3905      if (!TInfo) {
3906        AnyErrors = true;
3907        New->setInvalidDecl();
3908        continue;
3909      }
3910
3911      if (Init->isBaseInitializer())
3912        NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
3913                                       New->getParent(), EllipsisLoc);
3914      else
3915        NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
3916                                  cast<CXXRecordDecl>(CurContext->getParent()));
3917    } else if (Init->isMemberInitializer()) {
3918      FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
3919                                                     Init->getMemberLocation(),
3920                                                     Init->getMember(),
3921                                                     TemplateArgs));
3922      if (!Member) {
3923        AnyErrors = true;
3924        New->setInvalidDecl();
3925        continue;
3926      }
3927
3928      NewInit = BuildMemberInitializer(Member, TempInit.take(),
3929                                       Init->getSourceLocation());
3930    } else if (Init->isIndirectMemberInitializer()) {
3931      IndirectFieldDecl *IndirectMember =
3932         cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
3933                                 Init->getMemberLocation(),
3934                                 Init->getIndirectMember(), TemplateArgs));
3935
3936      if (!IndirectMember) {
3937        AnyErrors = true;
3938        New->setInvalidDecl();
3939        continue;
3940      }
3941
3942      NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
3943                                       Init->getSourceLocation());
3944    }
3945
3946    if (NewInit.isInvalid()) {
3947      AnyErrors = true;
3948      New->setInvalidDecl();
3949    } else {
3950      NewInits.push_back(NewInit.get());
3951    }
3952  }
3953
3954  // Assign all the initializers to the new constructor.
3955  ActOnMemInitializers(New,
3956                       /*FIXME: ColonLoc */
3957                       SourceLocation(),
3958                       NewInits,
3959                       AnyErrors);
3960}
3961
3962// TODO: this could be templated if the various decl types used the
3963// same method name.
3964static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3965                              ClassTemplateDecl *Instance) {
3966  Pattern = Pattern->getCanonicalDecl();
3967
3968  do {
3969    Instance = Instance->getCanonicalDecl();
3970    if (Pattern == Instance) return true;
3971    Instance = Instance->getInstantiatedFromMemberTemplate();
3972  } while (Instance);
3973
3974  return false;
3975}
3976
3977static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3978                              FunctionTemplateDecl *Instance) {
3979  Pattern = Pattern->getCanonicalDecl();
3980
3981  do {
3982    Instance = Instance->getCanonicalDecl();
3983    if (Pattern == Instance) return true;
3984    Instance = Instance->getInstantiatedFromMemberTemplate();
3985  } while (Instance);
3986
3987  return false;
3988}
3989
3990static bool
3991isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3992                  ClassTemplatePartialSpecializationDecl *Instance) {
3993  Pattern
3994    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3995  do {
3996    Instance = cast<ClassTemplatePartialSpecializationDecl>(
3997                                                Instance->getCanonicalDecl());
3998    if (Pattern == Instance)
3999      return true;
4000    Instance = Instance->getInstantiatedFromMember();
4001  } while (Instance);
4002
4003  return false;
4004}
4005
4006static bool isInstantiationOf(CXXRecordDecl *Pattern,
4007                              CXXRecordDecl *Instance) {
4008  Pattern = Pattern->getCanonicalDecl();
4009
4010  do {
4011    Instance = Instance->getCanonicalDecl();
4012    if (Pattern == Instance) return true;
4013    Instance = Instance->getInstantiatedFromMemberClass();
4014  } while (Instance);
4015
4016  return false;
4017}
4018
4019static bool isInstantiationOf(FunctionDecl *Pattern,
4020                              FunctionDecl *Instance) {
4021  Pattern = Pattern->getCanonicalDecl();
4022
4023  do {
4024    Instance = Instance->getCanonicalDecl();
4025    if (Pattern == Instance) return true;
4026    Instance = Instance->getInstantiatedFromMemberFunction();
4027  } while (Instance);
4028
4029  return false;
4030}
4031
4032static bool isInstantiationOf(EnumDecl *Pattern,
4033                              EnumDecl *Instance) {
4034  Pattern = Pattern->getCanonicalDecl();
4035
4036  do {
4037    Instance = Instance->getCanonicalDecl();
4038    if (Pattern == Instance) return true;
4039    Instance = Instance->getInstantiatedFromMemberEnum();
4040  } while (Instance);
4041
4042  return false;
4043}
4044
4045static bool isInstantiationOf(UsingShadowDecl *Pattern,
4046                              UsingShadowDecl *Instance,
4047                              ASTContext &C) {
4048  return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4049}
4050
4051static bool isInstantiationOf(UsingDecl *Pattern,
4052                              UsingDecl *Instance,
4053                              ASTContext &C) {
4054  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4055}
4056
4057static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4058                              UsingDecl *Instance,
4059                              ASTContext &C) {
4060  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4061}
4062
4063static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4064                              UsingDecl *Instance,
4065                              ASTContext &C) {
4066  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4067}
4068
4069static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4070                                              VarDecl *Instance) {
4071  assert(Instance->isStaticDataMember());
4072
4073  Pattern = Pattern->getCanonicalDecl();
4074
4075  do {
4076    Instance = Instance->getCanonicalDecl();
4077    if (Pattern == Instance) return true;
4078    Instance = Instance->getInstantiatedFromStaticDataMember();
4079  } while (Instance);
4080
4081  return false;
4082}
4083
4084// Other is the prospective instantiation
4085// D is the prospective pattern
4086static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4087  if (D->getKind() != Other->getKind()) {
4088    if (UnresolvedUsingTypenameDecl *UUD
4089          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4090      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4091        return isInstantiationOf(UUD, UD, Ctx);
4092      }
4093    }
4094
4095    if (UnresolvedUsingValueDecl *UUD
4096          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4097      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4098        return isInstantiationOf(UUD, UD, Ctx);
4099      }
4100    }
4101
4102    return false;
4103  }
4104
4105  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4106    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4107
4108  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4109    return isInstantiationOf(cast<FunctionDecl>(D), Function);
4110
4111  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4112    return isInstantiationOf(cast<EnumDecl>(D), Enum);
4113
4114  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4115    if (Var->isStaticDataMember())
4116      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4117
4118  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4119    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4120
4121  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4122    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4123
4124  if (ClassTemplatePartialSpecializationDecl *PartialSpec
4125        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4126    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4127                             PartialSpec);
4128
4129  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4130    if (!Field->getDeclName()) {
4131      // This is an unnamed field.
4132      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
4133        cast<FieldDecl>(D);
4134    }
4135  }
4136
4137  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4138    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4139
4140  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4141    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4142
4143  return D->getDeclName() && isa<NamedDecl>(Other) &&
4144    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4145}
4146
4147template<typename ForwardIterator>
4148static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4149                                      NamedDecl *D,
4150                                      ForwardIterator first,
4151                                      ForwardIterator last) {
4152  for (; first != last; ++first)
4153    if (isInstantiationOf(Ctx, D, *first))
4154      return cast<NamedDecl>(*first);
4155
4156  return 0;
4157}
4158
4159/// \brief Finds the instantiation of the given declaration context
4160/// within the current instantiation.
4161///
4162/// \returns NULL if there was an error
4163DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4164                          const MultiLevelTemplateArgumentList &TemplateArgs) {
4165  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4166    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4167    return cast_or_null<DeclContext>(ID);
4168  } else return DC;
4169}
4170
4171/// \brief Find the instantiation of the given declaration within the
4172/// current instantiation.
4173///
4174/// This routine is intended to be used when \p D is a declaration
4175/// referenced from within a template, that needs to mapped into the
4176/// corresponding declaration within an instantiation. For example,
4177/// given:
4178///
4179/// \code
4180/// template<typename T>
4181/// struct X {
4182///   enum Kind {
4183///     KnownValue = sizeof(T)
4184///   };
4185///
4186///   bool getKind() const { return KnownValue; }
4187/// };
4188///
4189/// template struct X<int>;
4190/// \endcode
4191///
4192/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4193/// \p EnumConstantDecl for \p KnownValue (which refers to
4194/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4195/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4196/// this mapping from within the instantiation of <tt>X<int></tt>.
4197NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4198                          const MultiLevelTemplateArgumentList &TemplateArgs) {
4199  DeclContext *ParentDC = D->getDeclContext();
4200  // FIXME: Parmeters of pointer to functions (y below) that are themselves
4201  // parameters (p below) can have their ParentDC set to the translation-unit
4202  // - thus we can not consistently check if the ParentDC of such a parameter
4203  // is Dependent or/and a FunctionOrMethod.
4204  // For e.g. this code, during Template argument deduction tries to
4205  // find an instantiated decl for (T y) when the ParentDC for y is
4206  // the translation unit.
4207  //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4208  //   float baz(float(*)()) { return 0.0; }
4209  //   Foo(baz);
4210  // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4211  // it gets here, always has a FunctionOrMethod as its ParentDC??
4212  // For now:
4213  //  - as long as we have a ParmVarDecl whose parent is non-dependent and
4214  //    whose type is not instantiation dependent, do nothing to the decl
4215  //  - otherwise find its instantiated decl.
4216  if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4217      !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4218    return D;
4219  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4220      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4221      (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4222      (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4223    // D is a local of some kind. Look into the map of local
4224    // declarations to their instantiations.
4225    typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4226    llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4227      = CurrentInstantiationScope->findInstantiationOf(D);
4228
4229    if (Found) {
4230      if (Decl *FD = Found->dyn_cast<Decl *>())
4231        return cast<NamedDecl>(FD);
4232
4233      int PackIdx = ArgumentPackSubstitutionIndex;
4234      assert(PackIdx != -1 && "found declaration pack but not pack expanding");
4235      return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4236    }
4237
4238    // If we're performing a partial substitution during template argument
4239    // deduction, we may not have values for template parameters yet. They
4240    // just map to themselves.
4241    if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4242        isa<TemplateTemplateParmDecl>(D))
4243      return D;
4244
4245    if (D->isInvalidDecl())
4246      return 0;
4247
4248    // If we didn't find the decl, then we must have a label decl that hasn't
4249    // been found yet.  Lazily instantiate it and return it now.
4250    assert(isa<LabelDecl>(D));
4251
4252    Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4253    assert(Inst && "Failed to instantiate label??");
4254
4255    CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4256    return cast<LabelDecl>(Inst);
4257  }
4258
4259  // For variable template specializations, update those that are still
4260  // type-dependent.
4261  if (VarTemplateSpecializationDecl *VarSpec =
4262          dyn_cast<VarTemplateSpecializationDecl>(D)) {
4263    bool InstantiationDependent = false;
4264    const TemplateArgumentListInfo &VarTemplateArgs =
4265        VarSpec->getTemplateArgsInfo();
4266    if (TemplateSpecializationType::anyDependentTemplateArguments(
4267            VarTemplateArgs, InstantiationDependent))
4268      D = cast<NamedDecl>(
4269          SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4270    return D;
4271  }
4272
4273  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4274    if (!Record->isDependentContext())
4275      return D;
4276
4277    // Determine whether this record is the "templated" declaration describing
4278    // a class template or class template partial specialization.
4279    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4280    if (ClassTemplate)
4281      ClassTemplate = ClassTemplate->getCanonicalDecl();
4282    else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4283               = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4284      ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4285
4286    // Walk the current context to find either the record or an instantiation of
4287    // it.
4288    DeclContext *DC = CurContext;
4289    while (!DC->isFileContext()) {
4290      // If we're performing substitution while we're inside the template
4291      // definition, we'll find our own context. We're done.
4292      if (DC->Equals(Record))
4293        return Record;
4294
4295      if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4296        // Check whether we're in the process of instantiating a class template
4297        // specialization of the template we're mapping.
4298        if (ClassTemplateSpecializationDecl *InstSpec
4299                      = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4300          ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4301          if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4302            return InstRecord;
4303        }
4304
4305        // Check whether we're in the process of instantiating a member class.
4306        if (isInstantiationOf(Record, InstRecord))
4307          return InstRecord;
4308      }
4309
4310      // Move to the outer template scope.
4311      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4312        if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4313          DC = FD->getLexicalDeclContext();
4314          continue;
4315        }
4316      }
4317
4318      DC = DC->getParent();
4319    }
4320
4321    // Fall through to deal with other dependent record types (e.g.,
4322    // anonymous unions in class templates).
4323  }
4324
4325  if (!ParentDC->isDependentContext())
4326    return D;
4327
4328  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4329  if (!ParentDC)
4330    return 0;
4331
4332  if (ParentDC != D->getDeclContext()) {
4333    // We performed some kind of instantiation in the parent context,
4334    // so now we need to look into the instantiated parent context to
4335    // find the instantiation of the declaration D.
4336
4337    // If our context used to be dependent, we may need to instantiate
4338    // it before performing lookup into that context.
4339    bool IsBeingInstantiated = false;
4340    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4341      if (!Spec->isDependentContext()) {
4342        QualType T = Context.getTypeDeclType(Spec);
4343        const RecordType *Tag = T->getAs<RecordType>();
4344        assert(Tag && "type of non-dependent record is not a RecordType");
4345        if (Tag->isBeingDefined())
4346          IsBeingInstantiated = true;
4347        if (!Tag->isBeingDefined() &&
4348            RequireCompleteType(Loc, T, diag::err_incomplete_type))
4349          return 0;
4350
4351        ParentDC = Tag->getDecl();
4352      }
4353    }
4354
4355    NamedDecl *Result = 0;
4356    if (D->getDeclName()) {
4357      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4358      Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4359    } else {
4360      // Since we don't have a name for the entity we're looking for,
4361      // our only option is to walk through all of the declarations to
4362      // find that name. This will occur in a few cases:
4363      //
4364      //   - anonymous struct/union within a template
4365      //   - unnamed class/struct/union/enum within a template
4366      //
4367      // FIXME: Find a better way to find these instantiations!
4368      Result = findInstantiationOf(Context, D,
4369                                   ParentDC->decls_begin(),
4370                                   ParentDC->decls_end());
4371    }
4372
4373    if (!Result) {
4374      if (isa<UsingShadowDecl>(D)) {
4375        // UsingShadowDecls can instantiate to nothing because of using hiding.
4376      } else if (Diags.hasErrorOccurred()) {
4377        // We've already complained about something, so most likely this
4378        // declaration failed to instantiate. There's no point in complaining
4379        // further, since this is normal in invalid code.
4380      } else if (IsBeingInstantiated) {
4381        // The class in which this member exists is currently being
4382        // instantiated, and we haven't gotten around to instantiating this
4383        // member yet. This can happen when the code uses forward declarations
4384        // of member classes, and introduces ordering dependencies via
4385        // template instantiation.
4386        Diag(Loc, diag::err_member_not_yet_instantiated)
4387          << D->getDeclName()
4388          << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4389        Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4390      } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4391        // This enumeration constant was found when the template was defined,
4392        // but can't be found in the instantiation. This can happen if an
4393        // unscoped enumeration member is explicitly specialized.
4394        EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4395        EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4396                                                             TemplateArgs));
4397        assert(Spec->getTemplateSpecializationKind() ==
4398                 TSK_ExplicitSpecialization);
4399        Diag(Loc, diag::err_enumerator_does_not_exist)
4400          << D->getDeclName()
4401          << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4402        Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4403          << Context.getTypeDeclType(Spec);
4404      } else {
4405        // We should have found something, but didn't.
4406        llvm_unreachable("Unable to find instantiation of declaration!");
4407      }
4408    }
4409
4410    D = Result;
4411  }
4412
4413  return D;
4414}
4415
4416/// \brief Performs template instantiation for all implicit template
4417/// instantiations we have seen until this point.
4418void Sema::PerformPendingInstantiations(bool LocalOnly) {
4419  // Load pending instantiations from the external source.
4420  if (!LocalOnly && ExternalSource) {
4421    SmallVector<PendingImplicitInstantiation, 4> Pending;
4422    ExternalSource->ReadPendingInstantiations(Pending);
4423    PendingInstantiations.insert(PendingInstantiations.begin(),
4424                                 Pending.begin(), Pending.end());
4425  }
4426
4427  while (!PendingLocalImplicitInstantiations.empty() ||
4428         (!LocalOnly && !PendingInstantiations.empty())) {
4429    PendingImplicitInstantiation Inst;
4430
4431    if (PendingLocalImplicitInstantiations.empty()) {
4432      Inst = PendingInstantiations.front();
4433      PendingInstantiations.pop_front();
4434    } else {
4435      Inst = PendingLocalImplicitInstantiations.front();
4436      PendingLocalImplicitInstantiations.pop_front();
4437    }
4438
4439    // Instantiate function definitions
4440    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4441      PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4442                                          "instantiating function definition");
4443      bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4444                                TSK_ExplicitInstantiationDefinition;
4445      InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4446                                    DefinitionRequired);
4447      continue;
4448    }
4449
4450    // Instantiate variable definitions
4451    VarDecl *Var = cast<VarDecl>(Inst.first);
4452
4453    assert((Var->isStaticDataMember() ||
4454            isa<VarTemplateSpecializationDecl>(Var)) &&
4455           "Not a static data member, nor a variable template"
4456           " specialization?");
4457
4458    // Don't try to instantiate declarations if the most recent redeclaration
4459    // is invalid.
4460    if (Var->getMostRecentDecl()->isInvalidDecl())
4461      continue;
4462
4463    // Check if the most recent declaration has changed the specialization kind
4464    // and removed the need for implicit instantiation.
4465    switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4466    case TSK_Undeclared:
4467      llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4468    case TSK_ExplicitInstantiationDeclaration:
4469    case TSK_ExplicitSpecialization:
4470      continue;  // No longer need to instantiate this type.
4471    case TSK_ExplicitInstantiationDefinition:
4472      // We only need an instantiation if the pending instantiation *is* the
4473      // explicit instantiation.
4474      if (Var != Var->getMostRecentDecl()) continue;
4475    case TSK_ImplicitInstantiation:
4476      break;
4477    }
4478
4479    PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4480                                        "instantiating variable definition");
4481    bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4482                              TSK_ExplicitInstantiationDefinition;
4483
4484    // Instantiate static data member definitions or variable template
4485    // specializations.
4486    InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4487                                  DefinitionRequired);
4488  }
4489}
4490
4491void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4492                       const MultiLevelTemplateArgumentList &TemplateArgs) {
4493  for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
4494         E = Pattern->ddiag_end(); I != E; ++I) {
4495    DependentDiagnostic *DD = *I;
4496
4497    switch (DD->getKind()) {
4498    case DependentDiagnostic::Access:
4499      HandleDependentAccessCheck(*DD, TemplateArgs);
4500      break;
4501    }
4502  }
4503}
4504