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