SemaTemplateInstantiateDecl.cpp revision ab91ef1dbe524bba3c0147b11dfdd394153c783d
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/Sema/Lookup.h"
14#include "clang/Sema/PrettyDeclStackTrace.h"
15#include "clang/Sema/Template.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DeclVisitor.h"
20#include "clang/AST/DependentDiagnostic.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/TypeLoc.h"
24#include "clang/Lex/Preprocessor.h"
25
26using namespace clang;
27
28bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29                                              DeclaratorDecl *NewDecl) {
30  if (!OldDecl->getQualifierLoc())
31    return false;
32
33  NestedNameSpecifierLoc NewQualifierLoc
34    = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
35                                          TemplateArgs);
36
37  if (!NewQualifierLoc)
38    return true;
39
40  NewDecl->setQualifierInfo(NewQualifierLoc);
41  return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45                                              TagDecl *NewDecl) {
46  if (!OldDecl->getQualifierLoc())
47    return false;
48
49  NestedNameSpecifierLoc NewQualifierLoc
50  = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
51                                        TemplateArgs);
52
53  if (!NewQualifierLoc)
54    return true;
55
56  NewDecl->setQualifierInfo(NewQualifierLoc);
57  return false;
58}
59
60// Include attribute instantiation code.
61#include "clang/Sema/AttrTemplateInstantiate.inc"
62
63void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
64                            const Decl *Tmpl, Decl *New,
65                            LateInstantiatedAttrVec *LateAttrs,
66                            LocalInstantiationScope *OuterMostScope) {
67  for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
68       i != e; ++i) {
69    const Attr *TmplAttr = *i;
70
71    // FIXME: This should be generalized to more than just the AlignedAttr.
72    if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
73      if (Aligned->isAlignmentDependent()) {
74        if (Aligned->isAlignmentExpr()) {
75          // The alignment expression is a constant expression.
76          EnterExpressionEvaluationContext Unevaluated(*this,
77                                                       Sema::ConstantEvaluated);
78
79          ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
80                                        TemplateArgs);
81          if (!Result.isInvalid())
82            AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83                           Aligned->getIsMSDeclSpec());
84        } else {
85          TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
86                                             TemplateArgs,
87                                             Aligned->getLocation(),
88                                             DeclarationName());
89          if (Result)
90            AddAlignedAttr(Aligned->getLocation(), New, Result,
91                           Aligned->getIsMSDeclSpec());
92        }
93        continue;
94      }
95    }
96
97    if (TmplAttr->isLateParsed() && LateAttrs) {
98      // Late parsed attributes must be instantiated and attached after the
99      // enclosing class has been instantiated.  See Sema::InstantiateClass.
100      LocalInstantiationScope *Saved = 0;
101      if (CurrentInstantiationScope)
102        Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
103      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
104    } else {
105      Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
106                                                         *this, TemplateArgs);
107      if (NewAttr)
108        New->addAttr(NewAttr);
109    }
110  }
111}
112
113Decl *
114TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
115  llvm_unreachable("Translation units cannot be instantiated");
116}
117
118Decl *
119TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
120  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
121                                      D->getIdentifier());
122  Owner->addDecl(Inst);
123  return Inst;
124}
125
126Decl *
127TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
128  llvm_unreachable("Namespaces cannot be instantiated");
129}
130
131Decl *
132TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
133  NamespaceAliasDecl *Inst
134    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
135                                 D->getNamespaceLoc(),
136                                 D->getAliasLoc(),
137                                 D->getIdentifier(),
138                                 D->getQualifierLoc(),
139                                 D->getTargetNameLoc(),
140                                 D->getNamespace());
141  Owner->addDecl(Inst);
142  return Inst;
143}
144
145Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
146                                                           bool IsTypeAlias) {
147  bool Invalid = false;
148  TypeSourceInfo *DI = D->getTypeSourceInfo();
149  if (DI->getType()->isInstantiationDependentType() ||
150      DI->getType()->isVariablyModifiedType()) {
151    DI = SemaRef.SubstType(DI, TemplateArgs,
152                           D->getLocation(), D->getDeclName());
153    if (!DI) {
154      Invalid = true;
155      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
156    }
157  } else {
158    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
159  }
160
161  // Create the new typedef
162  TypedefNameDecl *Typedef;
163  if (IsTypeAlias)
164    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
165                                    D->getLocation(), D->getIdentifier(), DI);
166  else
167    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
168                                  D->getLocation(), D->getIdentifier(), DI);
169  if (Invalid)
170    Typedef->setInvalidDecl();
171
172  // If the old typedef was the name for linkage purposes of an anonymous
173  // tag decl, re-establish that relationship for the new typedef.
174  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
175    TagDecl *oldTag = oldTagType->getDecl();
176    if (oldTag->getTypedefNameForAnonDecl() == D) {
177      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
178      assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
179      newTag->setTypedefNameForAnonDecl(Typedef);
180    }
181  }
182
183  if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
184    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
185                                                       TemplateArgs);
186    if (!InstPrev)
187      return 0;
188
189    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
190
191    // If the typedef types are not identical, reject them.
192    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
193
194    Typedef->setPreviousDeclaration(InstPrevTypedef);
195  }
196
197  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
198
199  Typedef->setAccess(D->getAccess());
200
201  return Typedef;
202}
203
204Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
205  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
206  Owner->addDecl(Typedef);
207  return Typedef;
208}
209
210Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
211  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
212  Owner->addDecl(Typedef);
213  return Typedef;
214}
215
216Decl *
217TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
218  // Create a local instantiation scope for this type alias template, which
219  // will contain the instantiations of the template parameters.
220  LocalInstantiationScope Scope(SemaRef);
221
222  TemplateParameterList *TempParams = D->getTemplateParameters();
223  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
224  if (!InstParams)
225    return 0;
226
227  TypeAliasDecl *Pattern = D->getTemplatedDecl();
228
229  TypeAliasTemplateDecl *PrevAliasTemplate = 0;
230  if (Pattern->getPreviousDecl()) {
231    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
232    if (Found.first != Found.second) {
233      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
234    }
235  }
236
237  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
238    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
239  if (!AliasInst)
240    return 0;
241
242  TypeAliasTemplateDecl *Inst
243    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
244                                    D->getDeclName(), InstParams, AliasInst);
245  if (PrevAliasTemplate)
246    Inst->setPreviousDeclaration(PrevAliasTemplate);
247
248  Inst->setAccess(D->getAccess());
249
250  if (!PrevAliasTemplate)
251    Inst->setInstantiatedFromMemberTemplate(D);
252
253  Owner->addDecl(Inst);
254
255  return Inst;
256}
257
258Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
259  // If this is the variable for an anonymous struct or union,
260  // instantiate the anonymous struct/union type first.
261  if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
262    if (RecordTy->getDecl()->isAnonymousStructOrUnion())
263      if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
264        return 0;
265
266  // Do substitution on the type of the declaration
267  TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
268                                         TemplateArgs,
269                                         D->getTypeSpecStartLoc(),
270                                         D->getDeclName());
271  if (!DI)
272    return 0;
273
274  if (DI->getType()->isFunctionType()) {
275    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
276      << D->isStaticDataMember() << DI->getType();
277    return 0;
278  }
279
280  // Build the instantiated declaration
281  VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
282                                 D->getInnerLocStart(),
283                                 D->getLocation(), D->getIdentifier(),
284                                 DI->getType(), DI,
285                                 D->getStorageClass(),
286                                 D->getStorageClassAsWritten());
287  Var->setThreadSpecified(D->isThreadSpecified());
288  Var->setInitStyle(D->getInitStyle());
289  Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
290  Var->setConstexpr(D->isConstexpr());
291
292  // Substitute the nested name specifier, if any.
293  if (SubstQualifier(D, Var))
294    return 0;
295
296  // If we are instantiating a static data member defined
297  // out-of-line, the instantiation will have the same lexical
298  // context (which will be a namespace scope) as the template.
299  if (D->isOutOfLine())
300    Var->setLexicalDeclContext(D->getLexicalDeclContext());
301
302  Var->setAccess(D->getAccess());
303
304  if (!D->isStaticDataMember()) {
305    Var->setUsed(D->isUsed(false));
306    Var->setReferenced(D->isReferenced());
307  }
308
309  // FIXME: In theory, we could have a previous declaration for variables that
310  // are not static data members.
311  // FIXME: having to fake up a LookupResult is dumb.
312  LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
313                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
314  if (D->isStaticDataMember())
315    SemaRef.LookupQualifiedName(Previous, Owner, false);
316
317  // In ARC, infer 'retaining' for variables of retainable type.
318  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
319      SemaRef.inferObjCARCLifetime(Var))
320    Var->setInvalidDecl();
321
322  SemaRef.CheckVariableDeclaration(Var, Previous);
323
324  if (D->isOutOfLine()) {
325    D->getLexicalDeclContext()->addDecl(Var);
326    Owner->makeDeclVisibleInContext(Var);
327  } else {
328    Owner->addDecl(Var);
329    if (Owner->isFunctionOrMethod())
330      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
331  }
332  SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
333
334  // Link instantiations of static data members back to the template from
335  // which they were instantiated.
336  if (Var->isStaticDataMember())
337    SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
338                                                     TSK_ImplicitInstantiation);
339
340  if (Var->getAnyInitializer()) {
341    // We already have an initializer in the class.
342  } else if (D->getInit()) {
343    if (Var->isStaticDataMember() && !D->isOutOfLine())
344      SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated);
345    else
346      SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
347
348    // Instantiate the initializer.
349    ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
350                                        D->getInitStyle() == VarDecl::CallInit);
351    if (!Init.isInvalid()) {
352      bool TypeMayContainAuto = true;
353      if (Init.get()) {
354        bool DirectInit = D->isDirectInit();
355        SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
356                                     TypeMayContainAuto);
357      } else
358        SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
359    } else {
360      // FIXME: Not too happy about invalidating the declaration
361      // because of a bogus initializer.
362      Var->setInvalidDecl();
363    }
364
365    SemaRef.PopExpressionEvaluationContext();
366  } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
367             !Var->isCXXForRangeDecl())
368    SemaRef.ActOnUninitializedDecl(Var, false);
369
370  // Diagnose unused local variables with dependent types, where the diagnostic
371  // will have been deferred.
372  if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
373      D->getType()->isDependentType())
374    SemaRef.DiagnoseUnusedDecl(Var);
375
376  return Var;
377}
378
379Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
380  AccessSpecDecl* AD
381    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
382                             D->getAccessSpecifierLoc(), D->getColonLoc());
383  Owner->addHiddenDecl(AD);
384  return AD;
385}
386
387Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
388  bool Invalid = false;
389  TypeSourceInfo *DI = D->getTypeSourceInfo();
390  if (DI->getType()->isInstantiationDependentType() ||
391      DI->getType()->isVariablyModifiedType())  {
392    DI = SemaRef.SubstType(DI, TemplateArgs,
393                           D->getLocation(), D->getDeclName());
394    if (!DI) {
395      DI = D->getTypeSourceInfo();
396      Invalid = true;
397    } else if (DI->getType()->isFunctionType()) {
398      // C++ [temp.arg.type]p3:
399      //   If a declaration acquires a function type through a type
400      //   dependent on a template-parameter and this causes a
401      //   declaration that does not use the syntactic form of a
402      //   function declarator to have function type, the program is
403      //   ill-formed.
404      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
405        << DI->getType();
406      Invalid = true;
407    }
408  } else {
409    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
410  }
411
412  Expr *BitWidth = D->getBitWidth();
413  if (Invalid)
414    BitWidth = 0;
415  else if (BitWidth) {
416    // The bit-width expression is a constant expression.
417    EnterExpressionEvaluationContext Unevaluated(SemaRef,
418                                                 Sema::ConstantEvaluated);
419
420    ExprResult InstantiatedBitWidth
421      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
422    if (InstantiatedBitWidth.isInvalid()) {
423      Invalid = true;
424      BitWidth = 0;
425    } else
426      BitWidth = InstantiatedBitWidth.takeAs<Expr>();
427  }
428
429  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
430                                            DI->getType(), DI,
431                                            cast<RecordDecl>(Owner),
432                                            D->getLocation(),
433                                            D->isMutable(),
434                                            BitWidth,
435                                            D->getInClassInitStyle(),
436                                            D->getInnerLocStart(),
437                                            D->getAccess(),
438                                            0);
439  if (!Field) {
440    cast<Decl>(Owner)->setInvalidDecl();
441    return 0;
442  }
443
444  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
445
446  if (Invalid)
447    Field->setInvalidDecl();
448
449  if (!Field->getDeclName()) {
450    // Keep track of where this decl came from.
451    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
452  }
453  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
454    if (Parent->isAnonymousStructOrUnion() &&
455        Parent->getRedeclContext()->isFunctionOrMethod())
456      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
457  }
458
459  Field->setImplicit(D->isImplicit());
460  Field->setAccess(D->getAccess());
461  Owner->addDecl(Field);
462
463  return Field;
464}
465
466Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
467  NamedDecl **NamedChain =
468    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
469
470  int i = 0;
471  for (IndirectFieldDecl::chain_iterator PI =
472       D->chain_begin(), PE = D->chain_end();
473       PI != PE; ++PI) {
474    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
475                                              TemplateArgs);
476    if (!Next)
477      return 0;
478
479    NamedChain[i++] = Next;
480  }
481
482  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
483  IndirectFieldDecl* IndirectField
484    = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
485                                D->getIdentifier(), T,
486                                NamedChain, D->getChainingSize());
487
488
489  IndirectField->setImplicit(D->isImplicit());
490  IndirectField->setAccess(D->getAccess());
491  Owner->addDecl(IndirectField);
492  return IndirectField;
493}
494
495Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
496  // Handle friend type expressions by simply substituting template
497  // parameters into the pattern type and checking the result.
498  if (TypeSourceInfo *Ty = D->getFriendType()) {
499    TypeSourceInfo *InstTy;
500    // If this is an unsupported friend, don't bother substituting template
501    // arguments into it. The actual type referred to won't be used by any
502    // parts of Clang, and may not be valid for instantiating. Just use the
503    // same info for the instantiated friend.
504    if (D->isUnsupportedFriend()) {
505      InstTy = Ty;
506    } else {
507      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
508                                 D->getLocation(), DeclarationName());
509    }
510    if (!InstTy)
511      return 0;
512
513    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
514                                                 D->getFriendLoc(), InstTy);
515    if (!FD)
516      return 0;
517
518    FD->setAccess(AS_public);
519    FD->setUnsupportedFriend(D->isUnsupportedFriend());
520    Owner->addDecl(FD);
521    return FD;
522  }
523
524  NamedDecl *ND = D->getFriendDecl();
525  assert(ND && "friend decl must be a decl or a type!");
526
527  // All of the Visit implementations for the various potential friend
528  // declarations have to be carefully written to work for friend
529  // objects, with the most important detail being that the target
530  // decl should almost certainly not be placed in Owner.
531  Decl *NewND = Visit(ND);
532  if (!NewND) return 0;
533
534  FriendDecl *FD =
535    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
536                       cast<NamedDecl>(NewND), D->getFriendLoc());
537  FD->setAccess(AS_public);
538  FD->setUnsupportedFriend(D->isUnsupportedFriend());
539  Owner->addDecl(FD);
540  return FD;
541}
542
543Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
544  Expr *AssertExpr = D->getAssertExpr();
545
546  // The expression in a static assertion is a constant expression.
547  EnterExpressionEvaluationContext Unevaluated(SemaRef,
548                                               Sema::ConstantEvaluated);
549
550  ExprResult InstantiatedAssertExpr
551    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
552  if (InstantiatedAssertExpr.isInvalid())
553    return 0;
554
555  ExprResult Message(D->getMessage());
556  D->getMessage();
557  return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
558                                              InstantiatedAssertExpr.get(),
559                                              Message.get(),
560                                              D->getRParenLoc());
561}
562
563Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
564  EnumDecl *PrevDecl = 0;
565  if (D->getPreviousDecl()) {
566    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
567                                                   D->getPreviousDecl(),
568                                                   TemplateArgs);
569    if (!Prev) return 0;
570    PrevDecl = cast<EnumDecl>(Prev);
571  }
572
573  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
574                                    D->getLocation(), D->getIdentifier(),
575                                    PrevDecl, D->isScoped(),
576                                    D->isScopedUsingClassTag(), D->isFixed());
577  if (D->isFixed()) {
578    if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
579      // If we have type source information for the underlying type, it means it
580      // has been explicitly set by the user. Perform substitution on it before
581      // moving on.
582      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
583      TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
584                                                DeclarationName());
585      if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
586        Enum->setIntegerType(SemaRef.Context.IntTy);
587      else
588        Enum->setIntegerTypeSourceInfo(NewTI);
589    } else {
590      assert(!D->getIntegerType()->isDependentType()
591             && "Dependent type without type source info");
592      Enum->setIntegerType(D->getIntegerType());
593    }
594  }
595
596  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
597
598  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
599  Enum->setAccess(D->getAccess());
600  if (SubstQualifier(D, Enum)) return 0;
601  Owner->addDecl(Enum);
602
603  EnumDecl *Def = D->getDefinition();
604  if (Def && Def != D) {
605    // If this is an out-of-line definition of an enum member template, check
606    // that the underlying types match in the instantiation of both
607    // declarations.
608    if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
609      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
610      QualType DefnUnderlying =
611        SemaRef.SubstType(TI->getType(), TemplateArgs,
612                          UnderlyingLoc, DeclarationName());
613      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
614                                     DefnUnderlying, Enum);
615    }
616  }
617
618  if (D->getDeclContext()->isFunctionOrMethod())
619    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
620
621  // C++11 [temp.inst]p1: The implicit instantiation of a class template
622  // specialization causes the implicit instantiation of the declarations, but
623  // not the definitions of scoped member enumerations.
624  // FIXME: There appears to be no wording for what happens for an enum defined
625  // within a block scope, but we treat that much like a member template. Only
626  // instantiate the definition when visiting the definition in that case, since
627  // we will visit all redeclarations.
628  if (!Enum->isScoped() && Def &&
629      (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
630    InstantiateEnumDefinition(Enum, Def);
631
632  return Enum;
633}
634
635void TemplateDeclInstantiator::InstantiateEnumDefinition(
636    EnumDecl *Enum, EnumDecl *Pattern) {
637  Enum->startDefinition();
638
639  // Update the location to refer to the definition.
640  Enum->setLocation(Pattern->getLocation());
641
642  SmallVector<Decl*, 4> Enumerators;
643
644  EnumConstantDecl *LastEnumConst = 0;
645  for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
646         ECEnd = Pattern->enumerator_end();
647       EC != ECEnd; ++EC) {
648    // The specified value for the enumerator.
649    ExprResult Value = SemaRef.Owned((Expr *)0);
650    if (Expr *UninstValue = EC->getInitExpr()) {
651      // The enumerator's value expression is a constant expression.
652      EnterExpressionEvaluationContext Unevaluated(SemaRef,
653                                                   Sema::ConstantEvaluated);
654
655      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
656    }
657
658    // Drop the initial value and continue.
659    bool isInvalid = false;
660    if (Value.isInvalid()) {
661      Value = SemaRef.Owned((Expr *)0);
662      isInvalid = true;
663    }
664
665    EnumConstantDecl *EnumConst
666      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
667                                  EC->getLocation(), EC->getIdentifier(),
668                                  Value.get());
669
670    if (isInvalid) {
671      if (EnumConst)
672        EnumConst->setInvalidDecl();
673      Enum->setInvalidDecl();
674    }
675
676    if (EnumConst) {
677      SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
678
679      EnumConst->setAccess(Enum->getAccess());
680      Enum->addDecl(EnumConst);
681      Enumerators.push_back(EnumConst);
682      LastEnumConst = EnumConst;
683
684      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
685          !Enum->isScoped()) {
686        // If the enumeration is within a function or method, record the enum
687        // constant as a local.
688        SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
689      }
690    }
691  }
692
693  // FIXME: Fixup LBraceLoc
694  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
695                        Enum->getRBraceLoc(), Enum,
696                        Enumerators.data(), Enumerators.size(),
697                        0, 0);
698}
699
700Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
701  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
702}
703
704Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
705  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
706
707  // Create a local instantiation scope for this class template, which
708  // will contain the instantiations of the template parameters.
709  LocalInstantiationScope Scope(SemaRef);
710  TemplateParameterList *TempParams = D->getTemplateParameters();
711  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
712  if (!InstParams)
713    return NULL;
714
715  CXXRecordDecl *Pattern = D->getTemplatedDecl();
716
717  // Instantiate the qualifier.  We have to do this first in case
718  // we're a friend declaration, because if we are then we need to put
719  // the new declaration in the appropriate context.
720  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
721  if (QualifierLoc) {
722    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
723                                                       TemplateArgs);
724    if (!QualifierLoc)
725      return 0;
726  }
727
728  CXXRecordDecl *PrevDecl = 0;
729  ClassTemplateDecl *PrevClassTemplate = 0;
730
731  if (!isFriend && Pattern->getPreviousDecl()) {
732    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
733    if (Found.first != Found.second) {
734      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
735      if (PrevClassTemplate)
736        PrevDecl = PrevClassTemplate->getTemplatedDecl();
737    }
738  }
739
740  // If this isn't a friend, then it's a member template, in which
741  // case we just want to build the instantiation in the
742  // specialization.  If it is a friend, we want to build it in
743  // the appropriate context.
744  DeclContext *DC = Owner;
745  if (isFriend) {
746    if (QualifierLoc) {
747      CXXScopeSpec SS;
748      SS.Adopt(QualifierLoc);
749      DC = SemaRef.computeDeclContext(SS);
750      if (!DC) return 0;
751    } else {
752      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
753                                           Pattern->getDeclContext(),
754                                           TemplateArgs);
755    }
756
757    // Look for a previous declaration of the template in the owning
758    // context.
759    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
760                   Sema::LookupOrdinaryName, Sema::ForRedeclaration);
761    SemaRef.LookupQualifiedName(R, DC);
762
763    if (R.isSingleResult()) {
764      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
765      if (PrevClassTemplate)
766        PrevDecl = PrevClassTemplate->getTemplatedDecl();
767    }
768
769    if (!PrevClassTemplate && QualifierLoc) {
770      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
771        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
772        << QualifierLoc.getSourceRange();
773      return 0;
774    }
775
776    bool AdoptedPreviousTemplateParams = false;
777    if (PrevClassTemplate) {
778      bool Complain = true;
779
780      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
781      // template for struct std::tr1::__detail::_Map_base, where the
782      // template parameters of the friend declaration don't match the
783      // template parameters of the original declaration. In this one
784      // case, we don't complain about the ill-formed friend
785      // declaration.
786      if (isFriend && Pattern->getIdentifier() &&
787          Pattern->getIdentifier()->isStr("_Map_base") &&
788          DC->isNamespace() &&
789          cast<NamespaceDecl>(DC)->getIdentifier() &&
790          cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
791        DeclContext *DCParent = DC->getParent();
792        if (DCParent->isNamespace() &&
793            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
794            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
795          DeclContext *DCParent2 = DCParent->getParent();
796          if (DCParent2->isNamespace() &&
797              cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
798              cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
799              DCParent2->getParent()->isTranslationUnit())
800            Complain = false;
801        }
802      }
803
804      TemplateParameterList *PrevParams
805        = PrevClassTemplate->getTemplateParameters();
806
807      // Make sure the parameter lists match.
808      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
809                                                  Complain,
810                                                  Sema::TPL_TemplateMatch)) {
811        if (Complain)
812          return 0;
813
814        AdoptedPreviousTemplateParams = true;
815        InstParams = PrevParams;
816      }
817
818      // Do some additional validation, then merge default arguments
819      // from the existing declarations.
820      if (!AdoptedPreviousTemplateParams &&
821          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
822                                             Sema::TPC_ClassTemplate))
823        return 0;
824    }
825  }
826
827  CXXRecordDecl *RecordInst
828    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
829                            Pattern->getLocStart(), Pattern->getLocation(),
830                            Pattern->getIdentifier(), PrevDecl,
831                            /*DelayTypeCreation=*/true);
832
833  if (QualifierLoc)
834    RecordInst->setQualifierInfo(QualifierLoc);
835
836  ClassTemplateDecl *Inst
837    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
838                                D->getIdentifier(), InstParams, RecordInst,
839                                PrevClassTemplate);
840  RecordInst->setDescribedClassTemplate(Inst);
841
842  if (isFriend) {
843    if (PrevClassTemplate)
844      Inst->setAccess(PrevClassTemplate->getAccess());
845    else
846      Inst->setAccess(D->getAccess());
847
848    Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
849    // TODO: do we want to track the instantiation progeny of this
850    // friend target decl?
851  } else {
852    Inst->setAccess(D->getAccess());
853    if (!PrevClassTemplate)
854      Inst->setInstantiatedFromMemberTemplate(D);
855  }
856
857  // Trigger creation of the type for the instantiation.
858  SemaRef.Context.getInjectedClassNameType(RecordInst,
859                                    Inst->getInjectedClassNameSpecialization());
860
861  // Finish handling of friends.
862  if (isFriend) {
863    DC->makeDeclVisibleInContext(Inst);
864    Inst->setLexicalDeclContext(Owner);
865    RecordInst->setLexicalDeclContext(Owner);
866    return Inst;
867  }
868
869  if (D->isOutOfLine()) {
870    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
871    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
872  }
873
874  Owner->addDecl(Inst);
875
876  if (!PrevClassTemplate) {
877    // Queue up any out-of-line partial specializations of this member
878    // class template; the client will force their instantiation once
879    // the enclosing class has been instantiated.
880    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
881    D->getPartialSpecializations(PartialSpecs);
882    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
883      if (PartialSpecs[I]->isOutOfLine())
884        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
885  }
886
887  return Inst;
888}
889
890Decl *
891TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
892                                   ClassTemplatePartialSpecializationDecl *D) {
893  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
894
895  // Lookup the already-instantiated declaration in the instantiation
896  // of the class template and return that.
897  DeclContext::lookup_result Found
898    = Owner->lookup(ClassTemplate->getDeclName());
899  if (Found.first == Found.second)
900    return 0;
901
902  ClassTemplateDecl *InstClassTemplate
903    = dyn_cast<ClassTemplateDecl>(*Found.first);
904  if (!InstClassTemplate)
905    return 0;
906
907  if (ClassTemplatePartialSpecializationDecl *Result
908        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
909    return Result;
910
911  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
912}
913
914Decl *
915TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
916  // Create a local instantiation scope for this function template, which
917  // will contain the instantiations of the template parameters and then get
918  // merged with the local instantiation scope for the function template
919  // itself.
920  LocalInstantiationScope Scope(SemaRef);
921
922  TemplateParameterList *TempParams = D->getTemplateParameters();
923  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
924  if (!InstParams)
925    return NULL;
926
927  FunctionDecl *Instantiated = 0;
928  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
929    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
930                                                                 InstParams));
931  else
932    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
933                                                          D->getTemplatedDecl(),
934                                                                InstParams));
935
936  if (!Instantiated)
937    return 0;
938
939  Instantiated->setAccess(D->getAccess());
940
941  // Link the instantiated function template declaration to the function
942  // template from which it was instantiated.
943  FunctionTemplateDecl *InstTemplate
944    = Instantiated->getDescribedFunctionTemplate();
945  InstTemplate->setAccess(D->getAccess());
946  assert(InstTemplate &&
947         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
948
949  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
950
951  // Link the instantiation back to the pattern *unless* this is a
952  // non-definition friend declaration.
953  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
954      !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
955    InstTemplate->setInstantiatedFromMemberTemplate(D);
956
957  // Make declarations visible in the appropriate context.
958  if (!isFriend)
959    Owner->addDecl(InstTemplate);
960
961  return InstTemplate;
962}
963
964Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
965  CXXRecordDecl *PrevDecl = 0;
966  if (D->isInjectedClassName())
967    PrevDecl = cast<CXXRecordDecl>(Owner);
968  else if (D->getPreviousDecl()) {
969    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
970                                                   D->getPreviousDecl(),
971                                                   TemplateArgs);
972    if (!Prev) return 0;
973    PrevDecl = cast<CXXRecordDecl>(Prev);
974  }
975
976  CXXRecordDecl *Record
977    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
978                            D->getLocStart(), D->getLocation(),
979                            D->getIdentifier(), PrevDecl);
980
981  // Substitute the nested name specifier, if any.
982  if (SubstQualifier(D, Record))
983    return 0;
984
985  Record->setImplicit(D->isImplicit());
986  // FIXME: Check against AS_none is an ugly hack to work around the issue that
987  // the tag decls introduced by friend class declarations don't have an access
988  // specifier. Remove once this area of the code gets sorted out.
989  if (D->getAccess() != AS_none)
990    Record->setAccess(D->getAccess());
991  if (!D->isInjectedClassName())
992    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
993
994  // If the original function was part of a friend declaration,
995  // inherit its namespace state.
996  if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
997    Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
998
999  // Make sure that anonymous structs and unions are recorded.
1000  if (D->isAnonymousStructOrUnion()) {
1001    Record->setAnonymousStructOrUnion(true);
1002    if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
1003      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1004  }
1005
1006  Owner->addDecl(Record);
1007  return Record;
1008}
1009
1010/// Normal class members are of more specific types and therefore
1011/// don't make it here.  This function serves two purposes:
1012///   1) instantiating function templates
1013///   2) substituting friend declarations
1014/// FIXME: preserve function definitions in case #2
1015Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1016                                       TemplateParameterList *TemplateParams) {
1017  // Check whether there is already a function template specialization for
1018  // this declaration.
1019  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1020  if (FunctionTemplate && !TemplateParams) {
1021    std::pair<const TemplateArgument *, unsigned> Innermost
1022      = TemplateArgs.getInnermost();
1023
1024    void *InsertPos = 0;
1025    FunctionDecl *SpecFunc
1026      = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1027                                             InsertPos);
1028
1029    // If we already have a function template specialization, return it.
1030    if (SpecFunc)
1031      return SpecFunc;
1032  }
1033
1034  bool isFriend;
1035  if (FunctionTemplate)
1036    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1037  else
1038    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1039
1040  bool MergeWithParentScope = (TemplateParams != 0) ||
1041    Owner->isFunctionOrMethod() ||
1042    !(isa<Decl>(Owner) &&
1043      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1044  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1045
1046  SmallVector<ParmVarDecl *, 4> Params;
1047  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1048  if (!TInfo)
1049    return 0;
1050  QualType T = TInfo->getType();
1051
1052  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1053  if (QualifierLoc) {
1054    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1055                                                       TemplateArgs);
1056    if (!QualifierLoc)
1057      return 0;
1058  }
1059
1060  // If we're instantiating a local function declaration, put the result
1061  // in the owner;  otherwise we need to find the instantiated context.
1062  DeclContext *DC;
1063  if (D->getDeclContext()->isFunctionOrMethod())
1064    DC = Owner;
1065  else if (isFriend && QualifierLoc) {
1066    CXXScopeSpec SS;
1067    SS.Adopt(QualifierLoc);
1068    DC = SemaRef.computeDeclContext(SS);
1069    if (!DC) return 0;
1070  } else {
1071    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1072                                         TemplateArgs);
1073  }
1074
1075  FunctionDecl *Function =
1076      FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1077                           D->getLocation(), D->getDeclName(), T, TInfo,
1078                           D->getStorageClass(), D->getStorageClassAsWritten(),
1079                           D->isInlineSpecified(), D->hasWrittenPrototype(),
1080                           D->isConstexpr());
1081
1082  if (QualifierLoc)
1083    Function->setQualifierInfo(QualifierLoc);
1084
1085  DeclContext *LexicalDC = Owner;
1086  if (!isFriend && D->isOutOfLine()) {
1087    assert(D->getDeclContext()->isFileContext());
1088    LexicalDC = D->getDeclContext();
1089  }
1090
1091  Function->setLexicalDeclContext(LexicalDC);
1092
1093  // Attach the parameters
1094  if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
1095    // Adopt the already-instantiated parameters into our own context.
1096    for (unsigned P = 0; P < Params.size(); ++P)
1097      if (Params[P])
1098        Params[P]->setOwningFunction(Function);
1099  } else {
1100    // Since we were instantiated via a typedef of a function type, create
1101    // new parameters.
1102    const FunctionProtoType *Proto
1103      = Function->getType()->getAs<FunctionProtoType>();
1104    assert(Proto && "No function prototype in template instantiation?");
1105    for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1106         AE = Proto->arg_type_end(); AI != AE; ++AI) {
1107      ParmVarDecl *Param
1108        = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1109                                             *AI);
1110      Param->setScopeInfo(0, Params.size());
1111      Params.push_back(Param);
1112    }
1113  }
1114  Function->setParams(Params);
1115
1116  SourceLocation InstantiateAtPOI;
1117  if (TemplateParams) {
1118    // Our resulting instantiation is actually a function template, since we
1119    // are substituting only the outer template parameters. For example, given
1120    //
1121    //   template<typename T>
1122    //   struct X {
1123    //     template<typename U> friend void f(T, U);
1124    //   };
1125    //
1126    //   X<int> x;
1127    //
1128    // We are instantiating the friend function template "f" within X<int>,
1129    // which means substituting int for T, but leaving "f" as a friend function
1130    // template.
1131    // Build the function template itself.
1132    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1133                                                    Function->getLocation(),
1134                                                    Function->getDeclName(),
1135                                                    TemplateParams, Function);
1136    Function->setDescribedFunctionTemplate(FunctionTemplate);
1137
1138    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1139
1140    if (isFriend && D->isThisDeclarationADefinition()) {
1141      // TODO: should we remember this connection regardless of whether
1142      // the friend declaration provided a body?
1143      FunctionTemplate->setInstantiatedFromMemberTemplate(
1144                                           D->getDescribedFunctionTemplate());
1145    }
1146  } else if (FunctionTemplate) {
1147    // Record this function template specialization.
1148    std::pair<const TemplateArgument *, unsigned> Innermost
1149      = TemplateArgs.getInnermost();
1150    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1151                            TemplateArgumentList::CreateCopy(SemaRef.Context,
1152                                                             Innermost.first,
1153                                                             Innermost.second),
1154                                                /*InsertPos=*/0);
1155  } else if (isFriend) {
1156    // Note, we need this connection even if the friend doesn't have a body.
1157    // Its body may exist but not have been attached yet due to deferred
1158    // parsing.
1159    // FIXME: It might be cleaner to set this when attaching the body to the
1160    // friend function declaration, however that would require finding all the
1161    // instantiations and modifying them.
1162    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1163  }
1164
1165  if (InitFunctionInstantiation(Function, D))
1166    Function->setInvalidDecl();
1167
1168  bool isExplicitSpecialization = false;
1169
1170  LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1171                        Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1172
1173  if (DependentFunctionTemplateSpecializationInfo *Info
1174        = D->getDependentSpecializationInfo()) {
1175    assert(isFriend && "non-friend has dependent specialization info?");
1176
1177    // This needs to be set now for future sanity.
1178    Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1179
1180    // Instantiate the explicit template arguments.
1181    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1182                                          Info->getRAngleLoc());
1183    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1184                      ExplicitArgs, TemplateArgs))
1185      return 0;
1186
1187    // Map the candidate templates to their instantiations.
1188    for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1189      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1190                                                Info->getTemplate(I),
1191                                                TemplateArgs);
1192      if (!Temp) return 0;
1193
1194      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1195    }
1196
1197    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1198                                                    &ExplicitArgs,
1199                                                    Previous))
1200      Function->setInvalidDecl();
1201
1202    isExplicitSpecialization = true;
1203
1204  } else if (TemplateParams || !FunctionTemplate) {
1205    // Look only into the namespace where the friend would be declared to
1206    // find a previous declaration. This is the innermost enclosing namespace,
1207    // as described in ActOnFriendFunctionDecl.
1208    SemaRef.LookupQualifiedName(Previous, DC);
1209
1210    // In C++, the previous declaration we find might be a tag type
1211    // (class or enum). In this case, the new declaration will hide the
1212    // tag type. Note that this does does not apply if we're declaring a
1213    // typedef (C++ [dcl.typedef]p4).
1214    if (Previous.isSingleTagDecl())
1215      Previous.clear();
1216  }
1217
1218  SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1219                                   isExplicitSpecialization);
1220
1221  NamedDecl *PrincipalDecl = (TemplateParams
1222                              ? cast<NamedDecl>(FunctionTemplate)
1223                              : Function);
1224
1225  // If the original function was part of a friend declaration,
1226  // inherit its namespace state and add it to the owner.
1227  if (isFriend) {
1228    NamedDecl *PrevDecl;
1229    if (TemplateParams)
1230      PrevDecl = FunctionTemplate->getPreviousDecl();
1231    else
1232      PrevDecl = Function->getPreviousDecl();
1233
1234    PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1235    DC->makeDeclVisibleInContext(PrincipalDecl);
1236
1237    bool queuedInstantiation = false;
1238
1239    // C++98 [temp.friend]p5: When a function is defined in a friend function
1240    //   declaration in a class template, the function is defined at each
1241    //   instantiation of the class template. The function is defined even if it
1242    //   is never used.
1243    // C++11 [temp.friend]p4: When a function is defined in a friend function
1244    //   declaration in a class template, the function is instantiated when the
1245    //   function is odr-used.
1246    //
1247    // If -Wc++98-compat is enabled, we go through the motions of checking for a
1248    // redefinition, but don't instantiate the function.
1249    if ((!SemaRef.getLangOpts().CPlusPlus0x ||
1250         SemaRef.Diags.getDiagnosticLevel(
1251             diag::warn_cxx98_compat_friend_redefinition,
1252             Function->getLocation())
1253           != DiagnosticsEngine::Ignored) &&
1254        D->isThisDeclarationADefinition()) {
1255      // Check for a function body.
1256      const FunctionDecl *Definition = 0;
1257      if (Function->isDefined(Definition) &&
1258          Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1259        SemaRef.Diag(Function->getLocation(),
1260                     SemaRef.getLangOpts().CPlusPlus0x ?
1261                       diag::warn_cxx98_compat_friend_redefinition :
1262                       diag::err_redefinition) << Function->getDeclName();
1263        SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1264        if (!SemaRef.getLangOpts().CPlusPlus0x)
1265          Function->setInvalidDecl();
1266      }
1267      // Check for redefinitions due to other instantiations of this or
1268      // a similar friend function.
1269      else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1270                                           REnd = Function->redecls_end();
1271                R != REnd; ++R) {
1272        if (*R == Function)
1273          continue;
1274        switch (R->getFriendObjectKind()) {
1275        case Decl::FOK_None:
1276          if (!SemaRef.getLangOpts().CPlusPlus0x &&
1277              !queuedInstantiation && R->isUsed(false)) {
1278            if (MemberSpecializationInfo *MSInfo
1279                = Function->getMemberSpecializationInfo()) {
1280              if (MSInfo->getPointOfInstantiation().isInvalid()) {
1281                SourceLocation Loc = R->getLocation(); // FIXME
1282                MSInfo->setPointOfInstantiation(Loc);
1283                SemaRef.PendingLocalImplicitInstantiations.push_back(
1284                                                 std::make_pair(Function, Loc));
1285                queuedInstantiation = true;
1286              }
1287            }
1288          }
1289          break;
1290        default:
1291          if (const FunctionDecl *RPattern
1292              = R->getTemplateInstantiationPattern())
1293            if (RPattern->isDefined(RPattern)) {
1294              SemaRef.Diag(Function->getLocation(),
1295                           SemaRef.getLangOpts().CPlusPlus0x ?
1296                             diag::warn_cxx98_compat_friend_redefinition :
1297                             diag::err_redefinition)
1298                << Function->getDeclName();
1299              SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1300              if (!SemaRef.getLangOpts().CPlusPlus0x)
1301                Function->setInvalidDecl();
1302              break;
1303            }
1304        }
1305      }
1306    }
1307  }
1308
1309  if (Function->isOverloadedOperator() && !DC->isRecord() &&
1310      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1311    PrincipalDecl->setNonMemberOperator();
1312
1313  assert(!D->isDefaulted() && "only methods should be defaulted");
1314  return Function;
1315}
1316
1317Decl *
1318TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1319                                      TemplateParameterList *TemplateParams,
1320                                      bool IsClassScopeSpecialization) {
1321  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1322  if (FunctionTemplate && !TemplateParams) {
1323    // We are creating a function template specialization from a function
1324    // template. Check whether there is already a function template
1325    // specialization for this particular set of template arguments.
1326    std::pair<const TemplateArgument *, unsigned> Innermost
1327      = TemplateArgs.getInnermost();
1328
1329    void *InsertPos = 0;
1330    FunctionDecl *SpecFunc
1331      = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1332                                             InsertPos);
1333
1334    // If we already have a function template specialization, return it.
1335    if (SpecFunc)
1336      return SpecFunc;
1337  }
1338
1339  bool isFriend;
1340  if (FunctionTemplate)
1341    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1342  else
1343    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1344
1345  bool MergeWithParentScope = (TemplateParams != 0) ||
1346    !(isa<Decl>(Owner) &&
1347      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1348  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1349
1350  // Instantiate enclosing template arguments for friends.
1351  SmallVector<TemplateParameterList *, 4> TempParamLists;
1352  unsigned NumTempParamLists = 0;
1353  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1354    TempParamLists.set_size(NumTempParamLists);
1355    for (unsigned I = 0; I != NumTempParamLists; ++I) {
1356      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1357      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1358      if (!InstParams)
1359        return NULL;
1360      TempParamLists[I] = InstParams;
1361    }
1362  }
1363
1364  SmallVector<ParmVarDecl *, 4> Params;
1365  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1366  if (!TInfo)
1367    return 0;
1368  QualType T = TInfo->getType();
1369
1370  // \brief If the type of this function, after ignoring parentheses,
1371  // is not *directly* a function type, then we're instantiating a function
1372  // that was declared via a typedef, e.g.,
1373  //
1374  //   typedef int functype(int, int);
1375  //   functype func;
1376  //
1377  // In this case, we'll just go instantiate the ParmVarDecls that we
1378  // synthesized in the method declaration.
1379  if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1380    assert(!Params.size() && "Instantiating type could not yield parameters");
1381    SmallVector<QualType, 4> ParamTypes;
1382    if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1383                               D->getNumParams(), TemplateArgs, ParamTypes,
1384                               &Params))
1385      return 0;
1386  }
1387
1388  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1389  if (QualifierLoc) {
1390    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1391                                                 TemplateArgs);
1392    if (!QualifierLoc)
1393      return 0;
1394  }
1395
1396  DeclContext *DC = Owner;
1397  if (isFriend) {
1398    if (QualifierLoc) {
1399      CXXScopeSpec SS;
1400      SS.Adopt(QualifierLoc);
1401      DC = SemaRef.computeDeclContext(SS);
1402
1403      if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1404        return 0;
1405    } else {
1406      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1407                                           D->getDeclContext(),
1408                                           TemplateArgs);
1409    }
1410    if (!DC) return 0;
1411  }
1412
1413  // Build the instantiated method declaration.
1414  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1415  CXXMethodDecl *Method = 0;
1416
1417  SourceLocation StartLoc = D->getInnerLocStart();
1418  DeclarationNameInfo NameInfo
1419    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1420  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1421    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1422                                        StartLoc, NameInfo, T, TInfo,
1423                                        Constructor->isExplicit(),
1424                                        Constructor->isInlineSpecified(),
1425                                        false, Constructor->isConstexpr());
1426  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1427    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1428                                       StartLoc, NameInfo, T, TInfo,
1429                                       Destructor->isInlineSpecified(),
1430                                       false);
1431  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1432    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1433                                       StartLoc, NameInfo, T, TInfo,
1434                                       Conversion->isInlineSpecified(),
1435                                       Conversion->isExplicit(),
1436                                       Conversion->isConstexpr(),
1437                                       Conversion->getLocEnd());
1438  } else {
1439    Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1440                                   StartLoc, NameInfo, T, TInfo,
1441                                   D->isStatic(),
1442                                   D->getStorageClassAsWritten(),
1443                                   D->isInlineSpecified(),
1444                                   D->isConstexpr(), D->getLocEnd());
1445  }
1446
1447  if (QualifierLoc)
1448    Method->setQualifierInfo(QualifierLoc);
1449
1450  if (TemplateParams) {
1451    // Our resulting instantiation is actually a function template, since we
1452    // are substituting only the outer template parameters. For example, given
1453    //
1454    //   template<typename T>
1455    //   struct X {
1456    //     template<typename U> void f(T, U);
1457    //   };
1458    //
1459    //   X<int> x;
1460    //
1461    // We are instantiating the member template "f" within X<int>, which means
1462    // substituting int for T, but leaving "f" as a member function template.
1463    // Build the function template itself.
1464    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1465                                                    Method->getLocation(),
1466                                                    Method->getDeclName(),
1467                                                    TemplateParams, Method);
1468    if (isFriend) {
1469      FunctionTemplate->setLexicalDeclContext(Owner);
1470      FunctionTemplate->setObjectOfFriendDecl(true);
1471    } else if (D->isOutOfLine())
1472      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1473    Method->setDescribedFunctionTemplate(FunctionTemplate);
1474  } else if (FunctionTemplate) {
1475    // Record this function template specialization.
1476    std::pair<const TemplateArgument *, unsigned> Innermost
1477      = TemplateArgs.getInnermost();
1478    Method->setFunctionTemplateSpecialization(FunctionTemplate,
1479                         TemplateArgumentList::CreateCopy(SemaRef.Context,
1480                                                          Innermost.first,
1481                                                          Innermost.second),
1482                                              /*InsertPos=*/0);
1483  } else if (!isFriend) {
1484    // Record that this is an instantiation of a member function.
1485    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1486  }
1487
1488  // If we are instantiating a member function defined
1489  // out-of-line, the instantiation will have the same lexical
1490  // context (which will be a namespace scope) as the template.
1491  if (isFriend) {
1492    if (NumTempParamLists)
1493      Method->setTemplateParameterListsInfo(SemaRef.Context,
1494                                            NumTempParamLists,
1495                                            TempParamLists.data());
1496
1497    Method->setLexicalDeclContext(Owner);
1498    Method->setObjectOfFriendDecl(true);
1499  } else if (D->isOutOfLine())
1500    Method->setLexicalDeclContext(D->getLexicalDeclContext());
1501
1502  // Attach the parameters
1503  for (unsigned P = 0; P < Params.size(); ++P)
1504    Params[P]->setOwningFunction(Method);
1505  Method->setParams(Params);
1506
1507  if (InitMethodInstantiation(Method, D))
1508    Method->setInvalidDecl();
1509
1510  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1511                        Sema::ForRedeclaration);
1512
1513  if (!FunctionTemplate || TemplateParams || isFriend) {
1514    SemaRef.LookupQualifiedName(Previous, Record);
1515
1516    // In C++, the previous declaration we find might be a tag type
1517    // (class or enum). In this case, the new declaration will hide the
1518    // tag type. Note that this does does not apply if we're declaring a
1519    // typedef (C++ [dcl.typedef]p4).
1520    if (Previous.isSingleTagDecl())
1521      Previous.clear();
1522  }
1523
1524  if (!IsClassScopeSpecialization)
1525    SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1526
1527  if (D->isPure())
1528    SemaRef.CheckPureMethod(Method, SourceRange());
1529
1530  Method->setAccess(D->getAccess());
1531
1532  SemaRef.CheckOverrideControl(Method);
1533
1534  // If a function is defined as defaulted or deleted, mark it as such now.
1535  if (D->isDefaulted())
1536    Method->setDefaulted();
1537  if (D->isDeletedAsWritten())
1538    Method->setDeletedAsWritten();
1539
1540  if (FunctionTemplate) {
1541    // If there's a function template, let our caller handle it.
1542  } else if (Method->isInvalidDecl() && !Previous.empty()) {
1543    // Don't hide a (potentially) valid declaration with an invalid one.
1544  } else {
1545    NamedDecl *DeclToAdd = (TemplateParams
1546                            ? cast<NamedDecl>(FunctionTemplate)
1547                            : Method);
1548    if (isFriend)
1549      Record->makeDeclVisibleInContext(DeclToAdd);
1550    else if (!IsClassScopeSpecialization)
1551      Owner->addDecl(DeclToAdd);
1552  }
1553
1554  if (D->isExplicitlyDefaulted()) {
1555    SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1556  } else {
1557    assert(!D->isDefaulted() &&
1558           "should not implicitly default uninstantiated function");
1559  }
1560
1561  return Method;
1562}
1563
1564Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1565  return VisitCXXMethodDecl(D);
1566}
1567
1568Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1569  return VisitCXXMethodDecl(D);
1570}
1571
1572Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1573  return VisitCXXMethodDecl(D);
1574}
1575
1576ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1577  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1578                                  llvm::Optional<unsigned>(),
1579                                  /*ExpectParameterPack=*/false);
1580}
1581
1582Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1583                                                    TemplateTypeParmDecl *D) {
1584  // TODO: don't always clone when decls are refcounted.
1585  assert(D->getTypeForDecl()->isTemplateTypeParmType());
1586
1587  TemplateTypeParmDecl *Inst =
1588    TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1589                                 D->getLocStart(), D->getLocation(),
1590                                 D->getDepth() - TemplateArgs.getNumLevels(),
1591                                 D->getIndex(), D->getIdentifier(),
1592                                 D->wasDeclaredWithTypename(),
1593                                 D->isParameterPack());
1594  Inst->setAccess(AS_public);
1595
1596  if (D->hasDefaultArgument())
1597    Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1598
1599  // Introduce this template parameter's instantiation into the instantiation
1600  // scope.
1601  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1602
1603  return Inst;
1604}
1605
1606Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1607                                                 NonTypeTemplateParmDecl *D) {
1608  // Substitute into the type of the non-type template parameter.
1609  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1610  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1611  SmallVector<QualType, 4> ExpandedParameterPackTypes;
1612  bool IsExpandedParameterPack = false;
1613  TypeSourceInfo *DI;
1614  QualType T;
1615  bool Invalid = false;
1616
1617  if (D->isExpandedParameterPack()) {
1618    // The non-type template parameter pack is an already-expanded pack
1619    // expansion of types. Substitute into each of the expanded types.
1620    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1621    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1622    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1623      TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1624                                               TemplateArgs,
1625                                               D->getLocation(),
1626                                               D->getDeclName());
1627      if (!NewDI)
1628        return 0;
1629
1630      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1631      QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1632                                                              D->getLocation());
1633      if (NewT.isNull())
1634        return 0;
1635      ExpandedParameterPackTypes.push_back(NewT);
1636    }
1637
1638    IsExpandedParameterPack = true;
1639    DI = D->getTypeSourceInfo();
1640    T = DI->getType();
1641  } else if (isa<PackExpansionTypeLoc>(TL)) {
1642    // The non-type template parameter pack's type is a pack expansion of types.
1643    // Determine whether we need to expand this parameter pack into separate
1644    // types.
1645    PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1646    TypeLoc Pattern = Expansion.getPatternLoc();
1647    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1648    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1649
1650    // Determine whether the set of unexpanded parameter packs can and should
1651    // be expanded.
1652    bool Expand = true;
1653    bool RetainExpansion = false;
1654    llvm::Optional<unsigned> OrigNumExpansions
1655      = Expansion.getTypePtr()->getNumExpansions();
1656    llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1657    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1658                                                Pattern.getSourceRange(),
1659                                                Unexpanded,
1660                                                TemplateArgs,
1661                                                Expand, RetainExpansion,
1662                                                NumExpansions))
1663      return 0;
1664
1665    if (Expand) {
1666      for (unsigned I = 0; I != *NumExpansions; ++I) {
1667        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1668        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1669                                                  D->getLocation(),
1670                                                  D->getDeclName());
1671        if (!NewDI)
1672          return 0;
1673
1674        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1675        QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1676                                                              NewDI->getType(),
1677                                                              D->getLocation());
1678        if (NewT.isNull())
1679          return 0;
1680        ExpandedParameterPackTypes.push_back(NewT);
1681      }
1682
1683      // Note that we have an expanded parameter pack. The "type" of this
1684      // expanded parameter pack is the original expansion type, but callers
1685      // will end up using the expanded parameter pack types for type-checking.
1686      IsExpandedParameterPack = true;
1687      DI = D->getTypeSourceInfo();
1688      T = DI->getType();
1689    } else {
1690      // We cannot fully expand the pack expansion now, so substitute into the
1691      // pattern and create a new pack expansion type.
1692      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1693      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1694                                                     D->getLocation(),
1695                                                     D->getDeclName());
1696      if (!NewPattern)
1697        return 0;
1698
1699      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1700                                      NumExpansions);
1701      if (!DI)
1702        return 0;
1703
1704      T = DI->getType();
1705    }
1706  } else {
1707    // Simple case: substitution into a parameter that is not a parameter pack.
1708    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1709                           D->getLocation(), D->getDeclName());
1710    if (!DI)
1711      return 0;
1712
1713    // Check that this type is acceptable for a non-type template parameter.
1714    T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1715                                                  D->getLocation());
1716    if (T.isNull()) {
1717      T = SemaRef.Context.IntTy;
1718      Invalid = true;
1719    }
1720  }
1721
1722  NonTypeTemplateParmDecl *Param;
1723  if (IsExpandedParameterPack)
1724    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1725                                            D->getInnerLocStart(),
1726                                            D->getLocation(),
1727                                    D->getDepth() - TemplateArgs.getNumLevels(),
1728                                            D->getPosition(),
1729                                            D->getIdentifier(), T,
1730                                            DI,
1731                                            ExpandedParameterPackTypes.data(),
1732                                            ExpandedParameterPackTypes.size(),
1733                                    ExpandedParameterPackTypesAsWritten.data());
1734  else
1735    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1736                                            D->getInnerLocStart(),
1737                                            D->getLocation(),
1738                                    D->getDepth() - TemplateArgs.getNumLevels(),
1739                                            D->getPosition(),
1740                                            D->getIdentifier(), T,
1741                                            D->isParameterPack(), DI);
1742
1743  Param->setAccess(AS_public);
1744  if (Invalid)
1745    Param->setInvalidDecl();
1746
1747  Param->setDefaultArgument(D->getDefaultArgument(), false);
1748
1749  // Introduce this template parameter's instantiation into the instantiation
1750  // scope.
1751  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1752  return Param;
1753}
1754
1755Decl *
1756TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1757                                                  TemplateTemplateParmDecl *D) {
1758  // Instantiate the template parameter list of the template template parameter.
1759  TemplateParameterList *TempParams = D->getTemplateParameters();
1760  TemplateParameterList *InstParams;
1761  {
1762    // Perform the actual substitution of template parameters within a new,
1763    // local instantiation scope.
1764    LocalInstantiationScope Scope(SemaRef);
1765    InstParams = SubstTemplateParams(TempParams);
1766    if (!InstParams)
1767      return NULL;
1768  }
1769
1770  // Build the template template parameter.
1771  TemplateTemplateParmDecl *Param
1772    = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1773                                   D->getDepth() - TemplateArgs.getNumLevels(),
1774                                       D->getPosition(), D->isParameterPack(),
1775                                       D->getIdentifier(), InstParams);
1776  Param->setDefaultArgument(D->getDefaultArgument(), false);
1777  Param->setAccess(AS_public);
1778
1779  // Introduce this template parameter's instantiation into the instantiation
1780  // scope.
1781  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1782
1783  return Param;
1784}
1785
1786Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1787  // Using directives are never dependent (and never contain any types or
1788  // expressions), so they require no explicit instantiation work.
1789
1790  UsingDirectiveDecl *Inst
1791    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1792                                 D->getNamespaceKeyLocation(),
1793                                 D->getQualifierLoc(),
1794                                 D->getIdentLocation(),
1795                                 D->getNominatedNamespace(),
1796                                 D->getCommonAncestor());
1797  Owner->addDecl(Inst);
1798  return Inst;
1799}
1800
1801Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1802
1803  // The nested name specifier may be dependent, for example
1804  //     template <typename T> struct t {
1805  //       struct s1 { T f1(); };
1806  //       struct s2 : s1 { using s1::f1; };
1807  //     };
1808  //     template struct t<int>;
1809  // Here, in using s1::f1, s1 refers to t<T>::s1;
1810  // we need to substitute for t<int>::s1.
1811  NestedNameSpecifierLoc QualifierLoc
1812    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1813                                          TemplateArgs);
1814  if (!QualifierLoc)
1815    return 0;
1816
1817  // The name info is non-dependent, so no transformation
1818  // is required.
1819  DeclarationNameInfo NameInfo = D->getNameInfo();
1820
1821  // We only need to do redeclaration lookups if we're in a class
1822  // scope (in fact, it's not really even possible in non-class
1823  // scopes).
1824  bool CheckRedeclaration = Owner->isRecord();
1825
1826  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1827                    Sema::ForRedeclaration);
1828
1829  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1830                                       D->getUsingLocation(),
1831                                       QualifierLoc,
1832                                       NameInfo,
1833                                       D->isTypeName());
1834
1835  CXXScopeSpec SS;
1836  SS.Adopt(QualifierLoc);
1837  if (CheckRedeclaration) {
1838    Prev.setHideTags(false);
1839    SemaRef.LookupQualifiedName(Prev, Owner);
1840
1841    // Check for invalid redeclarations.
1842    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1843                                            D->isTypeName(), SS,
1844                                            D->getLocation(), Prev))
1845      NewUD->setInvalidDecl();
1846
1847  }
1848
1849  if (!NewUD->isInvalidDecl() &&
1850      SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
1851                                      D->getLocation()))
1852    NewUD->setInvalidDecl();
1853
1854  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1855  NewUD->setAccess(D->getAccess());
1856  Owner->addDecl(NewUD);
1857
1858  // Don't process the shadow decls for an invalid decl.
1859  if (NewUD->isInvalidDecl())
1860    return NewUD;
1861
1862  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
1863    if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
1864      NewUD->setInvalidDecl();
1865    return NewUD;
1866  }
1867
1868  bool isFunctionScope = Owner->isFunctionOrMethod();
1869
1870  // Process the shadow decls.
1871  for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1872         I != E; ++I) {
1873    UsingShadowDecl *Shadow = *I;
1874    NamedDecl *InstTarget =
1875      cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1876                                                          Shadow->getLocation(),
1877                                                        Shadow->getTargetDecl(),
1878                                                           TemplateArgs));
1879    if (!InstTarget)
1880      return 0;
1881
1882    if (CheckRedeclaration &&
1883        SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1884      continue;
1885
1886    UsingShadowDecl *InstShadow
1887      = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1888    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
1889
1890    if (isFunctionScope)
1891      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
1892  }
1893
1894  return NewUD;
1895}
1896
1897Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
1898  // Ignore these;  we handle them in bulk when processing the UsingDecl.
1899  return 0;
1900}
1901
1902Decl * TemplateDeclInstantiator
1903    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1904  NestedNameSpecifierLoc QualifierLoc
1905    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1906                                          TemplateArgs);
1907  if (!QualifierLoc)
1908    return 0;
1909
1910  CXXScopeSpec SS;
1911  SS.Adopt(QualifierLoc);
1912
1913  // Since NameInfo refers to a typename, it cannot be a C++ special name.
1914  // Hence, no tranformation is required for it.
1915  DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
1916  NamedDecl *UD =
1917    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1918                                  D->getUsingLoc(), SS, NameInfo, 0,
1919                                  /*instantiation*/ true,
1920                                  /*typename*/ true, D->getTypenameLoc());
1921  if (UD)
1922    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1923
1924  return UD;
1925}
1926
1927Decl * TemplateDeclInstantiator
1928    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1929  NestedNameSpecifierLoc QualifierLoc
1930      = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1931  if (!QualifierLoc)
1932    return 0;
1933
1934  CXXScopeSpec SS;
1935  SS.Adopt(QualifierLoc);
1936
1937  DeclarationNameInfo NameInfo
1938    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1939
1940  NamedDecl *UD =
1941    SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1942                                  D->getUsingLoc(), SS, NameInfo, 0,
1943                                  /*instantiation*/ true,
1944                                  /*typename*/ false, SourceLocation());
1945  if (UD)
1946    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1947
1948  return UD;
1949}
1950
1951
1952Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
1953                                     ClassScopeFunctionSpecializationDecl *Decl) {
1954  CXXMethodDecl *OldFD = Decl->getSpecialization();
1955  CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
1956                                                                0, true));
1957
1958  LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
1959                        Sema::ForRedeclaration);
1960
1961  TemplateArgumentListInfo TemplateArgs;
1962  TemplateArgumentListInfo* TemplateArgsPtr = 0;
1963  if (Decl->hasExplicitTemplateArgs()) {
1964    TemplateArgs = Decl->templateArgs();
1965    TemplateArgsPtr = &TemplateArgs;
1966  }
1967
1968  SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
1969  if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
1970                                                  Previous)) {
1971    NewFD->setInvalidDecl();
1972    return NewFD;
1973  }
1974
1975  // Associate the specialization with the pattern.
1976  FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
1977  assert(Specialization && "Class scope Specialization is null");
1978  SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
1979
1980  return NewFD;
1981}
1982
1983Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
1984                      const MultiLevelTemplateArgumentList &TemplateArgs) {
1985  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
1986  if (D->isInvalidDecl())
1987    return 0;
1988
1989  return Instantiator.Visit(D);
1990}
1991
1992/// \brief Instantiates a nested template parameter list in the current
1993/// instantiation context.
1994///
1995/// \param L The parameter list to instantiate
1996///
1997/// \returns NULL if there was an error
1998TemplateParameterList *
1999TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2000  // Get errors for all the parameters before bailing out.
2001  bool Invalid = false;
2002
2003  unsigned N = L->size();
2004  typedef SmallVector<NamedDecl *, 8> ParamVector;
2005  ParamVector Params;
2006  Params.reserve(N);
2007  for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2008       PI != PE; ++PI) {
2009    NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2010    Params.push_back(D);
2011    Invalid = Invalid || !D || D->isInvalidDecl();
2012  }
2013
2014  // Clean up if we had an error.
2015  if (Invalid)
2016    return NULL;
2017
2018  TemplateParameterList *InstL
2019    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2020                                    L->getLAngleLoc(), &Params.front(), N,
2021                                    L->getRAngleLoc());
2022  return InstL;
2023}
2024
2025/// \brief Instantiate the declaration of a class template partial
2026/// specialization.
2027///
2028/// \param ClassTemplate the (instantiated) class template that is partially
2029// specialized by the instantiation of \p PartialSpec.
2030///
2031/// \param PartialSpec the (uninstantiated) class template partial
2032/// specialization that we are instantiating.
2033///
2034/// \returns The instantiated partial specialization, if successful; otherwise,
2035/// NULL to indicate an error.
2036ClassTemplatePartialSpecializationDecl *
2037TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2038                                            ClassTemplateDecl *ClassTemplate,
2039                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
2040  // Create a local instantiation scope for this class template partial
2041  // specialization, which will contain the instantiations of the template
2042  // parameters.
2043  LocalInstantiationScope Scope(SemaRef);
2044
2045  // Substitute into the template parameters of the class template partial
2046  // specialization.
2047  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2048  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2049  if (!InstParams)
2050    return 0;
2051
2052  // Substitute into the template arguments of the class template partial
2053  // specialization.
2054  TemplateArgumentListInfo InstTemplateArgs; // no angle locations
2055  if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2056                    PartialSpec->getNumTemplateArgsAsWritten(),
2057                    InstTemplateArgs, TemplateArgs))
2058    return 0;
2059
2060  // Check that the template argument list is well-formed for this
2061  // class template.
2062  SmallVector<TemplateArgument, 4> Converted;
2063  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2064                                        PartialSpec->getLocation(),
2065                                        InstTemplateArgs,
2066                                        false,
2067                                        Converted))
2068    return 0;
2069
2070  // Figure out where to insert this class template partial specialization
2071  // in the member template's set of class template partial specializations.
2072  void *InsertPos = 0;
2073  ClassTemplateSpecializationDecl *PrevDecl
2074    = ClassTemplate->findPartialSpecialization(Converted.data(),
2075                                               Converted.size(), InsertPos);
2076
2077  // Build the canonical type that describes the converted template
2078  // arguments of the class template partial specialization.
2079  QualType CanonType
2080    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2081                                                    Converted.data(),
2082                                                    Converted.size());
2083
2084  // Build the fully-sugared type for this class template
2085  // specialization as the user wrote in the specialization
2086  // itself. This means that we'll pretty-print the type retrieved
2087  // from the specialization's declaration the way that the user
2088  // actually wrote the specialization, rather than formatting the
2089  // name based on the "canonical" representation used to store the
2090  // template arguments in the specialization.
2091  TypeSourceInfo *WrittenTy
2092    = SemaRef.Context.getTemplateSpecializationTypeInfo(
2093                                                    TemplateName(ClassTemplate),
2094                                                    PartialSpec->getLocation(),
2095                                                    InstTemplateArgs,
2096                                                    CanonType);
2097
2098  if (PrevDecl) {
2099    // We've already seen a partial specialization with the same template
2100    // parameters and template arguments. This can happen, for example, when
2101    // substituting the outer template arguments ends up causing two
2102    // class template partial specializations of a member class template
2103    // to have identical forms, e.g.,
2104    //
2105    //   template<typename T, typename U>
2106    //   struct Outer {
2107    //     template<typename X, typename Y> struct Inner;
2108    //     template<typename Y> struct Inner<T, Y>;
2109    //     template<typename Y> struct Inner<U, Y>;
2110    //   };
2111    //
2112    //   Outer<int, int> outer; // error: the partial specializations of Inner
2113    //                          // have the same signature.
2114    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2115      << WrittenTy->getType();
2116    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2117      << SemaRef.Context.getTypeDeclType(PrevDecl);
2118    return 0;
2119  }
2120
2121
2122  // Create the class template partial specialization declaration.
2123  ClassTemplatePartialSpecializationDecl *InstPartialSpec
2124    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2125                                                     PartialSpec->getTagKind(),
2126                                                     Owner,
2127                                                     PartialSpec->getLocStart(),
2128                                                     PartialSpec->getLocation(),
2129                                                     InstParams,
2130                                                     ClassTemplate,
2131                                                     Converted.data(),
2132                                                     Converted.size(),
2133                                                     InstTemplateArgs,
2134                                                     CanonType,
2135                                                     0,
2136                             ClassTemplate->getNextPartialSpecSequenceNumber());
2137  // Substitute the nested name specifier, if any.
2138  if (SubstQualifier(PartialSpec, InstPartialSpec))
2139    return 0;
2140
2141  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2142  InstPartialSpec->setTypeAsWritten(WrittenTy);
2143
2144  // Add this partial specialization to the set of class template partial
2145  // specializations.
2146  ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2147  return InstPartialSpec;
2148}
2149
2150TypeSourceInfo*
2151TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2152                              SmallVectorImpl<ParmVarDecl *> &Params) {
2153  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2154  assert(OldTInfo && "substituting function without type source info");
2155  assert(Params.empty() && "parameter vector is non-empty at start");
2156
2157  CXXRecordDecl *ThisContext = 0;
2158  unsigned ThisTypeQuals = 0;
2159  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2160    ThisContext = Method->getParent();
2161    ThisTypeQuals = Method->getTypeQualifiers();
2162  }
2163
2164  TypeSourceInfo *NewTInfo
2165    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2166                                    D->getTypeSpecStartLoc(),
2167                                    D->getDeclName(),
2168                                    ThisContext, ThisTypeQuals);
2169  if (!NewTInfo)
2170    return 0;
2171
2172  if (NewTInfo != OldTInfo) {
2173    // Get parameters from the new type info.
2174    TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2175    if (FunctionProtoTypeLoc *OldProtoLoc
2176                                  = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2177      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2178      FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2179      assert(NewProtoLoc && "Missing prototype?");
2180      unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2181      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2182           OldIdx != NumOldParams; ++OldIdx) {
2183        ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2184        if (!OldParam->isParameterPack() ||
2185            // FIXME: Is this right? OldParam could expand to an empty parameter
2186            // pack and the next parameter could be an unexpanded parameter pack
2187            (NewIdx < NumNewParams &&
2188             NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2189          // Simple case: normal parameter, or a parameter pack that's
2190          // instantiated to a (still-dependent) parameter pack.
2191          ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2192          Params.push_back(NewParam);
2193          SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2194                                                               NewParam);
2195          continue;
2196        }
2197
2198        // Parameter pack: make the instantiation an argument pack.
2199        SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2200                                                                      OldParam);
2201        unsigned NumArgumentsInExpansion
2202          = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2203                                               TemplateArgs);
2204        while (NumArgumentsInExpansion--) {
2205          ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2206          Params.push_back(NewParam);
2207          SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2208                                                                      NewParam);
2209        }
2210      }
2211    }
2212  } else {
2213    // The function type itself was not dependent and therefore no
2214    // substitution occurred. However, we still need to instantiate
2215    // the function parameters themselves.
2216    TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2217    if (FunctionProtoTypeLoc *OldProtoLoc
2218                                    = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2219      for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2220        ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2221        if (!Parm)
2222          return 0;
2223        Params.push_back(Parm);
2224      }
2225    }
2226  }
2227  return NewTInfo;
2228}
2229
2230/// Introduce the instantiated function parameters into the local
2231/// instantiation scope, and set the parameter names to those used
2232/// in the template.
2233static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2234                                             const FunctionDecl *PatternDecl,
2235                                             LocalInstantiationScope &Scope,
2236                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2237  unsigned FParamIdx = 0;
2238  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2239    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2240    if (!PatternParam->isParameterPack()) {
2241      // Simple case: not a parameter pack.
2242      assert(FParamIdx < Function->getNumParams());
2243      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2244      FunctionParam->setDeclName(PatternParam->getDeclName());
2245      Scope.InstantiatedLocal(PatternParam, FunctionParam);
2246      ++FParamIdx;
2247      continue;
2248    }
2249
2250    // Expand the parameter pack.
2251    Scope.MakeInstantiatedLocalArgPack(PatternParam);
2252    unsigned NumArgumentsInExpansion
2253      = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
2254    for (unsigned Arg = 0; Arg < NumArgumentsInExpansion; ++Arg) {
2255      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2256      FunctionParam->setDeclName(PatternParam->getDeclName());
2257      Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2258      ++FParamIdx;
2259    }
2260  }
2261}
2262
2263static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2264                                     const FunctionProtoType *Proto,
2265                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2266  assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2267
2268  // C++11 [expr.prim.general]p3:
2269  //   If a declaration declares a member function or member function
2270  //   template of a class X, the expression this is a prvalue of type
2271  //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2272  //   and the end of the function-definition, member-declarator, or
2273  //   declarator.
2274  CXXRecordDecl *ThisContext = 0;
2275  unsigned ThisTypeQuals = 0;
2276  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2277    ThisContext = Method->getParent();
2278    ThisTypeQuals = Method->getTypeQualifiers();
2279  }
2280  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
2281                                   SemaRef.getLangOpts().CPlusPlus0x);
2282
2283  // The function has an exception specification or a "noreturn"
2284  // attribute. Substitute into each of the exception types.
2285  SmallVector<QualType, 4> Exceptions;
2286  for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2287    // FIXME: Poor location information!
2288    if (const PackExpansionType *PackExpansion
2289          = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2290      // We have a pack expansion. Instantiate it.
2291      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2292      SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2293                                              Unexpanded);
2294      assert(!Unexpanded.empty() &&
2295             "Pack expansion without parameter packs?");
2296
2297      bool Expand = false;
2298      bool RetainExpansion = false;
2299      llvm::Optional<unsigned> NumExpansions
2300                                        = PackExpansion->getNumExpansions();
2301      if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2302                                                  SourceRange(),
2303                                                  Unexpanded,
2304                                                  TemplateArgs,
2305                                                  Expand,
2306                                                  RetainExpansion,
2307                                                  NumExpansions))
2308        break;
2309
2310      if (!Expand) {
2311        // We can't expand this pack expansion into separate arguments yet;
2312        // just substitute into the pattern and create a new pack expansion
2313        // type.
2314        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2315        QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2316                                       TemplateArgs,
2317                                     New->getLocation(), New->getDeclName());
2318        if (T.isNull())
2319          break;
2320
2321        T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2322        Exceptions.push_back(T);
2323        continue;
2324      }
2325
2326      // Substitute into the pack expansion pattern for each template
2327      bool Invalid = false;
2328      for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2329        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2330
2331        QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2332                                       TemplateArgs,
2333                                     New->getLocation(), New->getDeclName());
2334        if (T.isNull()) {
2335          Invalid = true;
2336          break;
2337        }
2338
2339        Exceptions.push_back(T);
2340      }
2341
2342      if (Invalid)
2343        break;
2344
2345      continue;
2346    }
2347
2348    QualType T
2349      = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2350                          New->getLocation(), New->getDeclName());
2351    if (T.isNull() ||
2352        SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2353      continue;
2354
2355    Exceptions.push_back(T);
2356  }
2357  Expr *NoexceptExpr = 0;
2358  if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2359    EnterExpressionEvaluationContext Unevaluated(SemaRef,
2360                                                 Sema::ConstantEvaluated);
2361    ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2362    if (E.isUsable())
2363      E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2364
2365    if (E.isUsable()) {
2366      NoexceptExpr = E.take();
2367      if (!NoexceptExpr->isTypeDependent() &&
2368          !NoexceptExpr->isValueDependent())
2369        NoexceptExpr
2370          = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2371              0, diag::err_noexcept_needs_constant_expression,
2372              /*AllowFold*/ false).take();
2373    }
2374  }
2375
2376  // Rebuild the function type
2377  const FunctionProtoType *NewProto
2378    = New->getType()->getAs<FunctionProtoType>();
2379  assert(NewProto && "Template instantiation without function prototype?");
2380
2381  FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2382  EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2383  EPI.NumExceptions = Exceptions.size();
2384  EPI.Exceptions = Exceptions.data();
2385  EPI.NoexceptExpr = NoexceptExpr;
2386
2387  New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2388                                               NewProto->arg_type_begin(),
2389                                               NewProto->getNumArgs(),
2390                                               EPI));
2391}
2392
2393void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2394                                    FunctionDecl *Decl) {
2395  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2396  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
2397    return;
2398
2399  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2400                             InstantiatingTemplate::ExceptionSpecification());
2401  if (Inst)
2402    return;
2403
2404  // Enter the scope of this instantiation. We don't use
2405  // PushDeclContext because we don't have a scope.
2406  Sema::ContextRAII savedContext(*this, Decl);
2407  LocalInstantiationScope Scope(*this);
2408
2409  MultiLevelTemplateArgumentList TemplateArgs =
2410    getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2411
2412  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2413  addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
2414
2415  ::InstantiateExceptionSpec(*this, Decl,
2416                             Template->getType()->castAs<FunctionProtoType>(),
2417                             TemplateArgs);
2418}
2419
2420/// \brief Initializes the common fields of an instantiation function
2421/// declaration (New) from the corresponding fields of its template (Tmpl).
2422///
2423/// \returns true if there was an error
2424bool
2425TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
2426                                                    FunctionDecl *Tmpl) {
2427  if (Tmpl->isDeletedAsWritten())
2428    New->setDeletedAsWritten();
2429
2430  // If we are performing substituting explicitly-specified template arguments
2431  // or deduced template arguments into a function template and we reach this
2432  // point, we are now past the point where SFINAE applies and have committed
2433  // to keeping the new function template specialization. We therefore
2434  // convert the active template instantiation for the function template
2435  // into a template instantiation for this specific function template
2436  // specialization, which is not a SFINAE context, so that we diagnose any
2437  // further errors in the declaration itself.
2438  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2439  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2440  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2441      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
2442    if (FunctionTemplateDecl *FunTmpl
2443          = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
2444      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
2445             "Deduction from the wrong function template?");
2446      (void) FunTmpl;
2447      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2448      ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
2449    }
2450  }
2451
2452  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2453  assert(Proto && "Function template without prototype?");
2454
2455  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
2456    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2457
2458    // DR1330: In C++11, defer instantiation of a non-trivial
2459    // exception specification.
2460    if (SemaRef.getLangOpts().CPlusPlus0x &&
2461        EPI.ExceptionSpecType != EST_None &&
2462        EPI.ExceptionSpecType != EST_DynamicNone &&
2463        EPI.ExceptionSpecType != EST_BasicNoexcept) {
2464      FunctionDecl *ExceptionSpecTemplate = Tmpl;
2465      if (EPI.ExceptionSpecType == EST_Uninstantiated)
2466        ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
2467
2468      // Mark the function has having an uninstantiated exception specification.
2469      const FunctionProtoType *NewProto
2470        = New->getType()->getAs<FunctionProtoType>();
2471      assert(NewProto && "Template instantiation without function prototype?");
2472      EPI = NewProto->getExtProtoInfo();
2473      EPI.ExceptionSpecType = EST_Uninstantiated;
2474      EPI.ExceptionSpecDecl = New;
2475      EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
2476      New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2477                                                   NewProto->arg_type_begin(),
2478                                                   NewProto->getNumArgs(),
2479                                                   EPI));
2480    } else {
2481      ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2482    }
2483  }
2484
2485  // Get the definition. Leaves the variable unchanged if undefined.
2486  const FunctionDecl *Definition = Tmpl;
2487  Tmpl->isDefined(Definition);
2488
2489  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2490                           LateAttrs, StartingScope);
2491
2492  return false;
2493}
2494
2495/// \brief Initializes common fields of an instantiated method
2496/// declaration (New) from the corresponding fields of its template
2497/// (Tmpl).
2498///
2499/// \returns true if there was an error
2500bool
2501TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2502                                                  CXXMethodDecl *Tmpl) {
2503  if (InitFunctionInstantiation(New, Tmpl))
2504    return true;
2505
2506  New->setAccess(Tmpl->getAccess());
2507  if (Tmpl->isVirtualAsWritten())
2508    New->setVirtualAsWritten(true);
2509
2510  // FIXME: attributes
2511  // FIXME: New needs a pointer to Tmpl
2512  return false;
2513}
2514
2515/// \brief Instantiate the definition of the given function from its
2516/// template.
2517///
2518/// \param PointOfInstantiation the point at which the instantiation was
2519/// required. Note that this is not precisely a "point of instantiation"
2520/// for the function, but it's close.
2521///
2522/// \param Function the already-instantiated declaration of a
2523/// function template specialization or member function of a class template
2524/// specialization.
2525///
2526/// \param Recursive if true, recursively instantiates any functions that
2527/// are required by this instantiation.
2528///
2529/// \param DefinitionRequired if true, then we are performing an explicit
2530/// instantiation where the body of the function is required. Complain if
2531/// there is no such body.
2532void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2533                                         FunctionDecl *Function,
2534                                         bool Recursive,
2535                                         bool DefinitionRequired) {
2536  if (Function->isInvalidDecl() || Function->isDefined())
2537    return;
2538
2539  // Never instantiate an explicit specialization except if it is a class scope
2540  // explicit specialization.
2541  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2542      !Function->getClassScopeSpecializationPattern())
2543    return;
2544
2545  // Find the function body that we'll be substituting.
2546  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2547  assert(PatternDecl && "instantiating a non-template");
2548
2549  Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2550  assert(PatternDecl && "template definition is not a template");
2551  if (!Pattern) {
2552    // Try to find a defaulted definition
2553    PatternDecl->isDefined(PatternDecl);
2554  }
2555  assert(PatternDecl && "template definition is not a template");
2556
2557  // Postpone late parsed template instantiations.
2558  if (PatternDecl->isLateTemplateParsed() &&
2559      !LateTemplateParser) {
2560    PendingInstantiations.push_back(
2561      std::make_pair(Function, PointOfInstantiation));
2562    return;
2563  }
2564
2565  // Call the LateTemplateParser callback if there a need to late parse
2566  // a templated function definition.
2567  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
2568      LateTemplateParser) {
2569    LateTemplateParser(OpaqueParser, PatternDecl);
2570    Pattern = PatternDecl->getBody(PatternDecl);
2571  }
2572
2573  if (!Pattern && !PatternDecl->isDefaulted()) {
2574    if (DefinitionRequired) {
2575      if (Function->getPrimaryTemplate())
2576        Diag(PointOfInstantiation,
2577             diag::err_explicit_instantiation_undefined_func_template)
2578          << Function->getPrimaryTemplate();
2579      else
2580        Diag(PointOfInstantiation,
2581             diag::err_explicit_instantiation_undefined_member)
2582          << 1 << Function->getDeclName() << Function->getDeclContext();
2583
2584      if (PatternDecl)
2585        Diag(PatternDecl->getLocation(),
2586             diag::note_explicit_instantiation_here);
2587      Function->setInvalidDecl();
2588    } else if (Function->getTemplateSpecializationKind()
2589                 == TSK_ExplicitInstantiationDefinition) {
2590      PendingInstantiations.push_back(
2591        std::make_pair(Function, PointOfInstantiation));
2592    }
2593
2594    return;
2595  }
2596
2597  // C++0x [temp.explicit]p9:
2598  //   Except for inline functions, other explicit instantiation declarations
2599  //   have the effect of suppressing the implicit instantiation of the entity
2600  //   to which they refer.
2601  if (Function->getTemplateSpecializationKind()
2602        == TSK_ExplicitInstantiationDeclaration &&
2603      !PatternDecl->isInlined())
2604    return;
2605
2606  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2607  if (Inst)
2608    return;
2609
2610  // Copy the inner loc start from the pattern.
2611  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2612
2613  // If we're performing recursive template instantiation, create our own
2614  // queue of pending implicit instantiations that we will instantiate later,
2615  // while we're still within our own instantiation context.
2616  SmallVector<VTableUse, 16> SavedVTableUses;
2617  std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2618  if (Recursive) {
2619    VTableUses.swap(SavedVTableUses);
2620    PendingInstantiations.swap(SavedPendingInstantiations);
2621  }
2622
2623  EnterExpressionEvaluationContext EvalContext(*this,
2624                                               Sema::PotentiallyEvaluated);
2625  ActOnStartOfFunctionDef(0, Function);
2626
2627  // Introduce a new scope where local variable instantiations will be
2628  // recorded, unless we're actually a member function within a local
2629  // class, in which case we need to merge our results with the parent
2630  // scope (of the enclosing function).
2631  bool MergeWithParentScope = false;
2632  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2633    MergeWithParentScope = Rec->isLocalClass();
2634
2635  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2636
2637  // Enter the scope of this instantiation. We don't use
2638  // PushDeclContext because we don't have a scope.
2639  Sema::ContextRAII savedContext(*this, Function);
2640
2641  MultiLevelTemplateArgumentList TemplateArgs =
2642    getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2643
2644  addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2645                                   TemplateArgs);
2646
2647  if (PatternDecl->isDefaulted()) {
2648    ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2649
2650    SetDeclDefaulted(Function, PatternDecl->getLocation());
2651  } else {
2652    // If this is a constructor, instantiate the member initializers.
2653    if (const CXXConstructorDecl *Ctor =
2654          dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2655      InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2656                                 TemplateArgs);
2657    }
2658
2659    // Instantiate the function body.
2660    StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2661
2662    if (Body.isInvalid())
2663      Function->setInvalidDecl();
2664
2665    ActOnFinishFunctionBody(Function, Body.get(),
2666                            /*IsInstantiation=*/true);
2667  }
2668
2669  PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2670
2671  savedContext.pop();
2672
2673  DeclGroupRef DG(Function);
2674  Consumer.HandleTopLevelDecl(DG);
2675
2676  // This class may have local implicit instantiations that need to be
2677  // instantiation within this scope.
2678  PerformPendingInstantiations(/*LocalOnly=*/true);
2679  Scope.Exit();
2680
2681  if (Recursive) {
2682    // Define any pending vtables.
2683    DefineUsedVTables();
2684
2685    // Instantiate any pending implicit instantiations found during the
2686    // instantiation of this template.
2687    PerformPendingInstantiations();
2688
2689    // Restore the set of pending vtables.
2690    assert(VTableUses.empty() &&
2691           "VTableUses should be empty before it is discarded.");
2692    VTableUses.swap(SavedVTableUses);
2693
2694    // Restore the set of pending implicit instantiations.
2695    assert(PendingInstantiations.empty() &&
2696           "PendingInstantiations should be empty before it is discarded.");
2697    PendingInstantiations.swap(SavedPendingInstantiations);
2698  }
2699}
2700
2701/// \brief Instantiate the definition of the given variable from its
2702/// template.
2703///
2704/// \param PointOfInstantiation the point at which the instantiation was
2705/// required. Note that this is not precisely a "point of instantiation"
2706/// for the function, but it's close.
2707///
2708/// \param Var the already-instantiated declaration of a static member
2709/// variable of a class template specialization.
2710///
2711/// \param Recursive if true, recursively instantiates any functions that
2712/// are required by this instantiation.
2713///
2714/// \param DefinitionRequired if true, then we are performing an explicit
2715/// instantiation where an out-of-line definition of the member variable
2716/// is required. Complain if there is no such definition.
2717void Sema::InstantiateStaticDataMemberDefinition(
2718                                          SourceLocation PointOfInstantiation,
2719                                                 VarDecl *Var,
2720                                                 bool Recursive,
2721                                                 bool DefinitionRequired) {
2722  if (Var->isInvalidDecl())
2723    return;
2724
2725  // Find the out-of-line definition of this static data member.
2726  VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
2727  assert(Def && "This data member was not instantiated from a template?");
2728  assert(Def->isStaticDataMember() && "Not a static data member?");
2729  Def = Def->getOutOfLineDefinition();
2730
2731  if (!Def) {
2732    // We did not find an out-of-line definition of this static data member,
2733    // so we won't perform any instantiation. Rather, we rely on the user to
2734    // instantiate this definition (or provide a specialization for it) in
2735    // another translation unit.
2736    if (DefinitionRequired) {
2737      Def = Var->getInstantiatedFromStaticDataMember();
2738      Diag(PointOfInstantiation,
2739           diag::err_explicit_instantiation_undefined_member)
2740        << 2 << Var->getDeclName() << Var->getDeclContext();
2741      Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2742    } else if (Var->getTemplateSpecializationKind()
2743                 == TSK_ExplicitInstantiationDefinition) {
2744      PendingInstantiations.push_back(
2745        std::make_pair(Var, PointOfInstantiation));
2746    }
2747
2748    return;
2749  }
2750
2751  TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
2752
2753  // Never instantiate an explicit specialization.
2754  if (TSK == TSK_ExplicitSpecialization)
2755    return;
2756
2757  // C++0x [temp.explicit]p9:
2758  //   Except for inline functions, other explicit instantiation declarations
2759  //   have the effect of suppressing the implicit instantiation of the entity
2760  //   to which they refer.
2761  if (TSK == TSK_ExplicitInstantiationDeclaration)
2762    return;
2763
2764  Consumer.HandleCXXStaticMemberVarInstantiation(Var);
2765
2766  // If we already have a definition, we're done.
2767  if (VarDecl *Def = Var->getDefinition()) {
2768    // We may be explicitly instantiating something we've already implicitly
2769    // instantiated.
2770    Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
2771                                       PointOfInstantiation);
2772    return;
2773  }
2774
2775  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2776  if (Inst)
2777    return;
2778
2779  // If we're performing recursive template instantiation, create our own
2780  // queue of pending implicit instantiations that we will instantiate later,
2781  // while we're still within our own instantiation context.
2782  SmallVector<VTableUse, 16> SavedVTableUses;
2783  std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2784  if (Recursive) {
2785    VTableUses.swap(SavedVTableUses);
2786    PendingInstantiations.swap(SavedPendingInstantiations);
2787  }
2788
2789  // Enter the scope of this instantiation. We don't use
2790  // PushDeclContext because we don't have a scope.
2791  ContextRAII previousContext(*this, Var->getDeclContext());
2792  LocalInstantiationScope Local(*this);
2793
2794  VarDecl *OldVar = Var;
2795  Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
2796                                        getTemplateInstantiationArgs(Var)));
2797
2798  previousContext.pop();
2799
2800  if (Var) {
2801    MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2802    assert(MSInfo && "Missing member specialization information?");
2803    Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2804                                       MSInfo->getPointOfInstantiation());
2805    DeclGroupRef DG(Var);
2806    Consumer.HandleTopLevelDecl(DG);
2807  }
2808  Local.Exit();
2809
2810  if (Recursive) {
2811    // Define any newly required vtables.
2812    DefineUsedVTables();
2813
2814    // Instantiate any pending implicit instantiations found during the
2815    // instantiation of this template.
2816    PerformPendingInstantiations();
2817
2818    // Restore the set of pending vtables.
2819    assert(VTableUses.empty() &&
2820           "VTableUses should be empty before it is discarded, "
2821           "while instantiating static data member.");
2822    VTableUses.swap(SavedVTableUses);
2823
2824    // Restore the set of pending implicit instantiations.
2825    assert(PendingInstantiations.empty() &&
2826           "PendingInstantiations should be empty before it is discarded, "
2827           "while instantiating static data member.");
2828    PendingInstantiations.swap(SavedPendingInstantiations);
2829  }
2830}
2831
2832void
2833Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2834                                 const CXXConstructorDecl *Tmpl,
2835                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2836
2837  SmallVector<CXXCtorInitializer*, 4> NewInits;
2838  bool AnyErrors = false;
2839
2840  // Instantiate all the initializers.
2841  for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
2842                                            InitsEnd = Tmpl->init_end();
2843       Inits != InitsEnd; ++Inits) {
2844    CXXCtorInitializer *Init = *Inits;
2845
2846    // Only instantiate written initializers, let Sema re-construct implicit
2847    // ones.
2848    if (!Init->isWritten())
2849      continue;
2850
2851    SourceLocation EllipsisLoc;
2852
2853    if (Init->isPackExpansion()) {
2854      // This is a pack expansion. We should expand it now.
2855      TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
2856      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2857      collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2858      bool ShouldExpand = false;
2859      bool RetainExpansion = false;
2860      llvm::Optional<unsigned> NumExpansions;
2861      if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2862                                          BaseTL.getSourceRange(),
2863                                          Unexpanded,
2864                                          TemplateArgs, ShouldExpand,
2865                                          RetainExpansion,
2866                                          NumExpansions)) {
2867        AnyErrors = true;
2868        New->setInvalidDecl();
2869        continue;
2870      }
2871      assert(ShouldExpand && "Partial instantiation of base initializer?");
2872
2873      // Loop over all of the arguments in the argument pack(s),
2874      for (unsigned I = 0; I != *NumExpansions; ++I) {
2875        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2876
2877        // Instantiate the initializer.
2878        ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
2879                                               /*CXXDirectInit=*/true);
2880        if (TempInit.isInvalid()) {
2881          AnyErrors = true;
2882          break;
2883        }
2884
2885        // Instantiate the base type.
2886        TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
2887                                              TemplateArgs,
2888                                              Init->getSourceLocation(),
2889                                              New->getDeclName());
2890        if (!BaseTInfo) {
2891          AnyErrors = true;
2892          break;
2893        }
2894
2895        // Build the initializer.
2896        MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2897                                                     BaseTInfo, TempInit.take(),
2898                                                     New->getParent(),
2899                                                     SourceLocation());
2900        if (NewInit.isInvalid()) {
2901          AnyErrors = true;
2902          break;
2903        }
2904
2905        NewInits.push_back(NewInit.get());
2906      }
2907
2908      continue;
2909    }
2910
2911    // Instantiate the initializer.
2912    ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
2913                                           /*CXXDirectInit=*/true);
2914    if (TempInit.isInvalid()) {
2915      AnyErrors = true;
2916      continue;
2917    }
2918
2919    MemInitResult NewInit;
2920    if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
2921      TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
2922                                        TemplateArgs,
2923                                        Init->getSourceLocation(),
2924                                        New->getDeclName());
2925      if (!TInfo) {
2926        AnyErrors = true;
2927        New->setInvalidDecl();
2928        continue;
2929      }
2930
2931      if (Init->isBaseInitializer())
2932        NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
2933                                       New->getParent(), EllipsisLoc);
2934      else
2935        NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
2936                                  cast<CXXRecordDecl>(CurContext->getParent()));
2937    } else if (Init->isMemberInitializer()) {
2938      FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
2939                                                     Init->getMemberLocation(),
2940                                                     Init->getMember(),
2941                                                     TemplateArgs));
2942      if (!Member) {
2943        AnyErrors = true;
2944        New->setInvalidDecl();
2945        continue;
2946      }
2947
2948      NewInit = BuildMemberInitializer(Member, TempInit.take(),
2949                                       Init->getSourceLocation());
2950    } else if (Init->isIndirectMemberInitializer()) {
2951      IndirectFieldDecl *IndirectMember =
2952         cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
2953                                 Init->getMemberLocation(),
2954                                 Init->getIndirectMember(), TemplateArgs));
2955
2956      if (!IndirectMember) {
2957        AnyErrors = true;
2958        New->setInvalidDecl();
2959        continue;
2960      }
2961
2962      NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
2963                                       Init->getSourceLocation());
2964    }
2965
2966    if (NewInit.isInvalid()) {
2967      AnyErrors = true;
2968      New->setInvalidDecl();
2969    } else {
2970      NewInits.push_back(NewInit.get());
2971    }
2972  }
2973
2974  // Assign all the initializers to the new constructor.
2975  ActOnMemInitializers(New,
2976                       /*FIXME: ColonLoc */
2977                       SourceLocation(),
2978                       NewInits.data(), NewInits.size(),
2979                       AnyErrors);
2980}
2981
2982ExprResult Sema::SubstInitializer(Expr *Init,
2983                          const MultiLevelTemplateArgumentList &TemplateArgs,
2984                          bool CXXDirectInit) {
2985  // Initializers are instantiated like expressions, except that various outer
2986  // layers are stripped.
2987  if (!Init)
2988    return Owned(Init);
2989
2990  if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
2991    Init = ExprTemp->getSubExpr();
2992
2993  while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
2994    Init = Binder->getSubExpr();
2995
2996  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
2997    Init = ICE->getSubExprAsWritten();
2998
2999  // If this is a direct-initializer, we take apart CXXConstructExprs.
3000  // Everything else is passed through.
3001  CXXConstructExpr *Construct;
3002  if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
3003      isa<CXXTemporaryObjectExpr>(Construct))
3004    return SubstExpr(Init, TemplateArgs);
3005
3006  ASTOwningVector<Expr*> NewArgs(*this);
3007  if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
3008                 TemplateArgs, NewArgs))
3009    return ExprError();
3010
3011  // Treat an empty initializer like none.
3012  if (NewArgs.empty())
3013    return Owned((Expr*)0);
3014
3015  // Build a ParenListExpr to represent anything else.
3016  // FIXME: Fake locations!
3017  SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
3018  return ActOnParenListExpr(Loc, Loc, move_arg(NewArgs));
3019}
3020
3021// TODO: this could be templated if the various decl types used the
3022// same method name.
3023static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3024                              ClassTemplateDecl *Instance) {
3025  Pattern = Pattern->getCanonicalDecl();
3026
3027  do {
3028    Instance = Instance->getCanonicalDecl();
3029    if (Pattern == Instance) return true;
3030    Instance = Instance->getInstantiatedFromMemberTemplate();
3031  } while (Instance);
3032
3033  return false;
3034}
3035
3036static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3037                              FunctionTemplateDecl *Instance) {
3038  Pattern = Pattern->getCanonicalDecl();
3039
3040  do {
3041    Instance = Instance->getCanonicalDecl();
3042    if (Pattern == Instance) return true;
3043    Instance = Instance->getInstantiatedFromMemberTemplate();
3044  } while (Instance);
3045
3046  return false;
3047}
3048
3049static bool
3050isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3051                  ClassTemplatePartialSpecializationDecl *Instance) {
3052  Pattern
3053    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3054  do {
3055    Instance = cast<ClassTemplatePartialSpecializationDecl>(
3056                                                Instance->getCanonicalDecl());
3057    if (Pattern == Instance)
3058      return true;
3059    Instance = Instance->getInstantiatedFromMember();
3060  } while (Instance);
3061
3062  return false;
3063}
3064
3065static bool isInstantiationOf(CXXRecordDecl *Pattern,
3066                              CXXRecordDecl *Instance) {
3067  Pattern = Pattern->getCanonicalDecl();
3068
3069  do {
3070    Instance = Instance->getCanonicalDecl();
3071    if (Pattern == Instance) return true;
3072    Instance = Instance->getInstantiatedFromMemberClass();
3073  } while (Instance);
3074
3075  return false;
3076}
3077
3078static bool isInstantiationOf(FunctionDecl *Pattern,
3079                              FunctionDecl *Instance) {
3080  Pattern = Pattern->getCanonicalDecl();
3081
3082  do {
3083    Instance = Instance->getCanonicalDecl();
3084    if (Pattern == Instance) return true;
3085    Instance = Instance->getInstantiatedFromMemberFunction();
3086  } while (Instance);
3087
3088  return false;
3089}
3090
3091static bool isInstantiationOf(EnumDecl *Pattern,
3092                              EnumDecl *Instance) {
3093  Pattern = Pattern->getCanonicalDecl();
3094
3095  do {
3096    Instance = Instance->getCanonicalDecl();
3097    if (Pattern == Instance) return true;
3098    Instance = Instance->getInstantiatedFromMemberEnum();
3099  } while (Instance);
3100
3101  return false;
3102}
3103
3104static bool isInstantiationOf(UsingShadowDecl *Pattern,
3105                              UsingShadowDecl *Instance,
3106                              ASTContext &C) {
3107  return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3108}
3109
3110static bool isInstantiationOf(UsingDecl *Pattern,
3111                              UsingDecl *Instance,
3112                              ASTContext &C) {
3113  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3114}
3115
3116static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3117                              UsingDecl *Instance,
3118                              ASTContext &C) {
3119  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3120}
3121
3122static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
3123                              UsingDecl *Instance,
3124                              ASTContext &C) {
3125  return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3126}
3127
3128static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3129                                              VarDecl *Instance) {
3130  assert(Instance->isStaticDataMember());
3131
3132  Pattern = Pattern->getCanonicalDecl();
3133
3134  do {
3135    Instance = Instance->getCanonicalDecl();
3136    if (Pattern == Instance) return true;
3137    Instance = Instance->getInstantiatedFromStaticDataMember();
3138  } while (Instance);
3139
3140  return false;
3141}
3142
3143// Other is the prospective instantiation
3144// D is the prospective pattern
3145static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
3146  if (D->getKind() != Other->getKind()) {
3147    if (UnresolvedUsingTypenameDecl *UUD
3148          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3149      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3150        return isInstantiationOf(UUD, UD, Ctx);
3151      }
3152    }
3153
3154    if (UnresolvedUsingValueDecl *UUD
3155          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3156      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3157        return isInstantiationOf(UUD, UD, Ctx);
3158      }
3159    }
3160
3161    return false;
3162  }
3163
3164  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3165    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
3166
3167  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3168    return isInstantiationOf(cast<FunctionDecl>(D), Function);
3169
3170  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3171    return isInstantiationOf(cast<EnumDecl>(D), Enum);
3172
3173  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
3174    if (Var->isStaticDataMember())
3175      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3176
3177  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3178    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
3179
3180  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3181    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3182
3183  if (ClassTemplatePartialSpecializationDecl *PartialSpec
3184        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3185    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3186                             PartialSpec);
3187
3188  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3189    if (!Field->getDeclName()) {
3190      // This is an unnamed field.
3191      return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
3192        cast<FieldDecl>(D);
3193    }
3194  }
3195
3196  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3197    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3198
3199  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3200    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3201
3202  return D->getDeclName() && isa<NamedDecl>(Other) &&
3203    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3204}
3205
3206template<typename ForwardIterator>
3207static NamedDecl *findInstantiationOf(ASTContext &Ctx,
3208                                      NamedDecl *D,
3209                                      ForwardIterator first,
3210                                      ForwardIterator last) {
3211  for (; first != last; ++first)
3212    if (isInstantiationOf(Ctx, D, *first))
3213      return cast<NamedDecl>(*first);
3214
3215  return 0;
3216}
3217
3218/// \brief Finds the instantiation of the given declaration context
3219/// within the current instantiation.
3220///
3221/// \returns NULL if there was an error
3222DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
3223                          const MultiLevelTemplateArgumentList &TemplateArgs) {
3224  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
3225    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
3226    return cast_or_null<DeclContext>(ID);
3227  } else return DC;
3228}
3229
3230/// \brief Find the instantiation of the given declaration within the
3231/// current instantiation.
3232///
3233/// This routine is intended to be used when \p D is a declaration
3234/// referenced from within a template, that needs to mapped into the
3235/// corresponding declaration within an instantiation. For example,
3236/// given:
3237///
3238/// \code
3239/// template<typename T>
3240/// struct X {
3241///   enum Kind {
3242///     KnownValue = sizeof(T)
3243///   };
3244///
3245///   bool getKind() const { return KnownValue; }
3246/// };
3247///
3248/// template struct X<int>;
3249/// \endcode
3250///
3251/// In the instantiation of X<int>::getKind(), we need to map the
3252/// EnumConstantDecl for KnownValue (which refers to
3253/// X<T>::\<Kind>\::KnownValue) to its instantiation
3254/// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
3255/// this mapping from within the instantiation of X<int>.
3256NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
3257                          const MultiLevelTemplateArgumentList &TemplateArgs) {
3258  DeclContext *ParentDC = D->getDeclContext();
3259  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
3260      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
3261      (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3262      (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
3263    // D is a local of some kind. Look into the map of local
3264    // declarations to their instantiations.
3265    typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3266    llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3267      = CurrentInstantiationScope->findInstantiationOf(D);
3268
3269    if (Found) {
3270      if (Decl *FD = Found->dyn_cast<Decl *>())
3271        return cast<NamedDecl>(FD);
3272
3273      unsigned PackIdx = ArgumentPackSubstitutionIndex;
3274      return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3275    }
3276
3277    // If we didn't find the decl, then we must have a label decl that hasn't
3278    // been found yet.  Lazily instantiate it and return it now.
3279    assert(isa<LabelDecl>(D));
3280
3281    Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3282    assert(Inst && "Failed to instantiate label??");
3283
3284    CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3285    return cast<LabelDecl>(Inst);
3286  }
3287
3288  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3289    if (!Record->isDependentContext())
3290      return D;
3291
3292    // Determine whether this record is the "templated" declaration describing
3293    // a class template or class template partial specialization.
3294    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3295    if (ClassTemplate)
3296      ClassTemplate = ClassTemplate->getCanonicalDecl();
3297    else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3298               = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3299      ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3300
3301    // Walk the current context to find either the record or an instantiation of
3302    // it.
3303    DeclContext *DC = CurContext;
3304    while (!DC->isFileContext()) {
3305      // If we're performing substitution while we're inside the template
3306      // definition, we'll find our own context. We're done.
3307      if (DC->Equals(Record))
3308        return Record;
3309
3310      if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3311        // Check whether we're in the process of instantiating a class template
3312        // specialization of the template we're mapping.
3313        if (ClassTemplateSpecializationDecl *InstSpec
3314                      = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3315          ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3316          if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3317            return InstRecord;
3318        }
3319
3320        // Check whether we're in the process of instantiating a member class.
3321        if (isInstantiationOf(Record, InstRecord))
3322          return InstRecord;
3323      }
3324
3325
3326      // Move to the outer template scope.
3327      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3328        if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3329          DC = FD->getLexicalDeclContext();
3330          continue;
3331        }
3332      }
3333
3334      DC = DC->getParent();
3335    }
3336
3337    // Fall through to deal with other dependent record types (e.g.,
3338    // anonymous unions in class templates).
3339  }
3340
3341  if (!ParentDC->isDependentContext())
3342    return D;
3343
3344  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
3345  if (!ParentDC)
3346    return 0;
3347
3348  if (ParentDC != D->getDeclContext()) {
3349    // We performed some kind of instantiation in the parent context,
3350    // so now we need to look into the instantiated parent context to
3351    // find the instantiation of the declaration D.
3352
3353    // If our context used to be dependent, we may need to instantiate
3354    // it before performing lookup into that context.
3355    bool IsBeingInstantiated = false;
3356    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
3357      if (!Spec->isDependentContext()) {
3358        QualType T = Context.getTypeDeclType(Spec);
3359        const RecordType *Tag = T->getAs<RecordType>();
3360        assert(Tag && "type of non-dependent record is not a RecordType");
3361        if (Tag->isBeingDefined())
3362          IsBeingInstantiated = true;
3363        if (!Tag->isBeingDefined() &&
3364            RequireCompleteType(Loc, T, diag::err_incomplete_type))
3365          return 0;
3366
3367        ParentDC = Tag->getDecl();
3368      }
3369    }
3370
3371    NamedDecl *Result = 0;
3372    if (D->getDeclName()) {
3373      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
3374      Result = findInstantiationOf(Context, D, Found.first, Found.second);
3375    } else {
3376      // Since we don't have a name for the entity we're looking for,
3377      // our only option is to walk through all of the declarations to
3378      // find that name. This will occur in a few cases:
3379      //
3380      //   - anonymous struct/union within a template
3381      //   - unnamed class/struct/union/enum within a template
3382      //
3383      // FIXME: Find a better way to find these instantiations!
3384      Result = findInstantiationOf(Context, D,
3385                                   ParentDC->decls_begin(),
3386                                   ParentDC->decls_end());
3387    }
3388
3389    if (!Result) {
3390      if (isa<UsingShadowDecl>(D)) {
3391        // UsingShadowDecls can instantiate to nothing because of using hiding.
3392      } else if (Diags.hasErrorOccurred()) {
3393        // We've already complained about something, so most likely this
3394        // declaration failed to instantiate. There's no point in complaining
3395        // further, since this is normal in invalid code.
3396      } else if (IsBeingInstantiated) {
3397        // The class in which this member exists is currently being
3398        // instantiated, and we haven't gotten around to instantiating this
3399        // member yet. This can happen when the code uses forward declarations
3400        // of member classes, and introduces ordering dependencies via
3401        // template instantiation.
3402        Diag(Loc, diag::err_member_not_yet_instantiated)
3403          << D->getDeclName()
3404          << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3405        Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3406      } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3407        // This enumeration constant was found when the template was defined,
3408        // but can't be found in the instantiation. This can happen if an
3409        // unscoped enumeration member is explicitly specialized.
3410        EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3411        EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3412                                                             TemplateArgs));
3413        assert(Spec->getTemplateSpecializationKind() ==
3414                 TSK_ExplicitSpecialization);
3415        Diag(Loc, diag::err_enumerator_does_not_exist)
3416          << D->getDeclName()
3417          << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3418        Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3419          << Context.getTypeDeclType(Spec);
3420      } else {
3421        // We should have found something, but didn't.
3422        llvm_unreachable("Unable to find instantiation of declaration!");
3423      }
3424    }
3425
3426    D = Result;
3427  }
3428
3429  return D;
3430}
3431
3432/// \brief Performs template instantiation for all implicit template
3433/// instantiations we have seen until this point.
3434void Sema::PerformPendingInstantiations(bool LocalOnly) {
3435  // Load pending instantiations from the external source.
3436  if (!LocalOnly && ExternalSource) {
3437    SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending;
3438    ExternalSource->ReadPendingInstantiations(Pending);
3439    PendingInstantiations.insert(PendingInstantiations.begin(),
3440                                 Pending.begin(), Pending.end());
3441  }
3442
3443  while (!PendingLocalImplicitInstantiations.empty() ||
3444         (!LocalOnly && !PendingInstantiations.empty())) {
3445    PendingImplicitInstantiation Inst;
3446
3447    if (PendingLocalImplicitInstantiations.empty()) {
3448      Inst = PendingInstantiations.front();
3449      PendingInstantiations.pop_front();
3450    } else {
3451      Inst = PendingLocalImplicitInstantiations.front();
3452      PendingLocalImplicitInstantiations.pop_front();
3453    }
3454
3455    // Instantiate function definitions
3456    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
3457      PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3458                                          "instantiating function definition");
3459      bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3460                                TSK_ExplicitInstantiationDefinition;
3461      InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3462                                    DefinitionRequired);
3463      continue;
3464    }
3465
3466    // Instantiate static data member definitions.
3467    VarDecl *Var = cast<VarDecl>(Inst.first);
3468    assert(Var->isStaticDataMember() && "Not a static data member?");
3469
3470    // Don't try to instantiate declarations if the most recent redeclaration
3471    // is invalid.
3472    if (Var->getMostRecentDecl()->isInvalidDecl())
3473      continue;
3474
3475    // Check if the most recent declaration has changed the specialization kind
3476    // and removed the need for implicit instantiation.
3477    switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
3478    case TSK_Undeclared:
3479      llvm_unreachable("Cannot instantitiate an undeclared specialization.");
3480    case TSK_ExplicitInstantiationDeclaration:
3481    case TSK_ExplicitSpecialization:
3482      continue;  // No longer need to instantiate this type.
3483    case TSK_ExplicitInstantiationDefinition:
3484      // We only need an instantiation if the pending instantiation *is* the
3485      // explicit instantiation.
3486      if (Var != Var->getMostRecentDecl()) continue;
3487    case TSK_ImplicitInstantiation:
3488      break;
3489    }
3490
3491    PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3492                                        "instantiating static data member "
3493                                        "definition");
3494
3495    bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3496                              TSK_ExplicitInstantiationDefinition;
3497    InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3498                                          DefinitionRequired);
3499  }
3500}
3501
3502void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3503                       const MultiLevelTemplateArgumentList &TemplateArgs) {
3504  for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3505         E = Pattern->ddiag_end(); I != E; ++I) {
3506    DependentDiagnostic *DD = *I;
3507
3508    switch (DD->getKind()) {
3509    case DependentDiagnostic::Access:
3510      HandleDependentAccessCheck(*DD, TemplateArgs);
3511      break;
3512    }
3513  }
3514}
3515