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