18dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
28dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//
38dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//                     The LLVM Compiler Infrastructure
48dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//
58dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor// This file is distributed under the University of Illinois Open Source
68dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor// License. See LICENSE.TXT for details.
78dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//===----------------------------------------------------------------------===/
88dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//
98dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//  This file implements C++ template instantiation for declarations.
108dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//
118dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor//===----------------------------------------------------------------------===/
122d88708cbe4e4ec5e04e4acb6bd7f5be68557379John McCall#include "clang/Sema/SemaInternal.h"
13aba43bb13b3aa3e81990989375fba3a902bfe1c2Douglas Gregor#include "clang/AST/ASTConsumer.h"
148dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor#include "clang/AST/ASTContext.h"
15651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines#include "clang/AST/ASTMutationListener.h"
168dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor#include "clang/AST/DeclTemplate.h"
178dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor#include "clang/AST/DeclVisitor.h"
180c01d18094100db92d38daa923c95661512db203John McCall#include "clang/AST/DependentDiagnostic.h"
198dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor#include "clang/AST/Expr.h"
20a88cfbfac9bbcbb9858f048d6d73a48711d8e93dDouglas Gregor#include "clang/AST/ExprCXX.h"
2121ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCall#include "clang/AST/TypeLoc.h"
2255fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Sema/Lookup.h"
2355fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Sema/PrettyDeclStackTrace.h"
2455fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "clang/Sema/Template.h"
258dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
268dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregorusing namespace clang;
278dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
2857907e56191adea0fa870c052054eb0fe0c4681fBill Wendlingstatic bool isDeclWithinFunction(const Decl *D) {
2957907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  const DeclContext *DC = D->getDeclContext();
3057907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  if (DC->isFunctionOrMethod())
3157907e56191adea0fa870c052054eb0fe0c4681fBill Wendling    return true;
3257907e56191adea0fa870c052054eb0fe0c4681fBill Wendling
3357907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  if (DC->isRecord())
3457907e56191adea0fa870c052054eb0fe0c4681fBill Wendling    return cast<CXXRecordDecl>(DC)->isLocalClass();
3557907e56191adea0fa870c052054eb0fe0c4681fBill Wendling
3657907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  return false;
3757907e56191adea0fa870c052054eb0fe0c4681fBill Wendling}
3857907e56191adea0fa870c052054eb0fe0c4681fBill Wendling
39176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hinestemplate<typename DeclT>
40176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hinesstatic bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
41176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                           const MultiLevelTemplateArgumentList &TemplateArgs) {
42c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  if (!OldDecl->getQualifierLoc())
43c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    return false;
44a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
45176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  assert((NewDecl->getFriendObjectKind() ||
46176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
47176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines         "non-friend with qualified name defined in dependent context");
48176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  Sema::ContextRAII SavedContext(
49176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      SemaRef,
50176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
51176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                    ? NewDecl->getLexicalDeclContext()
52176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                    : OldDecl->getLexicalDeclContext()));
53176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
54c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  NestedNameSpecifierLoc NewQualifierLoc
55176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
56176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                            TemplateArgs);
57a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
58c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  if (!NewQualifierLoc)
59b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall    return true;
60a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
61c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  NewDecl->setQualifierInfo(NewQualifierLoc);
62b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall  return false;
63b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall}
64b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
65176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hinesbool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
66176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                              DeclaratorDecl *NewDecl) {
67176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
68176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines}
69176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
70b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCallbool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
71b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall                                              TagDecl *NewDecl) {
72176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
73b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall}
74b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
757b9ff0c09025dcbe48ec7db71330e2066d1e1863DeLesley Hutchins// Include attribute instantiation code.
767b9ff0c09025dcbe48ec7db71330e2066d1e1863DeLesley Hutchins#include "clang/Sema/AttrTemplateInstantiate.inc"
777b9ff0c09025dcbe48ec7db71330e2066d1e1863DeLesley Hutchins
78f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smithstatic void instantiateDependentAlignedAttr(
79f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
80f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
81f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  if (Aligned->isAlignmentExpr()) {
82f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    // The alignment expression is a constant expression.
83f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
84f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
85f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    if (!Result.isInvalid())
86c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
87f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith                       Aligned->getSpellingListIndex(), IsPackExpansion);
88f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  } else {
89f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
90f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith                                         TemplateArgs, Aligned->getLocation(),
91f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith                                         DeclarationName());
92f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    if (Result)
93f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith      S.AddAlignedAttr(Aligned->getLocation(), New, Result,
94f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith                       Aligned->getSpellingListIndex(), IsPackExpansion);
95f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  }
96f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith}
97f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith
98f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smithstatic void instantiateDependentAlignedAttr(
99f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
100f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    const AlignedAttr *Aligned, Decl *New) {
101f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  if (!Aligned->isPackExpansion()) {
102f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
103f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    return;
104f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  }
105f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith
106f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
107f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  if (Aligned->isAlignmentExpr())
108f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
109f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith                                      Unexpanded);
110f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  else
111f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
112f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith                                      Unexpanded);
113f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
114f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith
115f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  // Determine whether we can expand this attribute pack yet.
116f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  bool Expand = true, RetainExpansion = false;
117f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  Optional<unsigned> NumExpansions;
118f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  // FIXME: Use the actual location of the ellipsis.
119f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  SourceLocation EllipsisLoc = Aligned->getLocation();
120f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
121f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith                                        Unexpanded, TemplateArgs, Expand,
122f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith                                        RetainExpansion, NumExpansions))
123f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    return;
124f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith
125f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  if (!Expand) {
126f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
127f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
128f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  } else {
129f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    for (unsigned I = 0; I != *NumExpansions; ++I) {
130f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
131f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith      instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
132f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    }
133f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith  }
134f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith}
135f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith
136176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hinesstatic void instantiateDependentAssumeAlignedAttr(
137176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
138176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    const AssumeAlignedAttr *Aligned, Decl *New) {
139176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // The alignment expression is a constant expression.
140176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
141176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
142176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  Expr *E, *OE = nullptr;
143176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
144176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (Result.isInvalid())
145176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    return;
146176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  E = Result.getAs<Expr>();
147176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
148176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (Aligned->getOffset()) {
149176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
150176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    if (Result.isInvalid())
151176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      return;
152176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    OE = Result.getAs<Expr>();
153176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  }
154176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
155176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
156176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                         Aligned->getSpellingListIndex());
157176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines}
158176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
159176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hinesstatic void instantiateDependentAlignValueAttr(
160176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
161176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    const AlignValueAttr *Aligned, Decl *New) {
162176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // The alignment expression is a constant expression.
163176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
164176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
165176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (!Result.isInvalid())
166176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
167176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                        Aligned->getSpellingListIndex());
168176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines}
169176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
170651f13cea278ec967336033dd032faef0e9fc2ecStephen Hinesstatic void instantiateDependentEnableIfAttr(
171651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
172651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
1736bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  Expr *Cond = nullptr;
174651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  {
175651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
176651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
177651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    if (Result.isInvalid())
178651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      return;
179c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    Cond = Result.getAs<Expr>();
180651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  }
181651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
182651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
183651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    if (Converted.isInvalid())
184651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      return;
185c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    Cond = Converted.get();
186651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  }
187651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
188651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  SmallVector<PartialDiagnosticAt, 8> Diags;
189651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
190651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
191651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                                Diags)) {
192651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
193651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    for (int I = 0, N = Diags.size(); I != N; ++I)
194651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      S.Diag(Diags[I].first, Diags[I].second);
195651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    return;
196651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  }
197651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
198651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  EnableIfAttr *EIA = new (S.getASTContext())
199651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                        EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
200651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                     A->getMessage(),
201651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                     A->getSpellingListIndex());
202651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  New->addAttr(EIA);
203651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines}
204651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
205b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
206b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar// template A as the base and arguments from TemplateArgs.
207b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainarstatic void instantiateDependentCUDALaunchBoundsAttr(
208b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
209b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    const CUDALaunchBoundsAttr &Attr, Decl *New) {
210b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  // The alignment expression is a constant expression.
211b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
212b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
213b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
214b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  if (Result.isInvalid())
215b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    return;
216b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  Expr *MaxThreads = Result.getAs<Expr>();
217b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
218b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  Expr *MinBlocks = nullptr;
219b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  if (Attr.getMinBlocks()) {
220b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
221b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    if (Result.isInvalid())
222b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      return;
223b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    MinBlocks = Result.getAs<Expr>();
224b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  }
225b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
226b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar  S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
227b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar                        Attr.getSpellingListIndex());
228b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar}
229b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
2304967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainarstatic void
2314967a710c84587c654b56c828382219c3937dacbPirama Arumuga NainarinstantiateDependentModeAttr(Sema &S,
2324967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                             const MultiLevelTemplateArgumentList &TemplateArgs,
2334967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                             const ModeAttr &Attr, Decl *New) {
2344967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
2354967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                Attr.getSpellingListIndex(), /*InInstantiation=*/true);
2364967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar}
2374967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
2384967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar/// Instantiation of 'declare simd' attribute and its arguments.
2394967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainarstatic void instantiateOMPDeclareSimdDeclAttr(
2404967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
2414967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
2424967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // Allow 'this' in clauses with varlists.
2434967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
2444967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    New = FTD->getTemplatedDecl();
2454967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  auto *FD = cast<FunctionDecl>(New);
2464967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
2474967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
2484967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  SmallVector<unsigned, 4> LinModifiers;
2494967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
2504967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  auto &&Subst = [&](Expr *E) -> ExprResult {
2514967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2524967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2534967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        Sema::ContextRAII SavedContext(S, FD);
2544967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        LocalInstantiationScope Local(S);
2554967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        if (FD->getNumParams() > PVD->getFunctionScopeIndex())
2564967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          Local.InstantiatedLocal(
2574967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar              PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
2584967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        return S.SubstExpr(E, TemplateArgs);
2594967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      }
2604967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Sema::CXXThisScopeRAII ThisScope(S, ThisContext, /*TypeQuals=*/0,
2614967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                     FD->isCXXInstanceMember());
2624967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    return S.SubstExpr(E, TemplateArgs);
2634967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  };
2644967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
2654967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  ExprResult Simdlen;
2664967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (auto *E = Attr.getSimdlen())
2674967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Simdlen = Subst(E);
2684967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
2694967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (Attr.uniforms_size() > 0) {
2704967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    for(auto *E : Attr.uniforms()) {
2714967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      ExprResult Inst = Subst(E);
2724967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      if (Inst.isInvalid())
2734967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        continue;
2744967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      Uniforms.push_back(Inst.get());
2754967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    }
2764967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  }
2774967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
2784967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  auto AI = Attr.alignments_begin();
2794967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  for (auto *E : Attr.aligneds()) {
2804967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    ExprResult Inst = Subst(E);
2814967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (Inst.isInvalid())
2824967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      continue;
2834967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Aligneds.push_back(Inst.get());
2844967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Inst = ExprEmpty();
2854967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (*AI)
2864967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      Inst = S.SubstExpr(*AI, TemplateArgs);
2874967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Alignments.push_back(Inst.get());
2884967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    ++AI;
2894967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  }
2904967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
2914967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  auto SI = Attr.steps_begin();
2924967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  for (auto *E : Attr.linears()) {
2934967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    ExprResult Inst = Subst(E);
2944967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (Inst.isInvalid())
2954967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      continue;
2964967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Linears.push_back(Inst.get());
2974967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Inst = ExprEmpty();
2984967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (*SI)
2994967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      Inst = S.SubstExpr(*SI, TemplateArgs);
3004967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Steps.push_back(Inst.get());
3014967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    ++SI;
3024967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  }
3034967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
3044967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  (void)S.ActOnOpenMPDeclareSimdDirective(
3054967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
3064967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
3074967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      Attr.getRange());
3084967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar}
3094967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
3101d8d1ccd36888f1120b3a1df9e76f35dc2edb81dJohn McCallvoid Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
31123323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins                            const Decl *Tmpl, Decl *New,
31223323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins                            LateInstantiatedAttrVec *LateAttrs,
31323323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins                            LocalInstantiationScope *OuterMostScope) {
314651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  for (const auto *TmplAttr : Tmpl->attrs()) {
3154ced79f0971592e6e7122037de69ee9ae534ce72Chandler Carruth    // FIXME: This should be generalized to more than just the AlignedAttr.
316f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
317f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    if (Aligned && Aligned->isAlignmentDependent()) {
318f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith      instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
319f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith      continue;
3204ced79f0971592e6e7122037de69ee9ae534ce72Chandler Carruth    }
3214ced79f0971592e6e7122037de69ee9ae534ce72Chandler Carruth
322176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
323176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    if (AssumeAligned) {
324176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
325176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      continue;
326176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    }
327176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
328176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
329176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    if (AlignValue) {
330176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
331176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      continue;
332176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    }
333176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
334651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
335651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    if (EnableIf && EnableIf->getCond()->isValueDependent()) {
336651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
337651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                       New);
338651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      continue;
339651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    }
340651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
341b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
342b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar            dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
343b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
344b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar                                               *CUDALaunchBounds, New);
345b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      continue;
346b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    }
347b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
3484967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
3494967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
3504967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      continue;
3514967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    }
3524967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
3534967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
3544967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
3554967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      continue;
3564967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    }
3574967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
358176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    // Existing DLL attribute on the instantiation takes precedence.
359176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    if (TmplAttr->getKind() == attr::DLLExport ||
360176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        TmplAttr->getKind() == attr::DLLImport) {
361176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
362176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        continue;
363176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      }
364176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    }
365176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
3664967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
3674967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(),
3684967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                          ABIAttr->getSpellingListIndex());
3694967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      continue;
3704967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    }
3714967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
3724967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (isa<NSConsumedAttr>(TmplAttr) || isa<CFConsumedAttr>(TmplAttr)) {
3734967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      AddNSConsumedAttr(TmplAttr->getRange(), New,
3744967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                        TmplAttr->getSpellingListIndex(),
3754967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                        isa<NSConsumedAttr>(TmplAttr),
3764967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                        /*template instantiation*/ true);
3774967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      continue;
3784967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    }
3794967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
380f6565a9f7318b1ca6ea9510003dde7b89696daabRichard Smith    assert(!TmplAttr->isPackExpansion());
38123323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins    if (TmplAttr->isLateParsed() && LateAttrs) {
38223323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins      // Late parsed attributes must be instantiated and attached after the
38323323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins      // enclosing class has been instantiated.  See Sema::InstantiateClass.
3846bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      LocalInstantiationScope *Saved = nullptr;
38523323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins      if (CurrentInstantiationScope)
38623323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins        Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
38723323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
38823323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins    } else {
389cafeb948e6067b8dc897c441da522367917b06f9Richard Smith      // Allow 'this' within late-parsed attributes.
390cafeb948e6067b8dc897c441da522367917b06f9Richard Smith      NamedDecl *ND = dyn_cast<NamedDecl>(New);
391cafeb948e6067b8dc897c441da522367917b06f9Richard Smith      CXXRecordDecl *ThisContext =
392cafeb948e6067b8dc897c441da522367917b06f9Richard Smith          dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
393cafeb948e6067b8dc897c441da522367917b06f9Richard Smith      CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
394cafeb948e6067b8dc897c441da522367917b06f9Richard Smith                                 ND && ND->isCXXInstanceMember());
395cafeb948e6067b8dc897c441da522367917b06f9Richard Smith
3965bbc385ad2d8e487edfbc2756eaf4fb0b920cfe4Benjamin Kramer      Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
3975bbc385ad2d8e487edfbc2756eaf4fb0b920cfe4Benjamin Kramer                                                         *this, TemplateArgs);
39831c195ac0f3869e742d42f9d02b6cd33442fb630Rafael Espindola      if (NewAttr)
39931c195ac0f3869e742d42f9d02b6cd33442fb630Rafael Espindola        New->addAttr(NewAttr);
40023323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins    }
401d8fe2d56fb5463c9d109e8c6dab2e98b06bee186Anders Carlsson  }
402d8fe2d56fb5463c9d109e8c6dab2e98b06bee186Anders Carlsson}
403d8fe2d56fb5463c9d109e8c6dab2e98b06bee186Anders Carlsson
404176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines/// Get the previous declaration of a declaration for the purposes of template
405176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines/// instantiation. If this finds a previous declaration, then the previous
406176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines/// declaration of the instantiation of D should be an instantiation of the
407176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines/// result of this function.
408176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hinestemplate<typename DeclT>
409176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hinesstatic DeclT *getPreviousDeclForInstantiation(DeclT *D) {
410176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  DeclT *Result = D->getPreviousDecl();
411176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
412176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // If the declaration is within a class, and the previous declaration was
413176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // merged from a different definition of that class, then we don't have a
414176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // previous declaration for the purpose of template instantiation.
415176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
416176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      D->getLexicalDeclContext() != Result->getLexicalDeclContext())
417176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    return nullptr;
418176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
419176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  return Result;
420176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines}
421176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
4224f722be4587a7a0dece399fb5405dda158971ae1Douglas GregorDecl *
4234f722be4587a7a0dece399fb5405dda158971ae1Douglas GregorTemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
424b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie  llvm_unreachable("Translation units cannot be instantiated");
4254f722be4587a7a0dece399fb5405dda158971ae1Douglas Gregor}
4264f722be4587a7a0dece399fb5405dda158971ae1Douglas Gregor
4274f722be4587a7a0dece399fb5405dda158971ae1Douglas GregorDecl *
4284967a710c84587c654b56c828382219c3937dacbPirama Arumuga NainarTemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
4294967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  llvm_unreachable("pragma comment cannot be instantiated");
4304967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar}
4314967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
4324967a710c84587c654b56c828382219c3937dacbPirama Arumuga NainarDecl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
4334967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    PragmaDetectMismatchDecl *D) {
4344967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  llvm_unreachable("pragma comment cannot be instantiated");
4354967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar}
4364967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
4374967a710c84587c654b56c828382219c3937dacbPirama Arumuga NainarDecl *
4383ea9e33ea25e0c2b12db56418ba3f994eb662c04Pirama Arumuga NainarTemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
4393ea9e33ea25e0c2b12db56418ba3f994eb662c04Pirama Arumuga Nainar  llvm_unreachable("extern \"C\" context cannot be instantiated");
4403ea9e33ea25e0c2b12db56418ba3f994eb662c04Pirama Arumuga Nainar}
4413ea9e33ea25e0c2b12db56418ba3f994eb662c04Pirama Arumuga Nainar
4423ea9e33ea25e0c2b12db56418ba3f994eb662c04Pirama Arumuga NainarDecl *
44357ad37823e198f977cac605dbfbaefb4daf325e9Chris LattnerTemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
44457ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
44557ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner                                      D->getIdentifier());
44657ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner  Owner->addDecl(Inst);
44757ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner  return Inst;
44857ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner}
44957ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner
45057ad37823e198f977cac605dbfbaefb4daf325e9Chris LattnerDecl *
4514f722be4587a7a0dece399fb5405dda158971ae1Douglas GregorTemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
452b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie  llvm_unreachable("Namespaces cannot be instantiated");
4534f722be4587a7a0dece399fb5405dda158971ae1Douglas Gregor}
4544f722be4587a7a0dece399fb5405dda158971ae1Douglas Gregor
4553dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCallDecl *
4563dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCallTemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
4573dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall  NamespaceAliasDecl *Inst
4583dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
4593dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall                                 D->getNamespaceLoc(),
4603dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall                                 D->getAliasLoc(),
4610cfaf6a270ecd0f5c7e541a8047c87948317548bDouglas Gregor                                 D->getIdentifier(),
4620cfaf6a270ecd0f5c7e541a8047c87948317548bDouglas Gregor                                 D->getQualifierLoc(),
4633dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall                                 D->getTargetNameLoc(),
4643dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall                                 D->getNamespace());
4653dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall  Owner->addDecl(Inst);
4663dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall  return Inst;
4673dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall}
4683dbd3d5c04cd5abd7dfd83b15f51d7c610a3c512John McCall
4693e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard SmithDecl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
4703e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith                                                           bool IsTypeAlias) {
4718dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  bool Invalid = false;
472a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall  TypeSourceInfo *DI = D->getTypeSourceInfo();
473561f81243f665cf2001caadc45df505f826b72d6Douglas Gregor  if (DI->getType()->isInstantiationDependentType() ||
474836adf6771d5170d936599dfcce21687e37e9bbfDouglas Gregor      DI->getType()->isVariablyModifiedType()) {
475ba6a9bd384df475780be636ca45bcef5c5bbd19fJohn McCall    DI = SemaRef.SubstType(DI, TemplateArgs,
476ba6a9bd384df475780be636ca45bcef5c5bbd19fJohn McCall                           D->getLocation(), D->getDeclName());
477ba6a9bd384df475780be636ca45bcef5c5bbd19fJohn McCall    if (!DI) {
4788dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      Invalid = true;
479a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
4808dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    }
481b4eeaff1595b7d0a8fbc2b3c8bec7dc63f48b7fdDouglas Gregor  } else {
482b4eeaff1595b7d0a8fbc2b3c8bec7dc63f48b7fdDouglas Gregor    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
4838dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  }
4841eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
485b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith  // HACK: g++ has a bug where it gets the value kind of ?: wrong.
486b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith  // libstdc++ relies upon this bug in its implementation of common_type.
487b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith  // If we happen to be processing that implementation, fake up the g++ ?:
488b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith  // semantics. See LWG issue 2141 for more information on the bug.
489b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
490b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
491b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith  if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
492b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith      DT->isReferenceType() &&
493b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith      RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
494b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith      RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
495b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith      D->getIdentifier() && D->getIdentifier()->isStr("type") &&
496b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith      SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
497b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith    // Fold it to the (non-reference) type which g++ would have produced.
498b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith    DI = SemaRef.Context.getTrivialTypeSourceInfo(
499b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith      DI->getType().getNonReferenceType());
500b5b37d194dddb960f43f763b3f9c3e17e7be3c2dRichard Smith
5018dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  // Create the new typedef
502162e1c1b487352434552147967c3dd296ebee2f7Richard Smith  TypedefNameDecl *Typedef;
503162e1c1b487352434552147967c3dd296ebee2f7Richard Smith  if (IsTypeAlias)
504162e1c1b487352434552147967c3dd296ebee2f7Richard Smith    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
505162e1c1b487352434552147967c3dd296ebee2f7Richard Smith                                    D->getLocation(), D->getIdentifier(), DI);
506162e1c1b487352434552147967c3dd296ebee2f7Richard Smith  else
507162e1c1b487352434552147967c3dd296ebee2f7Richard Smith    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
508162e1c1b487352434552147967c3dd296ebee2f7Richard Smith                                  D->getLocation(), D->getIdentifier(), DI);
5098dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  if (Invalid)
5108dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    Typedef->setInvalidDecl();
5118dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
512cde5a400dbc9655eddf0f383585d3cf67c11c539John McCall  // If the old typedef was the name for linkage purposes of an anonymous
513cde5a400dbc9655eddf0f383585d3cf67c11c539John McCall  // tag decl, re-establish that relationship for the new typedef.
514cde5a400dbc9655eddf0f383585d3cf67c11c539John McCall  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
515cde5a400dbc9655eddf0f383585d3cf67c11c539John McCall    TagDecl *oldTag = oldTagType->getDecl();
516c61361b102fcb9be7b64cc493fb797ea551eb8e7Douglas Gregor    if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
517cde5a400dbc9655eddf0f383585d3cf67c11c539John McCall      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
51883972f128e9218c051692bf96361327a701aeb79John McCall      assert(!newTag->hasNameForLinkage());
519162e1c1b487352434552147967c3dd296ebee2f7Richard Smith      newTag->setTypedefNameForAnonDecl(Typedef);
520cde5a400dbc9655eddf0f383585d3cf67c11c539John McCall    }
521d57a38ee02c285d69d05fed6df0d7406b2517888Douglas Gregor  }
522a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
523176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
5247c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
5257c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor                                                       TemplateArgs);
526b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor    if (!InstPrev)
5276bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
528a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
5295df37bd0242e838e465f0bd51a70af424d152053Rafael Espindola    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
5305df37bd0242e838e465f0bd51a70af424d152053Rafael Espindola
5315df37bd0242e838e465f0bd51a70af424d152053Rafael Espindola    // If the typedef types are not identical, reject them.
5325df37bd0242e838e465f0bd51a70af424d152053Rafael Espindola    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
5335df37bd0242e838e465f0bd51a70af424d152053Rafael Espindola
534bc6509175e1ce5cc1b48d1b97ac8d23d8b74167cRafael Espindola    Typedef->setPreviousDecl(InstPrevTypedef);
5355126fd0dd92c4ec211c837ee78d5ce59c68dcbd5John McCall  }
5365126fd0dd92c4ec211c837ee78d5ce59c68dcbd5John McCall
5371d8d1ccd36888f1120b3a1df9e76f35dc2edb81dJohn McCall  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
538d57a38ee02c285d69d05fed6df0d7406b2517888Douglas Gregor
53946460a68f6508775e98c19b4bb8454bb471aac24John McCall  Typedef->setAccess(D->getAccess());
5401eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
5418dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  return Typedef;
5428dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor}
5438dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
544162e1c1b487352434552147967c3dd296ebee2f7Richard SmithDecl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
5453e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
546176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (Typedef)
547176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    Owner->addDecl(Typedef);
5483e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  return Typedef;
549162e1c1b487352434552147967c3dd296ebee2f7Richard Smith}
550162e1c1b487352434552147967c3dd296ebee2f7Richard Smith
551162e1c1b487352434552147967c3dd296ebee2f7Richard SmithDecl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
5523e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
553176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (Typedef)
554176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    Owner->addDecl(Typedef);
5553e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  return Typedef;
5563e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith}
5573e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5583e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard SmithDecl *
5593e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard SmithTemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
5603e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  // Create a local instantiation scope for this type alias template, which
5613e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  // will contain the instantiations of the template parameters.
5623e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  LocalInstantiationScope Scope(SemaRef);
5633e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5643e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  TemplateParameterList *TempParams = D->getTemplateParameters();
5653e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
5663e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  if (!InstParams)
5676bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
5683e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5693e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  TypeAliasDecl *Pattern = D->getTemplatedDecl();
5703e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5716bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
572176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
5733e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
5743bc93e3124ad5e7191c4a12dc981c8ee53578193David Blaikie    if (!Found.empty()) {
5753bc93e3124ad5e7191c4a12dc981c8ee53578193David Blaikie      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
5763e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith    }
5773e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  }
5783e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5793e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
5803e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
5813e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  if (!AliasInst)
5826bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
5833e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5843e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  TypeAliasTemplateDecl *Inst
5853e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
5863e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith                                    D->getDeclName(), InstParams, AliasInst);
587176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  AliasInst->setDescribedAliasTemplate(Inst);
5883e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  if (PrevAliasTemplate)
589bc6509175e1ce5cc1b48d1b97ac8d23d8b74167cRafael Espindola    Inst->setPreviousDecl(PrevAliasTemplate);
5903e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5913e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  Inst->setAccess(D->getAccess());
5923e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5933e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  if (!PrevAliasTemplate)
5943e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith    Inst->setInstantiatedFromMemberTemplate(D);
595a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
5963e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  Owner->addDecl(Inst);
5973e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith
5983e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  return Inst;
599162e1c1b487352434552147967c3dd296ebee2f7Richard Smith}
600162e1c1b487352434552147967c3dd296ebee2f7Richard Smith
6013d7a12a50558c31d4351e923c15ab57688f4fdf2Douglas GregorDecl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
602567f917df048d42732997a479b2b257403fc88efLarisse Voufo  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
603ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
604ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
605567f917df048d42732997a479b2b257403fc88efLarisse VoufoDecl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
606567f917df048d42732997a479b2b257403fc88efLarisse Voufo                                             bool InstantiatingVarTemplate) {
607ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
608ce3ff2bd3a3386dbc209d3cba4b8769173b274c1John McCall  // Do substitution on the type of the declaration
609a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall  TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
6100a5fa06a688e1086ea553a24b42b9915996ed1f7John McCall                                         TemplateArgs,
6110a5fa06a688e1086ea553a24b42b9915996ed1f7John McCall                                         D->getTypeSpecStartLoc(),
6120a5fa06a688e1086ea553a24b42b9915996ed1f7John McCall                                         D->getDeclName());
6130a5fa06a688e1086ea553a24b42b9915996ed1f7John McCall  if (!DI)
6146bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
6153d7a12a50558c31d4351e923c15ab57688f4fdf2Douglas Gregor
616c6dbc3fa467e2355b678a6b717534928048efcb2Douglas Gregor  if (DI->getType()->isFunctionType()) {
617c6dbc3fa467e2355b678a6b717534928048efcb2Douglas Gregor    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
618c6dbc3fa467e2355b678a6b717534928048efcb2Douglas Gregor      << D->isStaticDataMember() << DI->getType();
6196bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
620c6dbc3fa467e2355b678a6b717534928048efcb2Douglas Gregor  }
621a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
622a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  DeclContext *DC = Owner;
623a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  if (D->isLocalExternDecl())
624a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    SemaRef.adjustContextForLocalExternDecl(DC);
625a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith
626ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Build the instantiated declaration.
627a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
6283d7a12a50558c31d4351e923c15ab57688f4fdf2Douglas Gregor                                 D->getLocation(), D->getIdentifier(),
629ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                                 DI->getType(), DI, D->getStorageClass());
6301eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
6319aab9c4116bb3ea876d92d4af10bff7f4c451f24Douglas Gregor  // In ARC, infer 'retaining' for variables of retainable type.
6324e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
6339aab9c4116bb3ea876d92d4af10bff7f4c451f24Douglas Gregor      SemaRef.inferObjCARCLifetime(Var))
6349aab9c4116bb3ea876d92d4af10bff7f4c451f24Douglas Gregor    Var->setInvalidDecl();
6359aab9c4116bb3ea876d92d4af10bff7f4c451f24Douglas Gregor
636ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Substitute the nested name specifier, if any.
637ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (SubstQualifier(D, Var))
6386bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
639bbc6454bb98d6a6ecbaafa715222c5db834307f2Argyrios Kyrtzidis
640a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
641567f917df048d42732997a479b2b257403fc88efLarisse Voufo                                     StartingScope, InstantiatingVarTemplate);
6426bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines
6436bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  if (D->isNRVOVariable()) {
6446bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
6456bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
6466bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      Var->setNRVOVariable(true);
6476bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  }
6486bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines
6496bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  Var->setImplicit(D->isImplicit());
6506bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines
6513d7a12a50558c31d4351e923c15ab57688f4fdf2Douglas Gregor  return Var;
6523d7a12a50558c31d4351e923c15ab57688f4fdf2Douglas Gregor}
6533d7a12a50558c31d4351e923c15ab57688f4fdf2Douglas Gregor
6546206d53f67613958ae1b023aba337ebb46f11a8bAbramo BagnaraDecl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
6556206d53f67613958ae1b023aba337ebb46f11a8bAbramo Bagnara  AccessSpecDecl* AD
6566206d53f67613958ae1b023aba337ebb46f11a8bAbramo Bagnara    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
6576206d53f67613958ae1b023aba337ebb46f11a8bAbramo Bagnara                             D->getAccessSpecifierLoc(), D->getColonLoc());
6586206d53f67613958ae1b023aba337ebb46f11a8bAbramo Bagnara  Owner->addHiddenDecl(AD);
6596206d53f67613958ae1b023aba337ebb46f11a8bAbramo Bagnara  return AD;
6606206d53f67613958ae1b023aba337ebb46f11a8bAbramo Bagnara}
6616206d53f67613958ae1b023aba337ebb46f11a8bAbramo Bagnara
6628dbc2694424b4e842b1d5ea39744a137b58600c3Douglas GregorDecl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
6638dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  bool Invalid = false;
664a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall  TypeSourceInfo *DI = D->getTypeSourceInfo();
665561f81243f665cf2001caadc45df505f826b72d6Douglas Gregor  if (DI->getType()->isInstantiationDependentType() ||
666836adf6771d5170d936599dfcce21687e37e9bbfDouglas Gregor      DI->getType()->isVariablyModifiedType())  {
66707fb6bef6242c0f2ab47f059583edbdef924823eJohn McCall    DI = SemaRef.SubstType(DI, TemplateArgs,
66807fb6bef6242c0f2ab47f059583edbdef924823eJohn McCall                           D->getLocation(), D->getDeclName());
66907fb6bef6242c0f2ab47f059583edbdef924823eJohn McCall    if (!DI) {
670a93c934af4fbf97cbe8e649d82e68ccacfe57c95John McCall      DI = D->getTypeSourceInfo();
67107fb6bef6242c0f2ab47f059583edbdef924823eJohn McCall      Invalid = true;
67207fb6bef6242c0f2ab47f059583edbdef924823eJohn McCall    } else if (DI->getType()->isFunctionType()) {
6738dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      // C++ [temp.arg.type]p3:
6748dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      //   If a declaration acquires a function type through a type
6758dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      //   dependent on a template-parameter and this causes a
6768dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      //   declaration that does not use the syntactic form of a
6778dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      //   function declarator to have function type, the program is
6788dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      //   ill-formed.
6798dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
68007fb6bef6242c0f2ab47f059583edbdef924823eJohn McCall        << DI->getType();
6818dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      Invalid = true;
6828dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    }
683b4eeaff1595b7d0a8fbc2b3c8bec7dc63f48b7fdDouglas Gregor  } else {
684b4eeaff1595b7d0a8fbc2b3c8bec7dc63f48b7fdDouglas Gregor    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
6858dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  }
6868dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
6878dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  Expr *BitWidth = D->getBitWidth();
6888dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  if (Invalid)
6896bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    BitWidth = nullptr;
6908dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  else if (BitWidth) {
691f6702a3927147655206ae729a84339c4fda4c651Richard Smith    // The bit-width expression is a constant expression.
692f6702a3927147655206ae729a84339c4fda4c651Richard Smith    EnterExpressionEvaluationContext Unevaluated(SemaRef,
693f6702a3927147655206ae729a84339c4fda4c651Richard Smith                                                 Sema::ConstantEvaluated);
6941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
69560d7b3a319d84d688752be3870615ac0f111fb16John McCall    ExprResult InstantiatedBitWidth
696ce3ff2bd3a3386dbc209d3cba4b8769173b274c1John McCall      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
6978dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    if (InstantiatedBitWidth.isInvalid()) {
6988dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      Invalid = true;
6996bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      BitWidth = nullptr;
7008dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    } else
701c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      BitWidth = InstantiatedBitWidth.getAs<Expr>();
7028dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  }
7038dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
70407fb6bef6242c0f2ab47f059583edbdef924823eJohn McCall  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
70507fb6bef6242c0f2ab47f059583edbdef924823eJohn McCall                                            DI->getType(), DI,
7061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                            cast<RecordDecl>(Owner),
7078dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor                                            D->getLocation(),
7088dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor                                            D->isMutable(),
7098dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor                                            BitWidth,
710ca5233044ef679840d1ad1c46a36b16e2ee8a6e1Richard Smith                                            D->getInClassInitStyle(),
711703b6015176550eefc91f3e2f19cd19beacbc592Richard Smith                                            D->getInnerLocStart(),
7128dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor                                            D->getAccess(),
7136bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                            nullptr);
714663b5a0be7261c29bc4c526a71cffcfa02d4153eDouglas Gregor  if (!Field) {
715663b5a0be7261c29bc4c526a71cffcfa02d4153eDouglas Gregor    cast<Decl>(Owner)->setInvalidDecl();
7166bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
717663b5a0be7261c29bc4c526a71cffcfa02d4153eDouglas Gregor  }
7181eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
71923323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
720a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
721be507b6e72df8ab5e7d8c31eb4453e1bdf5fcfafRichard Smith  if (Field->hasAttrs())
722be507b6e72df8ab5e7d8c31eb4453e1bdf5fcfafRichard Smith    SemaRef.CheckAlignasUnderalignment(Field);
723be507b6e72df8ab5e7d8c31eb4453e1bdf5fcfafRichard Smith
724f4b5f5c6a1487317aab9aa30d97bccfd57c82c98Anders Carlsson  if (Invalid)
725f4b5f5c6a1487317aab9aa30d97bccfd57c82c98Anders Carlsson    Field->setInvalidDecl();
7261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
727f4b5f5c6a1487317aab9aa30d97bccfd57c82c98Anders Carlsson  if (!Field->getDeclName()) {
728f4b5f5c6a1487317aab9aa30d97bccfd57c82c98Anders Carlsson    // Keep track of where this decl came from.
729f4b5f5c6a1487317aab9aa30d97bccfd57c82c98Anders Carlsson    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
730a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  }
7319901c57806f7e36736ed1616e6ab3eebcc99b78cDouglas Gregor  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
7329901c57806f7e36736ed1616e6ab3eebcc99b78cDouglas Gregor    if (Parent->isAnonymousStructOrUnion() &&
7337a126a474fdde06382b315b4e3d8ef0a21d4dc31Sebastian Redl        Parent->getRedeclContext()->isFunctionOrMethod())
7349901c57806f7e36736ed1616e6ab3eebcc99b78cDouglas Gregor      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
7358dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  }
7361eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
737f4b5f5c6a1487317aab9aa30d97bccfd57c82c98Anders Carlsson  Field->setImplicit(D->isImplicit());
73846460a68f6508775e98c19b4bb8454bb471aac24John McCall  Field->setAccess(D->getAccess());
739f4b5f5c6a1487317aab9aa30d97bccfd57c82c98Anders Carlsson  Owner->addDecl(Field);
7408dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
7418dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  return Field;
7428dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor}
7438dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
74476da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCallDecl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
74576da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  bool Invalid = false;
74676da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  TypeSourceInfo *DI = D->getTypeSourceInfo();
74776da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall
74876da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  if (DI->getType()->isVariablyModifiedType()) {
74976da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall    SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
750651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      << D;
75176da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall    Invalid = true;
75276da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  } else if (DI->getType()->isInstantiationDependentType())  {
75376da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall    DI = SemaRef.SubstType(DI, TemplateArgs,
75476da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall                           D->getLocation(), D->getDeclName());
75576da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall    if (!DI) {
75676da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      DI = D->getTypeSourceInfo();
75776da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      Invalid = true;
75876da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall    } else if (DI->getType()->isFunctionType()) {
75976da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      // C++ [temp.arg.type]p3:
76076da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      //   If a declaration acquires a function type through a type
76176da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      //   dependent on a template-parameter and this causes a
76276da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      //   declaration that does not use the syntactic form of a
76376da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      //   function declarator to have function type, the program is
76476da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      //   ill-formed.
76576da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
76676da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      << DI->getType();
76776da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall      Invalid = true;
76876da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall    }
76976da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  } else {
77076da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
77176da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  }
77276da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall
773651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  MSPropertyDecl *Property = MSPropertyDecl::Create(
774651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
775651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
77676da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall
77776da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
77876da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall                           StartingScope);
77976da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall
78076da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  if (Invalid)
78176da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall    Property->setInvalidDecl();
78276da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall
78376da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  Property->setAccess(D->getAccess());
78476da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  Owner->addDecl(Property);
78576da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall
78676da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  return Property;
78776da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall}
78876da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall
78987c2e121cf0522fc266efe2922b58091cd2e0182Francois PichetDecl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
79087c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet  NamedDecl **NamedChain =
79187c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
79287c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet
79387c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet  int i = 0;
794651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  for (auto *PI : D->chain()) {
795651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
796b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor                                              TemplateArgs);
797b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor    if (!Next)
7986bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
799a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
800b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor    NamedChain[i++] = Next;
801b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor  }
80287c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet
80340e17752086c2c497951d64f5ac6ab5039466113Francois Pichet  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
804176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
805176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
8064967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      {NamedChain, D->getChainingSize()});
80787c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet
808176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  for (const auto *Attr : D->attrs())
809176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    IndirectField->addAttr(Attr->clone(SemaRef.Context));
81087c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet
81187c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet  IndirectField->setImplicit(D->isImplicit());
81287c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet  IndirectField->setAccess(D->getAccess());
81387c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet  Owner->addDecl(IndirectField);
81487c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet  return IndirectField;
81587c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet}
81687c2e121cf0522fc266efe2922b58091cd2e0182Francois Pichet
81702cace78cf48cc26686bd5b07c78606abca13bcdJohn McCallDecl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
81802cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  // Handle friend type expressions by simply substituting template
81906245bfb3ae40bb24a8bfb17eafeb266a4daf5caDouglas Gregor  // parameters into the pattern type and checking the result.
82032f2fb53d9d7c28c94d8569fd0fcf06cccee0c3dJohn McCall  if (TypeSourceInfo *Ty = D->getFriendType()) {
8214fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    TypeSourceInfo *InstTy;
8224fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    // If this is an unsupported friend, don't bother substituting template
8234fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    // arguments into it. The actual type referred to won't be used by any
8244fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    // parts of Clang, and may not be valid for instantiating. Just use the
8254fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    // same info for the instantiated friend.
8264fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    if (D->isUnsupportedFriend()) {
8274fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth      InstTy = Ty;
8284fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    } else {
8294fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
8304fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth                                 D->getLocation(), DeclarationName());
8314fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    }
8324fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth    if (!InstTy)
8336bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
834fd810b1386ed29b250e7d522ea826a65c815e49dJohn McCall
835d6f80daa84164ceeb8900da07f43b6a150edf713Richard Smith    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
8360216df8fd3ce58f5a68ef2ab141ea34c96c11164Abramo Bagnara                                                 D->getFriendLoc(), InstTy);
83706245bfb3ae40bb24a8bfb17eafeb266a4daf5caDouglas Gregor    if (!FD)
8386bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
839a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
84006245bfb3ae40bb24a8bfb17eafeb266a4daf5caDouglas Gregor    FD->setAccess(AS_public);
8419a34edb710917798aa30263374f624f13b594605John McCall    FD->setUnsupportedFriend(D->isUnsupportedFriend());
84206245bfb3ae40bb24a8bfb17eafeb266a4daf5caDouglas Gregor    Owner->addDecl(FD);
84306245bfb3ae40bb24a8bfb17eafeb266a4daf5caDouglas Gregor    return FD;
844a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  }
845a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
84606245bfb3ae40bb24a8bfb17eafeb266a4daf5caDouglas Gregor  NamedDecl *ND = D->getFriendDecl();
84706245bfb3ae40bb24a8bfb17eafeb266a4daf5caDouglas Gregor  assert(ND && "friend decl must be a decl or a type!");
84832f2fb53d9d7c28c94d8569fd0fcf06cccee0c3dJohn McCall
849af2094e7cecadf36667deb61a83587ffdd979bd3John McCall  // All of the Visit implementations for the various potential friend
850af2094e7cecadf36667deb61a83587ffdd979bd3John McCall  // declarations have to be carefully written to work for friend
851af2094e7cecadf36667deb61a83587ffdd979bd3John McCall  // objects, with the most important detail being that the target
852af2094e7cecadf36667deb61a83587ffdd979bd3John McCall  // decl should almost certainly not be placed in Owner.
853af2094e7cecadf36667deb61a83587ffdd979bd3John McCall  Decl *NewND = Visit(ND);
8546bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  if (!NewND) return nullptr;
8551eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
85602cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  FriendDecl *FD =
857a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
85806245bfb3ae40bb24a8bfb17eafeb266a4daf5caDouglas Gregor                       cast<NamedDecl>(NewND), D->getFriendLoc());
8595fee110ac106370f75592df024001de73edced2aJohn McCall  FD->setAccess(AS_public);
8609a34edb710917798aa30263374f624f13b594605John McCall  FD->setUnsupportedFriend(D->isUnsupportedFriend());
86102cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  Owner->addDecl(FD);
86202cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  return FD;
863fd810b1386ed29b250e7d522ea826a65c815e49dJohn McCall}
864fd810b1386ed29b250e7d522ea826a65c815e49dJohn McCall
8658dbc2694424b4e842b1d5ea39744a137b58600c3Douglas GregorDecl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
8668dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  Expr *AssertExpr = D->getAssertExpr();
8671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
868f6702a3927147655206ae729a84339c4fda4c651Richard Smith  // The expression in a static assertion is a constant expression.
869f6702a3927147655206ae729a84339c4fda4c651Richard Smith  EnterExpressionEvaluationContext Unevaluated(SemaRef,
870f6702a3927147655206ae729a84339c4fda4c651Richard Smith                                               Sema::ConstantEvaluated);
8711eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
87260d7b3a319d84d688752be3870615ac0f111fb16John McCall  ExprResult InstantiatedAssertExpr
873ce3ff2bd3a3386dbc209d3cba4b8769173b274c1John McCall    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
8748dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  if (InstantiatedAssertExpr.isInvalid())
8756bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
8768dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
877e3f470a718ec00eb8b546e405fa59bc2df2d7c46Richard Smith  return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
8789ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                              InstantiatedAssertExpr.get(),
879e3f470a718ec00eb8b546e405fa59bc2df2d7c46Richard Smith                                              D->getMessage(),
880e3f470a718ec00eb8b546e405fa59bc2df2d7c46Richard Smith                                              D->getRParenLoc(),
881e3f470a718ec00eb8b546e405fa59bc2df2d7c46Richard Smith                                              D->isFailed());
8828dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor}
8838dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
8848dbc2694424b4e842b1d5ea39744a137b58600c3Douglas GregorDecl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
8856bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  EnumDecl *PrevDecl = nullptr;
886176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
88738f0df352fadc546c5666079fb22de5ec1819d92Richard Smith    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
888176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                                   PatternPrev,
88938f0df352fadc546c5666079fb22de5ec1819d92Richard Smith                                                   TemplateArgs);
8906bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    if (!Prev) return nullptr;
89138f0df352fadc546c5666079fb22de5ec1819d92Richard Smith    PrevDecl = cast<EnumDecl>(Prev);
89238f0df352fadc546c5666079fb22de5ec1819d92Richard Smith  }
89338f0df352fadc546c5666079fb22de5ec1819d92Richard Smith
894ba877adeb49ed6dc17f27fa3a3bcd0cca713fd68Abramo Bagnara  EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
8958dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor                                    D->getLocation(), D->getIdentifier(),
89638f0df352fadc546c5666079fb22de5ec1819d92Richard Smith                                    PrevDecl, D->isScoped(),
897a88cefd266c428be33cc06f7e8b00ff8fc97c1ffAbramo Bagnara                                    D->isScopedUsingClassTag(), D->isFixed());
8981274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor  if (D->isFixed()) {
899f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith    if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
9001274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor      // If we have type source information for the underlying type, it means it
9011274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor      // has been explicitly set by the user. Perform substitution on it before
9021274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor      // moving on.
9031274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
904f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith      TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
905f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith                                                DeclarationName());
906f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith      if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
9071274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor        Enum->setIntegerType(SemaRef.Context.IntTy);
908f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith      else
909f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith        Enum->setIntegerTypeSourceInfo(NewTI);
910f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith    } else {
9111274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor      assert(!D->getIntegerType()->isDependentType()
9121274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor             && "Dependent type without type source info");
9131274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor      Enum->setIntegerType(D->getIntegerType());
9141274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor    }
9151274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor  }
9161274ccd90aec0b205fc838c3d504821ccfb55482Douglas Gregor
9175b629aa86c987f276d00453b6c9ab8424f7903feJohn McCall  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
9185b629aa86c987f276d00453b6c9ab8424f7903feJohn McCall
919f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
92006c0fecd197fef21e265a41bca8dc5022de1f864Douglas Gregor  Enum->setAccess(D->getAccess());
921651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  // Forward the mangling number from the template to the instantiated decl.
922651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
92387d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  // See if the old tag was defined along with a declarator.
92487d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  // If it did, mark the new tag as being associated with that declarator.
92587d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
92687d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
92787d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  // See if the old tag was defined along with a typedef.
92887d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  // If it did, mark the new tag as being associated with that typedef.
92987d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
93087d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
9316bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  if (SubstQualifier(D, Enum)) return nullptr;
93217945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  Owner->addDecl(Enum);
933f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith
9344ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith  EnumDecl *Def = D->getDefinition();
9354ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith  if (Def && Def != D) {
9364ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith    // If this is an out-of-line definition of an enum member template, check
9374ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith    // that the underlying types match in the instantiation of both
9384ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith    // declarations.
9394ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith    if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
9404ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
9414ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith      QualType DefnUnderlying =
9424ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith        SemaRef.SubstType(TI->getType(), TemplateArgs,
9434ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith                          UnderlyingLoc, DeclarationName());
9444ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
94587d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar                                     DefnUnderlying,
94687d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar                                     /*EnumUnderlyingIsImplicit=*/false, Enum);
9474ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith    }
9484ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith  }
9498dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
950f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith  // C++11 [temp.inst]p1: The implicit instantiation of a class template
951f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith  // specialization causes the implicit instantiation of the declarations, but
952f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith  // not the definitions of scoped member enumerations.
95357907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  //
95457907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  // DR1484 clarifies that enumeration definitions inside of a template
95557907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  // declaration aren't considered entities that can be separately instantiated
95657907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  // from the rest of the entity they are declared inside of.
95757907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
95857907e56191adea0fa870c052054eb0fe0c4681fBill Wendling    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
9594ca93d9978aac02b01814b4f749d6903a1f87ee5Richard Smith    InstantiateEnumDefinition(Enum, Def);
96057907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  }
961f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith
962f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith  return Enum;
963f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith}
964f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith
965f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smithvoid TemplateDeclInstantiator::InstantiateEnumDefinition(
966f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith    EnumDecl *Enum, EnumDecl *Pattern) {
967f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith  Enum->startDefinition();
968f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith
9691af83c444e5a2f6f50a6e1c15e6ebc618ae18a5fRichard Smith  // Update the location to refer to the definition.
9701af83c444e5a2f6f50a6e1c15e6ebc618ae18a5fRichard Smith  Enum->setLocation(Pattern->getLocation());
9711af83c444e5a2f6f50a6e1c15e6ebc618ae18a5fRichard Smith
9725f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<Decl*, 4> Enumerators;
9738dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
9746bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  EnumConstantDecl *LastEnumConst = nullptr;
975651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  for (auto *EC : Pattern->enumerators()) {
9768dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    // The specified value for the enumerator.
977c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    ExprResult Value((Expr *)nullptr);
978ac7610dad6653bad02dd42de198ca358b6fb1f1dDouglas Gregor    if (Expr *UninstValue = EC->getInitExpr()) {
979f6702a3927147655206ae729a84339c4fda4c651Richard Smith      // The enumerator's value expression is a constant expression.
9801eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      EnterExpressionEvaluationContext Unevaluated(SemaRef,
981f6702a3927147655206ae729a84339c4fda4c651Richard Smith                                                   Sema::ConstantEvaluated);
9821eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
983ce3ff2bd3a3386dbc209d3cba4b8769173b274c1John McCall      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
984ac7610dad6653bad02dd42de198ca358b6fb1f1dDouglas Gregor    }
9858dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
9868dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    // Drop the initial value and continue.
9878dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    bool isInvalid = false;
9888dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    if (Value.isInvalid()) {
989c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      Value = nullptr;
9908dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      isInvalid = true;
9918dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    }
9928dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
9931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    EnumConstantDecl *EnumConst
9948dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
9958dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor                                  EC->getLocation(), EC->getIdentifier(),
9969ae2f076ca5ab1feb3ba95629099ec2319833701John McCall                                  Value.get());
9978dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
9988dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    if (isInvalid) {
9998dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      if (EnumConst)
10008dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor        EnumConst->setInvalidDecl();
10018dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      Enum->setInvalidDecl();
10028dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    }
10038dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
10048dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    if (EnumConst) {
1005651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
10065b629aa86c987f276d00453b6c9ab8424f7903feJohn McCall
10073b85ecf2049c8670eba30d0c06f28f64168af9b8John McCall      EnumConst->setAccess(Enum->getAccess());
100817945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      Enum->addDecl(EnumConst);
1009d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall      Enumerators.push_back(EnumConst);
10108dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor      LastEnumConst = EnumConst;
1011a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1012f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1013f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith          !Enum->isScoped()) {
101496084f171f4824397dc48453146f0a9719cb9247Douglas Gregor        // If the enumeration is within a function or method, record the enum
101596084f171f4824397dc48453146f0a9719cb9247Douglas Gregor        // constant as a local.
1016651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
101796084f171f4824397dc48453146f0a9719cb9247Douglas Gregor      }
10188dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor    }
10198dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  }
10201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1021f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith  // FIXME: Fixup LBraceLoc
1022f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith  SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
1023f1c66b40213784a1c4612f04c14cafa2b0e89988Richard Smith                        Enum->getRBraceLoc(), Enum,
10249ff2b421f352fe0a0769c0a2a75af922c147b878Dmitri Gribenko                        Enumerators,
10256bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                        nullptr, nullptr);
10268dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor}
10278dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
10286477b69cc93e0a0ff15036d60d604f3544da0f29Douglas GregorDecl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1029b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
10306477b69cc93e0a0ff15036d60d604f3544da0f29Douglas Gregor}
10316477b69cc93e0a0ff15036d60d604f3544da0f29Douglas Gregor
103287d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga NainarDecl *
103387d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga NainarTemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
103487d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
103587d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar}
103687d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar
1037e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCallDecl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
103893ba8579c341d5329175f1413cdc3b35a36592d2John McCall  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
103993ba8579c341d5329175f1413cdc3b35a36592d2John McCall
1040550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // Create a local instantiation scope for this class template, which
1041550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // will contain the instantiations of the template parameters.
10422a7fb27913999d132cf9e10e03dc5271faa2e9d3John McCall  LocalInstantiationScope Scope(SemaRef);
1043e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  TemplateParameterList *TempParams = D->getTemplateParameters();
1044ce3ff2bd3a3386dbc209d3cba4b8769173b274c1John McCall  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
10451eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!InstParams)
10466bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
1047e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
1048e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  CXXRecordDecl *Pattern = D->getTemplatedDecl();
104993ba8579c341d5329175f1413cdc3b35a36592d2John McCall
105093ba8579c341d5329175f1413cdc3b35a36592d2John McCall  // Instantiate the qualifier.  We have to do this first in case
105193ba8579c341d5329175f1413cdc3b35a36592d2John McCall  // we're a friend declaration, because if we are then we need to put
105293ba8579c341d5329175f1413cdc3b35a36592d2John McCall  // the new declaration in the appropriate context.
1053c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1054c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  if (QualifierLoc) {
1055c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1056c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor                                                       TemplateArgs);
1057c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    if (!QualifierLoc)
10586bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
105993ba8579c341d5329175f1413cdc3b35a36592d2John McCall  }
106093ba8579c341d5329175f1413cdc3b35a36592d2John McCall
10616bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  CXXRecordDecl *PrevDecl = nullptr;
10626bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  ClassTemplateDecl *PrevClassTemplate = nullptr;
106393ba8579c341d5329175f1413cdc3b35a36592d2John McCall
1064176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
106537574f55cd637340f651330f5cfda69742880d36Nick Lewycky    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
10663bc93e3124ad5e7191c4a12dc981c8ee53578193David Blaikie    if (!Found.empty()) {
10673bc93e3124ad5e7191c4a12dc981c8ee53578193David Blaikie      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
106837574f55cd637340f651330f5cfda69742880d36Nick Lewycky      if (PrevClassTemplate)
106937574f55cd637340f651330f5cfda69742880d36Nick Lewycky        PrevDecl = PrevClassTemplate->getTemplatedDecl();
107037574f55cd637340f651330f5cfda69742880d36Nick Lewycky    }
107137574f55cd637340f651330f5cfda69742880d36Nick Lewycky  }
107237574f55cd637340f651330f5cfda69742880d36Nick Lewycky
107393ba8579c341d5329175f1413cdc3b35a36592d2John McCall  // If this isn't a friend, then it's a member template, in which
107493ba8579c341d5329175f1413cdc3b35a36592d2John McCall  // case we just want to build the instantiation in the
107593ba8579c341d5329175f1413cdc3b35a36592d2John McCall  // specialization.  If it is a friend, we want to build it in
107693ba8579c341d5329175f1413cdc3b35a36592d2John McCall  // the appropriate context.
107793ba8579c341d5329175f1413cdc3b35a36592d2John McCall  DeclContext *DC = Owner;
107893ba8579c341d5329175f1413cdc3b35a36592d2John McCall  if (isFriend) {
1079c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    if (QualifierLoc) {
108093ba8579c341d5329175f1413cdc3b35a36592d2John McCall      CXXScopeSpec SS;
1081c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor      SS.Adopt(QualifierLoc);
108293ba8579c341d5329175f1413cdc3b35a36592d2John McCall      DC = SemaRef.computeDeclContext(SS);
10836bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      if (!DC) return nullptr;
108493ba8579c341d5329175f1413cdc3b35a36592d2John McCall    } else {
108593ba8579c341d5329175f1413cdc3b35a36592d2John McCall      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
108693ba8579c341d5329175f1413cdc3b35a36592d2John McCall                                           Pattern->getDeclContext(),
108793ba8579c341d5329175f1413cdc3b35a36592d2John McCall                                           TemplateArgs);
108893ba8579c341d5329175f1413cdc3b35a36592d2John McCall    }
108993ba8579c341d5329175f1413cdc3b35a36592d2John McCall
109093ba8579c341d5329175f1413cdc3b35a36592d2John McCall    // Look for a previous declaration of the template in the owning
109193ba8579c341d5329175f1413cdc3b35a36592d2John McCall    // context.
109293ba8579c341d5329175f1413cdc3b35a36592d2John McCall    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
109393ba8579c341d5329175f1413cdc3b35a36592d2John McCall                   Sema::LookupOrdinaryName, Sema::ForRedeclaration);
109493ba8579c341d5329175f1413cdc3b35a36592d2John McCall    SemaRef.LookupQualifiedName(R, DC);
109593ba8579c341d5329175f1413cdc3b35a36592d2John McCall
109693ba8579c341d5329175f1413cdc3b35a36592d2John McCall    if (R.isSingleResult()) {
109793ba8579c341d5329175f1413cdc3b35a36592d2John McCall      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
109893ba8579c341d5329175f1413cdc3b35a36592d2John McCall      if (PrevClassTemplate)
109993ba8579c341d5329175f1413cdc3b35a36592d2John McCall        PrevDecl = PrevClassTemplate->getTemplatedDecl();
110093ba8579c341d5329175f1413cdc3b35a36592d2John McCall    }
110193ba8579c341d5329175f1413cdc3b35a36592d2John McCall
1102c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    if (!PrevClassTemplate && QualifierLoc) {
110393ba8579c341d5329175f1413cdc3b35a36592d2John McCall      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
11041eabb7d0c30f6a876b0fd03ad4656c096c26b8d0Douglas Gregor        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1105c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor        << QualifierLoc.getSourceRange();
11066bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
110793ba8579c341d5329175f1413cdc3b35a36592d2John McCall    }
110893ba8579c341d5329175f1413cdc3b35a36592d2John McCall
1109c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor    bool AdoptedPreviousTemplateParams = false;
111093ba8579c341d5329175f1413cdc3b35a36592d2John McCall    if (PrevClassTemplate) {
1111c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      bool Complain = true;
1112c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor
1113c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1114c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      // template for struct std::tr1::__detail::_Map_base, where the
1115c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      // template parameters of the friend declaration don't match the
1116c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      // template parameters of the original declaration. In this one
1117c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      // case, we don't complain about the ill-formed friend
1118c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      // declaration.
1119a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi      if (isFriend && Pattern->getIdentifier() &&
1120c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor          Pattern->getIdentifier()->isStr("_Map_base") &&
1121c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor          DC->isNamespace() &&
1122c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor          cast<NamespaceDecl>(DC)->getIdentifier() &&
1123c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor          cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1124c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor        DeclContext *DCParent = DC->getParent();
1125c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor        if (DCParent->isNamespace() &&
1126c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor            cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1127c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor            cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
11286bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines          if (cast<Decl>(DCParent)->isInStdNamespace())
1129c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor            Complain = false;
1130c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor        }
1131c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      }
1132c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor
113393ba8579c341d5329175f1413cdc3b35a36592d2John McCall      TemplateParameterList *PrevParams
113493ba8579c341d5329175f1413cdc3b35a36592d2John McCall        = PrevClassTemplate->getTemplateParameters();
113593ba8579c341d5329175f1413cdc3b35a36592d2John McCall
113693ba8579c341d5329175f1413cdc3b35a36592d2John McCall      // Make sure the parameter lists match.
113793ba8579c341d5329175f1413cdc3b35a36592d2John McCall      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1138a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                                  Complain,
1139c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor                                                  Sema::TPL_TemplateMatch)) {
1140c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor        if (Complain)
11416bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines          return nullptr;
1142c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor
1143c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor        AdoptedPreviousTemplateParams = true;
1144c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor        InstParams = PrevParams;
1145c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      }
114693ba8579c341d5329175f1413cdc3b35a36592d2John McCall
114793ba8579c341d5329175f1413cdc3b35a36592d2John McCall      // Do some additional validation, then merge default arguments
114893ba8579c341d5329175f1413cdc3b35a36592d2John McCall      // from the existing declarations.
1149c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor      if (!AdoptedPreviousTemplateParams &&
1150c53d0d762010217d02da5aa14be171817d63e3feDouglas Gregor          SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
115193ba8579c341d5329175f1413cdc3b35a36592d2John McCall                                             Sema::TPC_ClassTemplate))
11526bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
115393ba8579c341d5329175f1413cdc3b35a36592d2John McCall    }
115493ba8579c341d5329175f1413cdc3b35a36592d2John McCall  }
115593ba8579c341d5329175f1413cdc3b35a36592d2John McCall
1156e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  CXXRecordDecl *RecordInst
115793ba8579c341d5329175f1413cdc3b35a36592d2John McCall    = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
1158ba877adeb49ed6dc17f27fa3a3bcd0cca713fd68Abramo Bagnara                            Pattern->getLocStart(), Pattern->getLocation(),
1159ba877adeb49ed6dc17f27fa3a3bcd0cca713fd68Abramo Bagnara                            Pattern->getIdentifier(), PrevDecl,
1160f0510d49a6985e9284d30cfc36a0df2a6292a638Douglas Gregor                            /*DelayTypeCreation=*/true);
1161e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
1162c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  if (QualifierLoc)
1163c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    RecordInst->setQualifierInfo(QualifierLoc);
1164b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
1165e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  ClassTemplateDecl *Inst
116693ba8579c341d5329175f1413cdc3b35a36592d2John McCall    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
116793ba8579c341d5329175f1413cdc3b35a36592d2John McCall                                D->getIdentifier(), InstParams, RecordInst,
116893ba8579c341d5329175f1413cdc3b35a36592d2John McCall                                PrevClassTemplate);
1169e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  RecordInst->setDescribedClassTemplate(Inst);
1170ea7390c7b384ce607bfc8fc13c01f37cfc3776f0John McCall
117193ba8579c341d5329175f1413cdc3b35a36592d2John McCall  if (isFriend) {
1172ea7390c7b384ce607bfc8fc13c01f37cfc3776f0John McCall    if (PrevClassTemplate)
1173ea7390c7b384ce607bfc8fc13c01f37cfc3776f0John McCall      Inst->setAccess(PrevClassTemplate->getAccess());
1174ea7390c7b384ce607bfc8fc13c01f37cfc3776f0John McCall    else
1175ea7390c7b384ce607bfc8fc13c01f37cfc3776f0John McCall      Inst->setAccess(D->getAccess());
1176ea7390c7b384ce607bfc8fc13c01f37cfc3776f0John McCall
117722050f25e34ba0cd21ee2dc3d765951c48e27cdeRichard Smith    Inst->setObjectOfFriendDecl();
117893ba8579c341d5329175f1413cdc3b35a36592d2John McCall    // TODO: do we want to track the instantiation progeny of this
117993ba8579c341d5329175f1413cdc3b35a36592d2John McCall    // friend target decl?
118093ba8579c341d5329175f1413cdc3b35a36592d2John McCall  } else {
1181e8c01bdb56549adcecd71ce39160eea54b2c51c8Douglas Gregor    Inst->setAccess(D->getAccess());
118237574f55cd637340f651330f5cfda69742880d36Nick Lewycky    if (!PrevClassTemplate)
118337574f55cd637340f651330f5cfda69742880d36Nick Lewycky      Inst->setInstantiatedFromMemberTemplate(D);
118493ba8579c341d5329175f1413cdc3b35a36592d2John McCall  }
1185a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1186f0510d49a6985e9284d30cfc36a0df2a6292a638Douglas Gregor  // Trigger creation of the type for the instantiation.
11873cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall  SemaRef.Context.getInjectedClassNameType(RecordInst,
118824bae92f08ae098cc50a602d8cf1273b423e14daDouglas Gregor                                    Inst->getInjectedClassNameSpecialization());
1189ea7390c7b384ce607bfc8fc13c01f37cfc3776f0John McCall
1190259571e27e513cfaf691cc7447e09b31a47d5438Douglas Gregor  // Finish handling of friends.
119193ba8579c341d5329175f1413cdc3b35a36592d2John McCall  if (isFriend) {
11921b7f9cbed1b96b58a6e5f7808ebc9345a76a0936Richard Smith    DC->makeDeclVisibleInContext(Inst);
11934c51548271d2f8385127e1d943764ae8939d7794Abramo Bagnara    Inst->setLexicalDeclContext(Owner);
11944c51548271d2f8385127e1d943764ae8939d7794Abramo Bagnara    RecordInst->setLexicalDeclContext(Owner);
1195e8c01bdb56549adcecd71ce39160eea54b2c51c8Douglas Gregor    return Inst;
1196259571e27e513cfaf691cc7447e09b31a47d5438Douglas Gregor  }
1197a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
11984c51548271d2f8385127e1d943764ae8939d7794Abramo Bagnara  if (D->isOutOfLine()) {
11994c51548271d2f8385127e1d943764ae8939d7794Abramo Bagnara    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
12004c51548271d2f8385127e1d943764ae8939d7794Abramo Bagnara    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
12014c51548271d2f8385127e1d943764ae8939d7794Abramo Bagnara  }
12024c51548271d2f8385127e1d943764ae8939d7794Abramo Bagnara
1203e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  Owner->addDecl(Inst);
1204d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor
1205d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor  if (!PrevClassTemplate) {
1206d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor    // Queue up any out-of-line partial specializations of this member
1207d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor    // class template; the client will force their instantiation once
1208d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor    // the enclosing class has been instantiated.
12095f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1210d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor    D->getPartialSpecializations(PartialSpecs);
1211d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1212bc6509175e1ce5cc1b48d1b97ac8d23d8b74167cRafael Espindola      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1213d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1214d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor  }
1215d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor
1216e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  return Inst;
1217e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall}
1218e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
1219d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas GregorDecl *
12207974c3b7062f85bb7c0ada34526cdefe1d30f89bDouglas GregorTemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
12217974c3b7062f85bb7c0ada34526cdefe1d30f89bDouglas Gregor                                   ClassTemplatePartialSpecializationDecl *D) {
1222ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1223a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1224ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Lookup the already-instantiated declaration in the instantiation
1225ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // of the class template and return that.
1226ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  DeclContext::lookup_result Found
1227ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    = Owner->lookup(ClassTemplate->getDeclName());
12283bc93e3124ad5e7191c4a12dc981c8ee53578193David Blaikie  if (Found.empty())
12296bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
1230a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1231ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  ClassTemplateDecl *InstClassTemplate
12323bc93e3124ad5e7191c4a12dc981c8ee53578193David Blaikie    = dyn_cast<ClassTemplateDecl>(Found.front());
1233ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  if (!InstClassTemplate)
12346bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
1235a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1236d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor  if (ClassTemplatePartialSpecializationDecl *Result
1237d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1238d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor    return Result;
1239d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor
1240d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
12417974c3b7062f85bb7c0ada34526cdefe1d30f89bDouglas Gregor}
12427974c3b7062f85bb7c0ada34526cdefe1d30f89bDouglas Gregor
1243ef4579cda09b73e3d4d98af48201da25adc29326Larisse VoufoDecl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1244ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  assert(D->getTemplatedDecl()->isStaticDataMember() &&
1245ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo         "Only static data member templates are allowed.");
1246ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1247ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Create a local instantiation scope for this variable template, which
1248ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // will contain the instantiations of the template parameters.
1249ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  LocalInstantiationScope Scope(SemaRef);
1250ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TemplateParameterList *TempParams = D->getTemplateParameters();
1251ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1252ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (!InstParams)
12536bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
1254ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1255ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarDecl *Pattern = D->getTemplatedDecl();
12566bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  VarTemplateDecl *PrevVarTemplate = nullptr;
1257ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1258176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (getPreviousDeclForInstantiation(Pattern)) {
1259ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1260ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    if (!Found.empty())
1261ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1262ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
1263ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1264dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith  VarDecl *VarInst =
1265567f917df048d42732997a479b2b257403fc88efLarisse Voufo      cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1266567f917df048d42732997a479b2b257403fc88efLarisse Voufo                                         /*InstantiatingVarTemplate=*/true));
126787d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  if (!VarInst) return nullptr;
1268ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1269ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  DeclContext *DC = Owner;
1270ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1271ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateDecl *Inst = VarTemplateDecl::Create(
1272ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1273651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      VarInst);
1274ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarInst->setDescribedVarTemplate(Inst);
1275651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  Inst->setPreviousDecl(PrevVarTemplate);
1276ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1277ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  Inst->setAccess(D->getAccess());
1278ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (!PrevVarTemplate)
1279ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    Inst->setInstantiatedFromMemberTemplate(D);
1280ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1281ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (D->isOutOfLine()) {
1282ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1283ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1284ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
1285ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1286ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  Owner->addDecl(Inst);
1287ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1288ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (!PrevVarTemplate) {
1289ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // Queue up any out-of-line partial specializations of this member
1290ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // variable template; the client will force their instantiation once
1291ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // the enclosing class has been instantiated.
1292ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1293ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    D->getPartialSpecializations(PartialSpecs);
1294ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1295bc6509175e1ce5cc1b48d1b97ac8d23d8b74167cRafael Espindola      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1296ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        OutOfLineVarPartialSpecs.push_back(
1297ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo            std::make_pair(Inst, PartialSpecs[I]));
1298ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
1299ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1300ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  return Inst;
1301ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
1302ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1303ef4579cda09b73e3d4d98af48201da25adc29326Larisse VoufoDecl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1304ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarTemplatePartialSpecializationDecl *D) {
1305ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  assert(D->isStaticDataMember() &&
1306ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo         "Only static data member templates are allowed.");
1307ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1308ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1309ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1310ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Lookup the already-instantiated declaration and return that.
1311ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1312ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  assert(!Found.empty() && "Instantiation found nothing?");
1313ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1314ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1315ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1316ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1317ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (VarTemplatePartialSpecializationDecl *Result =
1318ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo          InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1319ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    return Result;
1320ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
1321ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1322ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
1323ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
13247974c3b7062f85bb7c0ada34526cdefe1d30f89bDouglas GregorDecl *
1325d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas GregorTemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1326550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // Create a local instantiation scope for this function template, which
1327550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // will contain the instantiations of the template parameters and then get
1328a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  // merged with the local instantiation scope for the function template
1329550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // itself.
13302a7fb27913999d132cf9e10e03dc5271faa2e9d3John McCall  LocalInstantiationScope Scope(SemaRef);
1331895162da2d52f4243f61081d7436de66af4503fcDouglas Gregor
1332d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor  TemplateParameterList *TempParams = D->getTemplateParameters();
1333d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
13341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!InstParams)
13356bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
1336a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
13376bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  FunctionDecl *Instantiated = nullptr;
1338a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1339a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1340a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor                                                                 InstParams));
1341a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor  else
1342a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1343a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                                          D->getTemplatedDecl(),
1344a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor                                                                InstParams));
1345a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1346a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor  if (!Instantiated)
13476bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
1348d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor
13491eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // Link the instantiated function template declaration to the function
1350d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor  // template from which it was instantiated.
1351a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  FunctionTemplateDecl *InstTemplate
1352a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    = Instantiated->getDescribedFunctionTemplate();
135337d68185088947322a97eabdc1c0714b0debd929Douglas Gregor  InstTemplate->setAccess(D->getAccess());
1354a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  assert(InstTemplate &&
1355a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1356e976ffe18ee60b81641423f42ff6feec2f5e3cb7John McCall
1357b1a56e767cfb645fcb25027ab728dd5824d92615John McCall  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1358b1a56e767cfb645fcb25027ab728dd5824d92615John McCall
1359e976ffe18ee60b81641423f42ff6feec2f5e3cb7John McCall  // Link the instantiation back to the pattern *unless* this is a
1360e976ffe18ee60b81641423f42ff6feec2f5e3cb7John McCall  // non-definition friend declaration.
1361e976ffe18ee60b81641423f42ff6feec2f5e3cb7John McCall  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1362b1a56e767cfb645fcb25027ab728dd5824d92615John McCall      !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1363a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    InstTemplate->setInstantiatedFromMemberTemplate(D);
1364a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1365b1a56e767cfb645fcb25027ab728dd5824d92615John McCall  // Make declarations visible in the appropriate context.
13661f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  if (!isFriend) {
1367a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    Owner->addDecl(InstTemplate);
13681f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  } else if (InstTemplate->getDeclContext()->isRecord() &&
1369176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines             !getPreviousDeclForInstantiation(D)) {
13701f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    SemaRef.CheckFriendAccess(InstTemplate);
13711f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  }
1372b1a56e767cfb645fcb25027ab728dd5824d92615John McCall
1373d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor  return InstTemplate;
1374d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor}
1375d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor
1376d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas GregorDecl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
13776bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  CXXRecordDecl *PrevDecl = nullptr;
1378d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor  if (D->isInjectedClassName())
1379d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor    PrevDecl = cast<CXXRecordDecl>(Owner);
1380176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
13817c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1382176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                                   PatternPrev,
13836c1c1b8c6ca743a5b6b4c81f9ac56392c12c7457John McCall                                                   TemplateArgs);
13846bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    if (!Prev) return nullptr;
13856c1c1b8c6ca743a5b6b4c81f9ac56392c12c7457John McCall    PrevDecl = cast<CXXRecordDecl>(Prev);
13866c1c1b8c6ca743a5b6b4c81f9ac56392c12c7457John McCall  }
1387d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor
1388d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor  CXXRecordDecl *Record
13891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1390ba877adeb49ed6dc17f27fa3a3bcd0cca713fd68Abramo Bagnara                            D->getLocStart(), D->getLocation(),
1391ba877adeb49ed6dc17f27fa3a3bcd0cca713fd68Abramo Bagnara                            D->getIdentifier(), PrevDecl);
1392b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
1393b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall  // Substitute the nested name specifier, if any.
1394b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall  if (SubstQualifier(D, Record))
13956bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
1396b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
1397d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor  Record->setImplicit(D->isImplicit());
1398eaba1af8529c381d7bfd4dd0a8b48d2c01647972Eli Friedman  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1399eaba1af8529c381d7bfd4dd0a8b48d2c01647972Eli Friedman  // the tag decls introduced by friend class declarations don't have an access
1400eaba1af8529c381d7bfd4dd0a8b48d2c01647972Eli Friedman  // specifier. Remove once this area of the code gets sorted out.
1401eaba1af8529c381d7bfd4dd0a8b48d2c01647972Eli Friedman  if (D->getAccess() != AS_none)
1402eaba1af8529c381d7bfd4dd0a8b48d2c01647972Eli Friedman    Record->setAccess(D->getAccess());
1403d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor  if (!D->isInjectedClassName())
1404f6b1185f0a8a209c06dfc1efdb6a59cc851e970cDouglas Gregor    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1405d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor
140602cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  // If the original function was part of a friend declaration,
140702cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  // inherit its namespace state.
140822050f25e34ba0cd21ee2dc3d765951c48e27cdeRichard Smith  if (D->getFriendObjectKind())
140922050f25e34ba0cd21ee2dc3d765951c48e27cdeRichard Smith    Record->setObjectOfFriendDecl();
141002cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall
14119901c57806f7e36736ed1616e6ab3eebcc99b78cDouglas Gregor  // Make sure that anonymous structs and unions are recorded.
141257907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  if (D->isAnonymousStructOrUnion())
14139901c57806f7e36736ed1616e6ab3eebcc99b78cDouglas Gregor    Record->setAnonymousStructOrUnion(true);
141457907e56191adea0fa870c052054eb0fe0c4681fBill Wendling
141557907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  if (D->isLocalClass())
141657907e56191adea0fa870c052054eb0fe0c4681fBill Wendling    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1417d8b285fee4471f393da8ee30f552ceacdc362afaAnders Carlsson
1418651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  // Forward the mangling number from the template to the instantiated decl.
1419651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  SemaRef.Context.setManglingNumber(Record,
1420651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                    SemaRef.Context.getManglingNumber(D));
1421651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
142287d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  // See if the old tag was defined along with a declarator.
142387d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  // If it did, mark the new tag as being associated with that declarator.
142487d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
142587d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
142687d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar
142787d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  // See if the old tag was defined along with a typedef.
142887d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  // If it did, mark the new tag as being associated with that typedef.
142987d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
143087d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
143187d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar
143217945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis  Owner->addDecl(Record);
143357907e56191adea0fa870c052054eb0fe0c4681fBill Wendling
143457907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  // DR1484 clarifies that the members of a local class are instantiated as part
143557907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  // of the instantiation of their enclosing entity.
143657907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  if (D->isCompleteDefinition() && D->isLocalClass()) {
1437b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    Sema::SavePendingLocalImplicitInstantiationsRAII
1438b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar        SavedPendingLocalImplicitInstantiations(SemaRef);
1439b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
1440651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1441651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                             TSK_ImplicitInstantiation,
1442651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                             /*Complain=*/true);
1443b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
1444651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1445651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                    TSK_ImplicitInstantiation);
1446b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
1447b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // This class may have local implicit instantiations that need to be
1448b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // performed within this scope.
1449b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    SemaRef.PerformPendingInstantiations(/*LocalOnly=*/true);
145057907e56191adea0fa870c052054eb0fe0c4681fBill Wendling  }
1451176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
1452176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1453176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
1454d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor  return Record;
1455d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor}
1456d475b8d9e6f5ff0e6ab8d15667ce8a64c7cb9a4dDouglas Gregor
145771074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor/// \brief Adjust the given function type for an instantiation of the
145871074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor/// given declaration, to cope with modifications to the function's type that
145971074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor/// aren't reflected in the type-source information.
146071074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor///
146171074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor/// \param D The declaration we're instantiating.
146271074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor/// \param TInfo The already-instantiated type.
146371074fdf40a8f5b53810712102b58c27efc30759Douglas Gregorstatic QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
146471074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor                                                   FunctionDecl *D,
146571074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor                                                   TypeSourceInfo *TInfo) {
1466bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor  const FunctionProtoType *OrigFunc
1467bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor    = D->getType()->castAs<FunctionProtoType>();
1468bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor  const FunctionProtoType *NewFunc
1469bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor    = TInfo->getType()->castAs<FunctionProtoType>();
1470bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1471bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor    return TInfo->getType();
1472bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor
1473bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1474bed51fef5773f043db2ad13aa2b6d2f8a8bdbdbaDouglas Gregor  NewEPI.ExtInfo = OrigFunc->getExtInfo();
1475651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  return Context.getFunctionType(NewFunc->getReturnType(),
1476651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                 NewFunc->getParamTypes(), NewEPI);
147771074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor}
147871074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor
147902cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall/// Normal class members are of more specific types and therefore
148002cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall/// don't make it here.  This function serves two purposes:
148102cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall///   1) instantiating function templates
148202cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall///   2) substituting friend declarations
14837557a1348d2821dce126a778aa7acd7a00b814fdDouglas GregorDecl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1484a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor                                       TemplateParameterList *TemplateParams) {
1485127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  // Check whether there is already a function template specialization for
1486127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  // this declaration.
1487127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1488b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  if (FunctionTemplate && !TemplateParams) {
1489c95d413660756c474bc8f97e5b32edc7ddff3850Richard Smith    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
14901eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
14916bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    void *InsertPos = nullptr;
14922c853e401ca406d417eb916e867226050e7be06bArgyrios Kyrtzidis    FunctionDecl *SpecFunc
1493c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
14941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1495127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor    // If we already have a function template specialization, return it.
14962c853e401ca406d417eb916e867226050e7be06bArgyrios Kyrtzidis    if (SpecFunc)
14972c853e401ca406d417eb916e867226050e7be06bArgyrios Kyrtzidis      return SpecFunc;
1498127102b5196ffe04bdb70fd553fe62c265ab10a9Douglas Gregor  }
14991eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1500b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  bool isFriend;
1501b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  if (FunctionTemplate)
1502b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1503b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  else
1504b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1505b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall
15066bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1507b212d9a8e10308cde5b7a1ce07bd59d8df14fa06Douglas Gregor    Owner->isFunctionOrMethod() ||
1508a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    !(isa<Decl>(Owner) &&
150979c2278a66d8fc0943774d1b7c71a32f7764e1e2Douglas Gregor      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
15102a7fb27913999d132cf9e10e03dc5271faa2e9d3John McCall  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
15111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
15125f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<ParmVarDecl *, 4> Params;
151364b4b43a23aa8b8009470e3cc451333f623d7d58David Blaikie  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
151421ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCall  if (!TInfo)
15156bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
151671074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1517fd810b1386ed29b250e7d522ea826a65c815e49dJohn McCall
1518c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1519c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  if (QualifierLoc) {
1520c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1521c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor                                                       TemplateArgs);
1522c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    if (!QualifierLoc)
15236bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
1524d325daa506338ab86f9dd468b48fd010673f49a6John McCall  }
1525d325daa506338ab86f9dd468b48fd010673f49a6John McCall
152668b6b87b6beb7922fc2c8ab923ba2ce125490363John McCall  // If we're instantiating a local function declaration, put the result
1527a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  // in the enclosing namespace; otherwise we need to find the instantiated
1528a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  // context.
152968b6b87b6beb7922fc2c8ab923ba2ce125490363John McCall  DeclContext *DC;
1530a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  if (D->isLocalExternDecl()) {
153168b6b87b6beb7922fc2c8ab923ba2ce125490363John McCall    DC = Owner;
1532a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    SemaRef.adjustContextForLocalExternDecl(DC);
1533a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  } else if (isFriend && QualifierLoc) {
1534d325daa506338ab86f9dd468b48fd010673f49a6John McCall    CXXScopeSpec SS;
1535c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    SS.Adopt(QualifierLoc);
1536d325daa506338ab86f9dd468b48fd010673f49a6John McCall    DC = SemaRef.computeDeclContext(SS);
15376bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    if (!DC) return nullptr;
1538d325daa506338ab86f9dd468b48fd010673f49a6John McCall  } else {
1539a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
15407c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor                                         TemplateArgs);
1541d325daa506338ab86f9dd468b48fd010673f49a6John McCall  }
154268b6b87b6beb7922fc2c8ab923ba2ce125490363John McCall
154302cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  FunctionDecl *Function =
1544ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara      FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1545635311f94e8fd4ff153130d91046ff78ffe97b06Abramo Bagnara                           D->getNameInfo(), T, TInfo,
1546459ef03126f9f0420efb3355e3b2ed3c1fdfb38aRafael Espindola                           D->getCanonicalDecl()->getStorageClass(),
1547af1fc7af351758b0ea0d285bdfe5640128109a4eRichard Smith                           D->isInlineSpecified(), D->hasWrittenPrototype(),
154886c3ae46250cdcc57778c27826060779a92f3815Richard Smith                           D->isConstexpr());
1549de9ed71c696bee936a21323f61548164de0eda13Enea Zaffanella  Function->setRangeEnd(D->getSourceRange().getEnd());
1550b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
1551d4497dde6fc8f5ce79e0ec37682b8dc920bbbef0Richard Smith  if (D->isInlined())
1552d4497dde6fc8f5ce79e0ec37682b8dc920bbbef0Richard Smith    Function->setImplicitlyInline();
1553d4497dde6fc8f5ce79e0ec37682b8dc920bbbef0Richard Smith
1554c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  if (QualifierLoc)
1555c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    Function->setQualifierInfo(QualifierLoc);
1556b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
1557a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  if (D->isLocalExternDecl())
1558a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    Function->setLocalExternDecl();
1559a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith
1560b1a56e767cfb645fcb25027ab728dd5824d92615John McCall  DeclContext *LexicalDC = Owner;
1561a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1562b1a56e767cfb645fcb25027ab728dd5824d92615John McCall    assert(D->getDeclContext()->isFileContext());
1563b1a56e767cfb645fcb25027ab728dd5824d92615John McCall    LexicalDC = D->getDeclContext();
1564b1a56e767cfb645fcb25027ab728dd5824d92615John McCall  }
1565b1a56e767cfb645fcb25027ab728dd5824d92615John McCall
1566b1a56e767cfb645fcb25027ab728dd5824d92615John McCall  Function->setLexicalDeclContext(LexicalDC);
15671eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1568e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor  // Attach the parameters
1569c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner  for (unsigned P = 0; P < Params.size(); ++P)
1570c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    if (Params[P])
1571c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner      Params[P]->setOwningFunction(Function);
15724278c654b645402554eb52a48e9c7097c9f1233aDavid Blaikie  Function->setParams(Params);
157302cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall
1574ac7c2c8a9d47df7d652364af3043c41816a18fa4Douglas Gregor  SourceLocation InstantiateAtPOI;
1575a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor  if (TemplateParams) {
1576a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // Our resulting instantiation is actually a function template, since we
1577a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // are substituting only the outer template parameters. For example, given
1578a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    //
1579a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    //   template<typename T>
1580a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    //   struct X {
1581a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    //     template<typename U> friend void f(T, U);
1582a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    //   };
1583a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    //
1584a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    //   X<int> x;
1585a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    //
1586a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    // We are instantiating the friend function template "f" within X<int>,
1587a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // which means substituting int for T, but leaving "f" as a friend function
1588a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // template.
1589a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // Build the function template itself.
1590d325daa506338ab86f9dd468b48fd010673f49a6John McCall    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1591a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor                                                    Function->getLocation(),
1592a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor                                                    Function->getDeclName(),
1593a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor                                                    TemplateParams, Function);
1594a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    Function->setDescribedFunctionTemplate(FunctionTemplate);
1595b1a56e767cfb645fcb25027ab728dd5824d92615John McCall
1596b1a56e767cfb645fcb25027ab728dd5824d92615John McCall    FunctionTemplate->setLexicalDeclContext(LexicalDC);
1597d325daa506338ab86f9dd468b48fd010673f49a6John McCall
1598d325daa506338ab86f9dd468b48fd010673f49a6John McCall    if (isFriend && D->isThisDeclarationADefinition()) {
1599d325daa506338ab86f9dd468b48fd010673f49a6John McCall      // TODO: should we remember this connection regardless of whether
1600d325daa506338ab86f9dd468b48fd010673f49a6John McCall      // the friend declaration provided a body?
1601d325daa506338ab86f9dd468b48fd010673f49a6John McCall      FunctionTemplate->setInstantiatedFromMemberTemplate(
1602d325daa506338ab86f9dd468b48fd010673f49a6John McCall                                           D->getDescribedFunctionTemplate());
1603d325daa506338ab86f9dd468b48fd010673f49a6John McCall    }
160466724ea67d7d598b937d86fa66f03f09a1c758f3Douglas Gregor  } else if (FunctionTemplate) {
160566724ea67d7d598b937d86fa66f03f09a1c758f3Douglas Gregor    // Record this function template specialization.
1606c95d413660756c474bc8f97e5b32edc7ddff3850Richard Smith    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1607838db383b69b9fb55f55c8e9546477df198a4faaDouglas Gregor    Function->setFunctionTemplateSpecialization(FunctionTemplate,
1608910f8008fea79120489a53593fe971b0b8a4a740Douglas Gregor                            TemplateArgumentList::CreateCopy(SemaRef.Context,
16094967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                                             Innermost),
16106bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                                /*InsertPos=*/nullptr);
161180f5b16efb658dabbcf971f42ed8b789aaaa6baaChandler Carruth  } else if (isFriend) {
161280f5b16efb658dabbcf971f42ed8b789aaaa6baaChandler Carruth    // Note, we need this connection even if the friend doesn't have a body.
161380f5b16efb658dabbcf971f42ed8b789aaaa6baaChandler Carruth    // Its body may exist but not have been attached yet due to deferred
161480f5b16efb658dabbcf971f42ed8b789aaaa6baaChandler Carruth    // parsing.
161580f5b16efb658dabbcf971f42ed8b789aaaa6baaChandler Carruth    // FIXME: It might be cleaner to set this when attaching the body to the
161680f5b16efb658dabbcf971f42ed8b789aaaa6baaChandler Carruth    // friend function declaration, however that would require finding all the
161780f5b16efb658dabbcf971f42ed8b789aaaa6baaChandler Carruth    // instantiations and modifying them.
1618d325daa506338ab86f9dd468b48fd010673f49a6John McCall    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
161902cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  }
1620a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1621e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor  if (InitFunctionInstantiation(Function, D))
1622e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor    Function->setInvalidDecl();
16231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1624af2094e7cecadf36667deb61a83587ffdd979bd3John McCall  bool isExplicitSpecialization = false;
1625a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1626a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  LookupResult Previous(
1627a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith      SemaRef, Function->getDeclName(), SourceLocation(),
1628a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith      D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1629a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith                             : Sema::LookupOrdinaryName,
1630a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith      Sema::ForRedeclaration);
16316826314938f8510cd1a6b03b5d032592456ae27bJohn McCall
1632af2094e7cecadf36667deb61a83587ffdd979bd3John McCall  if (DependentFunctionTemplateSpecializationInfo *Info
1633af2094e7cecadf36667deb61a83587ffdd979bd3John McCall        = D->getDependentSpecializationInfo()) {
1634af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    assert(isFriend && "non-friend has dependent specialization info?");
1635af2094e7cecadf36667deb61a83587ffdd979bd3John McCall
1636af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    // This needs to be set now for future sanity.
163722050f25e34ba0cd21ee2dc3d765951c48e27cdeRichard Smith    Function->setObjectOfFriendDecl();
1638af2094e7cecadf36667deb61a83587ffdd979bd3John McCall
1639af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    // Instantiate the explicit template arguments.
1640af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1641af2094e7cecadf36667deb61a83587ffdd979bd3John McCall                                          Info->getRAngleLoc());
1642e02e26293cf8e3bad1059b39cea75c6582896da6Douglas Gregor    if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1643e02e26293cf8e3bad1059b39cea75c6582896da6Douglas Gregor                      ExplicitArgs, TemplateArgs))
16446bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
1645af2094e7cecadf36667deb61a83587ffdd979bd3John McCall
1646af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    // Map the candidate templates to their instantiations.
1647af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1648af2094e7cecadf36667deb61a83587ffdd979bd3John McCall      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1649af2094e7cecadf36667deb61a83587ffdd979bd3John McCall                                                Info->getTemplate(I),
1650af2094e7cecadf36667deb61a83587ffdd979bd3John McCall                                                TemplateArgs);
16516bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      if (!Temp) return nullptr;
1652af2094e7cecadf36667deb61a83587ffdd979bd3John McCall
1653af2094e7cecadf36667deb61a83587ffdd979bd3John McCall      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1654af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    }
1655af2094e7cecadf36667deb61a83587ffdd979bd3John McCall
1656af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1657af2094e7cecadf36667deb61a83587ffdd979bd3John McCall                                                    &ExplicitArgs,
1658af2094e7cecadf36667deb61a83587ffdd979bd3John McCall                                                    Previous))
1659af2094e7cecadf36667deb61a83587ffdd979bd3John McCall      Function->setInvalidDecl();
1660a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1661af2094e7cecadf36667deb61a83587ffdd979bd3John McCall    isExplicitSpecialization = true;
1662af2094e7cecadf36667deb61a83587ffdd979bd3John McCall
1663af2094e7cecadf36667deb61a83587ffdd979bd3John McCall  } else if (TemplateParams || !FunctionTemplate) {
1664a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    // Look only into the namespace where the friend would be declared to
1665a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    // find a previous declaration. This is the innermost enclosing namespace,
1666a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // as described in ActOnFriendFunctionDecl.
16676826314938f8510cd1a6b03b5d032592456ae27bJohn McCall    SemaRef.LookupQualifiedName(Previous, DC);
1668a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
1669a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // In C++, the previous declaration we find might be a tag type
1670a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // (class or enum). In this case, the new declaration will hide the
1671a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // tag type. Note that this does does not apply if we're declaring a
1672a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor    // typedef (C++ [dcl.typedef]p4).
16736826314938f8510cd1a6b03b5d032592456ae27bJohn McCall    if (Previous.isSingleTagDecl())
16746826314938f8510cd1a6b03b5d032592456ae27bJohn McCall      Previous.clear();
1675a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor  }
1676a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
16776bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
16782c712f50cd56eaf3662989b556e9c6b1e8fcd11aKaelyn Uhrain                                   isExplicitSpecialization);
1679e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor
168076d326448d7e4c10b2896edc2ee855d1e68d1b88John McCall  NamedDecl *PrincipalDecl = (TemplateParams
168176d326448d7e4c10b2896edc2ee855d1e68d1b88John McCall                              ? cast<NamedDecl>(FunctionTemplate)
168276d326448d7e4c10b2896edc2ee855d1e68d1b88John McCall                              : Function);
168376d326448d7e4c10b2896edc2ee855d1e68d1b88John McCall
1684a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor  // If the original function was part of a friend declaration,
1685a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor  // inherit its namespace state and add it to the owner.
1686d325daa506338ab86f9dd468b48fd010673f49a6John McCall  if (isFriend) {
168722050f25e34ba0cd21ee2dc3d765951c48e27cdeRichard Smith    PrincipalDecl->setObjectOfFriendDecl();
16881b7f9cbed1b96b58a6e5f7808ebc9345a76a0936Richard Smith    DC->makeDeclVisibleInContext(PrincipalDecl);
1689ab297ac4d3f7c078a34c75493b840ef6b5801be3Gabor Greif
1690651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    bool QueuedInstantiation = false;
1691ab297ac4d3f7c078a34c75493b840ef6b5801be3Gabor Greif
1692651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    // C++11 [temp.friend]p4 (DR329):
1693651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    //   When a function is defined in a friend function declaration in a class
1694651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    //   template, the function is instantiated when the function is odr-used.
1695651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    //   The same restrictions on multiple declarations and definitions that
1696651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    //   apply to non-template function declarations and definitions also apply
1697651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    //   to these implicit definitions.
1698651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    if (D->isThisDeclarationADefinition()) {
1699238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor      // Check for a function body.
17006bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      const FunctionDecl *Definition = nullptr;
170110620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt      if (Function->isDefined(Definition) &&
1702238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor          Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1703651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1704651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines            << Function->getDeclName();
1705238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor        SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1706a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi      }
1707238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor      // Check for redefinitions due to other instantiations of this or
1708238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor      // a similar friend function.
1709651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      else for (auto R : Function->redecls()) {
1710651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        if (R == Function)
171113a8affbb87cdb869adabe2a6e5998559f2598c4Gabor Greif          continue;
1712651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
1713651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        // If some prior declaration of this function has been used, we need
1714651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        // to instantiate its definition.
1715651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        if (!QueuedInstantiation && R->isUsed(false)) {
1716651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines          if (MemberSpecializationInfo *MSInfo =
1717651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                  Function->getMemberSpecializationInfo()) {
1718651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines            if (MSInfo->getPointOfInstantiation().isInvalid()) {
1719651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines              SourceLocation Loc = R->getLocation(); // FIXME
1720651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines              MSInfo->setPointOfInstantiation(Loc);
1721651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines              SemaRef.PendingLocalImplicitInstantiations.push_back(
1722651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                               std::make_pair(Function, Loc));
1723651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines              QueuedInstantiation = true;
1724ab297ac4d3f7c078a34c75493b840ef6b5801be3Gabor Greif            }
1725ab297ac4d3f7c078a34c75493b840ef6b5801be3Gabor Greif          }
1726651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        }
1727651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
1728651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        // If some prior declaration of this function was a friend with an
1729651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        // uninstantiated definition, reject it.
1730651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        if (R->getFriendObjectKind()) {
1731651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines          if (const FunctionDecl *RPattern =
1732651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                  R->getTemplateInstantiationPattern()) {
173310620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt            if (RPattern->isDefined(RPattern)) {
1734651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines              SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1735238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor                << Function->getDeclName();
17366a557d8f6b3d7a747a0b57960d4b86f05ba2e53cGabor Greif              SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1737238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor              break;
1738238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor            }
1739651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines          }
1740238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor        }
1741238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor      }
1742238058c372cfb7bdaf489f51171eb1380ebfd6a6Douglas Gregor    }
1743a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor  }
1744a735b206fdb5c15767a45289e1ffb3b568f70f2bDouglas Gregor
1745a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1746a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    DC->makeDeclVisibleInContext(PrincipalDecl);
1747a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith
174876d326448d7e4c10b2896edc2ee855d1e68d1b88John McCall  if (Function->isOverloadedOperator() && !DC->isRecord() &&
174976d326448d7e4c10b2896edc2ee855d1e68d1b88John McCall      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
175076d326448d7e4c10b2896edc2ee855d1e68d1b88John McCall    PrincipalDecl->setNonMemberOperator();
175176d326448d7e4c10b2896edc2ee855d1e68d1b88John McCall
1752eb88ae5f9acdd17ec76fb83e151a77e25e4e8f31Sean Hunt  assert(!D->isDefaulted() && "only methods should be defaulted");
1753e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor  return Function;
1754e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor}
17552dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor
1756d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas GregorDecl *
1757d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas GregorTemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1758af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet                                      TemplateParameterList *TemplateParams,
1759af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet                                      bool IsClassScopeSpecialization) {
17606b906869527be40b0d38d755e9ef51b331b88162Douglas Gregor  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1761d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor  if (FunctionTemplate && !TemplateParams) {
17621eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // We are creating a function template specialization from a function
17631eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // template. Check whether there is already a function template
1764d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    // specialization for this particular set of template arguments.
1765c95d413660756c474bc8f97e5b32edc7ddff3850Richard Smith    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
17661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17676bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    void *InsertPos = nullptr;
17682c853e401ca406d417eb916e867226050e7be06bArgyrios Kyrtzidis    FunctionDecl *SpecFunc
1769c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
17701eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
17716b906869527be40b0d38d755e9ef51b331b88162Douglas Gregor    // If we already have a function template specialization, return it.
17722c853e401ca406d417eb916e867226050e7be06bArgyrios Kyrtzidis    if (SpecFunc)
17732c853e401ca406d417eb916e867226050e7be06bArgyrios Kyrtzidis      return SpecFunc;
17746b906869527be40b0d38d755e9ef51b331b88162Douglas Gregor  }
17756b906869527be40b0d38d755e9ef51b331b88162Douglas Gregor
1776b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  bool isFriend;
1777b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  if (FunctionTemplate)
1778b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1779b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  else
1780b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1781b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall
17826bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1783a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    !(isa<Decl>(Owner) &&
178479c2278a66d8fc0943774d1b7c71a32f7764e1e2Douglas Gregor      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
17852a7fb27913999d132cf9e10e03dc5271faa2e9d3John McCall  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
178648dd19b19ddb9e105f8cf0bf6f0732ca4e6a385bDouglas Gregor
17874eab39f0745fb1949dbb40c4145771b927888242John McCall  // Instantiate enclosing template arguments for friends.
17885f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<TemplateParameterList *, 4> TempParamLists;
17894eab39f0745fb1949dbb40c4145771b927888242John McCall  unsigned NumTempParamLists = 0;
17904eab39f0745fb1949dbb40c4145771b927888242John McCall  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
179187d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    TempParamLists.resize(NumTempParamLists);
17924eab39f0745fb1949dbb40c4145771b927888242John McCall    for (unsigned I = 0; I != NumTempParamLists; ++I) {
17934eab39f0745fb1949dbb40c4145771b927888242John McCall      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
17944eab39f0745fb1949dbb40c4145771b927888242John McCall      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
17954eab39f0745fb1949dbb40c4145771b927888242John McCall      if (!InstParams)
17966bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
17974eab39f0745fb1949dbb40c4145771b927888242John McCall      TempParamLists[I] = InstParams;
17984eab39f0745fb1949dbb40c4145771b927888242John McCall    }
17994eab39f0745fb1949dbb40c4145771b927888242John McCall  }
18004eab39f0745fb1949dbb40c4145771b927888242John McCall
18015f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<ParmVarDecl *, 4> Params;
1802dc370c1e70a2f876c65be4057ead751b72c8ddd5Benjamin Kramer  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
180321ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCall  if (!TInfo)
18046bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
180571074fdf40a8f5b53810712102b58c27efc30759Douglas Gregor  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
18062dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor
1807c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1808c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  if (QualifierLoc) {
1809c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1810b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall                                                 TemplateArgs);
1811a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    if (!QualifierLoc)
18126bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
1813b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  }
1814b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall
1815b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  DeclContext *DC = Owner;
1816b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  if (isFriend) {
1817c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    if (QualifierLoc) {
1818b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall      CXXScopeSpec SS;
1819c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor      SS.Adopt(QualifierLoc);
1820b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall      DC = SemaRef.computeDeclContext(SS);
1821c54d688c604d28dcb9ab8f92047837c10c8f9c61John McCall
1822c54d688c604d28dcb9ab8f92047837c10c8f9c61John McCall      if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
18236bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
1824b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    } else {
1825b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1826b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall                                           D->getDeclContext(),
1827b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall                                           TemplateArgs);
1828b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    }
18296bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    if (!DC) return nullptr;
1830b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  }
1831b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall
18322dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor  // Build the instantiated method declaration.
1833b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
18346bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  CXXMethodDecl *Method = nullptr;
18351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1836ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara  SourceLocation StartLoc = D->getInnerLocStart();
18372577743c5650c646fb705df01403707e94f2df04Abramo Bagnara  DeclarationNameInfo NameInfo
18382577743c5650c646fb705df01403707e94f2df04Abramo Bagnara    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
183917e32f30e2d1eaf6639d3d4e2196a8d7c709fbacDouglas Gregor  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
18401eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1841ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                        StartLoc, NameInfo, T, TInfo,
18421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                        Constructor->isExplicit(),
184316573fa9705b546b7597c273b25b85d6321e2b33Douglas Gregor                                        Constructor->isInlineSpecified(),
184486c3ae46250cdcc57778c27826060779a92f3815Richard Smith                                        false, Constructor->isConstexpr());
184517e32f30e2d1eaf6639d3d4e2196a8d7c709fbacDouglas Gregor  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
184617e32f30e2d1eaf6639d3d4e2196a8d7c709fbacDouglas Gregor    Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1847ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                       StartLoc, NameInfo, T, TInfo,
18482577743c5650c646fb705df01403707e94f2df04Abramo Bagnara                                       Destructor->isInlineSpecified(),
184916573fa9705b546b7597c273b25b85d6321e2b33Douglas Gregor                                       false);
185065ec1fda479688d143fe2403242cd9c730c800a1Douglas Gregor  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
185165ec1fda479688d143fe2403242cd9c730c800a1Douglas Gregor    Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1852ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                       StartLoc, NameInfo, T, TInfo,
18530130f3cc4ccd5f46361c48d5fe94133d74619424Douglas Gregor                                       Conversion->isInlineSpecified(),
1854f52516038ab5d0b1b90a6dd32f46b7d6dabd04c8Douglas Gregor                                       Conversion->isExplicit(),
185586c3ae46250cdcc57778c27826060779a92f3815Richard Smith                                       Conversion->isConstexpr(),
18569f569cca2a4c5fb6026005434e27025b9e71309dRichard Smith                                       Conversion->getLocEnd());
1857dec06664a1c4d8984251083db2215875aea1c80dDouglas Gregor  } else {
185872fdc8947e54be1a8dd36b03e24f112aba1241e1Rafael Espindola    StorageClass SC = D->isStatic() ? SC_Static : SC_None;
18592577743c5650c646fb705df01403707e94f2df04Abramo Bagnara    Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1860ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                   StartLoc, NameInfo, T, TInfo,
186172fdc8947e54be1a8dd36b03e24f112aba1241e1Rafael Espindola                                   SC, D->isInlineSpecified(),
186286c3ae46250cdcc57778c27826060779a92f3815Richard Smith                                   D->isConstexpr(), D->getLocEnd());
1863dec06664a1c4d8984251083db2215875aea1c80dDouglas Gregor  }
18646b906869527be40b0d38d755e9ef51b331b88162Douglas Gregor
1865d4497dde6fc8f5ce79e0ec37682b8dc920bbbef0Richard Smith  if (D->isInlined())
1866d4497dde6fc8f5ce79e0ec37682b8dc920bbbef0Richard Smith    Method->setImplicitlyInline();
1867d4497dde6fc8f5ce79e0ec37682b8dc920bbbef0Richard Smith
1868c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor  if (QualifierLoc)
1869c22b5fff39a7520207f165fb16a27a34b944bd9cDouglas Gregor    Method->setQualifierInfo(QualifierLoc);
1870b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
1871d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor  if (TemplateParams) {
1872d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    // Our resulting instantiation is actually a function template, since we
1873d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    // are substituting only the outer template parameters. For example, given
18741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    //
1875d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    //   template<typename T>
1876d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    //   struct X {
1877d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    //     template<typename U> void f(T, U);
1878d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    //   };
1879d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    //
1880d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    //   X<int> x;
1881d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    //
1882d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    // We are instantiating the member template "f" within X<int>, which means
1883d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    // substituting int for T, but leaving "f" as a member function template.
1884d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    // Build the function template itself.
1885d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1886d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor                                                    Method->getLocation(),
18871eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump                                                    Method->getDeclName(),
1888d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor                                                    TemplateParams, Method);
1889b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    if (isFriend) {
1890b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall      FunctionTemplate->setLexicalDeclContext(Owner);
189122050f25e34ba0cd21ee2dc3d765951c48e27cdeRichard Smith      FunctionTemplate->setObjectOfFriendDecl();
1892b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    } else if (D->isOutOfLine())
18931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1894d60e105e6d1624da647ef7dd35a9cf6fad1b763eDouglas Gregor    Method->setDescribedFunctionTemplate(FunctionTemplate);
189566724ea67d7d598b937d86fa66f03f09a1c758f3Douglas Gregor  } else if (FunctionTemplate) {
189666724ea67d7d598b937d86fa66f03f09a1c758f3Douglas Gregor    // Record this function template specialization.
1897c95d413660756c474bc8f97e5b32edc7ddff3850Richard Smith    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1898838db383b69b9fb55f55c8e9546477df198a4faaDouglas Gregor    Method->setFunctionTemplateSpecialization(FunctionTemplate,
1899910f8008fea79120489a53593fe971b0b8a4a740Douglas Gregor                         TemplateArgumentList::CreateCopy(SemaRef.Context,
19004967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                                          Innermost),
19016bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                              /*InsertPos=*/nullptr);
1902b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  } else if (!isFriend) {
190366724ea67d7d598b937d86fa66f03f09a1c758f3Douglas Gregor    // Record that this is an instantiation of a member function.
19042db323294ac02296125e1e0beb4c3595992e75bbDouglas Gregor    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
190566724ea67d7d598b937d86fa66f03f09a1c758f3Douglas Gregor  }
1906a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
19071eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // If we are instantiating a member function defined
19087caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  // out-of-line, the instantiation will have the same lexical
19097caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  // context (which will be a namespace scope) as the template.
1910b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  if (isFriend) {
19114eab39f0745fb1949dbb40c4145771b927888242John McCall    if (NumTempParamLists)
191287d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar      Method->setTemplateParameterListsInfo(
191387d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar          SemaRef.Context,
191487d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar          llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
19154eab39f0745fb1949dbb40c4145771b927888242John McCall
1916b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    Method->setLexicalDeclContext(Owner);
191722050f25e34ba0cd21ee2dc3d765951c48e27cdeRichard Smith    Method->setObjectOfFriendDecl();
1918b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  } else if (D->isOutOfLine())
19197caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    Method->setLexicalDeclContext(D->getLexicalDeclContext());
19201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
19215545e166a956a20d7a6b58408e251a1119025485Douglas Gregor  // Attach the parameters
19225545e166a956a20d7a6b58408e251a1119025485Douglas Gregor  for (unsigned P = 0; P < Params.size(); ++P)
19235545e166a956a20d7a6b58408e251a1119025485Douglas Gregor    Params[P]->setOwningFunction(Method);
19244278c654b645402554eb52a48e9c7097c9f1233aDavid Blaikie  Method->setParams(Params);
19255545e166a956a20d7a6b58408e251a1119025485Douglas Gregor
19265545e166a956a20d7a6b58408e251a1119025485Douglas Gregor  if (InitMethodInstantiation(Method, D))
19275545e166a956a20d7a6b58408e251a1119025485Douglas Gregor    Method->setInvalidDecl();
19282dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor
19292577743c5650c646fb705df01403707e94f2df04Abramo Bagnara  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
19302577743c5650c646fb705df01403707e94f2df04Abramo Bagnara                        Sema::ForRedeclaration);
19311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1932b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  if (!FunctionTemplate || TemplateParams || isFriend) {
1933b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall    SemaRef.LookupQualifiedName(Previous, Record);
19341eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1935dec06664a1c4d8984251083db2215875aea1c80dDouglas Gregor    // In C++, the previous declaration we find might be a tag type
1936dec06664a1c4d8984251083db2215875aea1c80dDouglas Gregor    // (class or enum). In this case, the new declaration will hide the
1937dec06664a1c4d8984251083db2215875aea1c80dDouglas Gregor    // tag type. Note that this does does not apply if we're declaring a
1938dec06664a1c4d8984251083db2215875aea1c80dDouglas Gregor    // typedef (C++ [dcl.typedef]p4).
19396826314938f8510cd1a6b03b5d032592456ae27bJohn McCall    if (Previous.isSingleTagDecl())
19406826314938f8510cd1a6b03b5d032592456ae27bJohn McCall      Previous.clear();
1941dec06664a1c4d8984251083db2215875aea1c80dDouglas Gregor  }
19422dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor
1943af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  if (!IsClassScopeSpecialization)
19446bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
194565ec1fda479688d143fe2403242cd9c730c800a1Douglas Gregor
19464ba3136b3eb9740a07bd61d0ab23ce9a8d894deeDouglas Gregor  if (D->isPure())
19474ba3136b3eb9740a07bd61d0ab23ce9a8d894deeDouglas Gregor    SemaRef.CheckPureMethod(Method, SourceRange());
19484ba3136b3eb9740a07bd61d0ab23ce9a8d894deeDouglas Gregor
19491f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // Propagate access.  For a non-friend declaration, the access is
19501f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // whatever we're propagating from.  For a friend, it should be the
19511f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // previous declaration we just found.
19521f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  if (isFriend && Method->getPreviousDecl())
19531f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    Method->setAccess(Method->getPreviousDecl()->getAccess());
19541f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  else
19551f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    Method->setAccess(D->getAccess());
19561f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  if (FunctionTemplate)
19571f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    FunctionTemplate->setAccess(Method->getAccess());
195846460a68f6508775e98c19b4bb8454bb471aac24John McCall
19599eefa229dfb71400a6bbee326420a7f0e2e91f1fAnders Carlsson  SemaRef.CheckOverrideControl(Method);
19609eefa229dfb71400a6bbee326420a7f0e2e91f1fAnders Carlsson
19613bc451593fa44bfc45753e44e37cb4242e714f82Eli Friedman  // If a function is defined as defaulted or deleted, mark it as such now.
1962ac71351acdefc9de0c770c1d717e621ac9e684bfRichard Smith  if (D->isExplicitlyDefaulted())
1963ac71351acdefc9de0c770c1d717e621ac9e684bfRichard Smith    SemaRef.SetDeclDefaulted(Method, Method->getLocation());
19643bc451593fa44bfc45753e44e37cb4242e714f82Eli Friedman  if (D->isDeletedAsWritten())
1965ac71351acdefc9de0c770c1d717e621ac9e684bfRichard Smith    SemaRef.SetDeclDeleted(Method, Method->getLocation());
19663bc451593fa44bfc45753e44e37cb4242e714f82Eli Friedman
19671f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // If there's a function template, let our caller handle it.
1968b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  if (FunctionTemplate) {
19691f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    // do nothing
19701f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall
19711f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // Don't hide a (potentially) valid declaration with an invalid one.
1972b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  } else if (Method->isInvalidDecl() && !Previous.empty()) {
19731f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    // do nothing
19741f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall
19751f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // Otherwise, check access to friends and make them visible.
19761f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  } else if (isFriend) {
19771f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    // We only need to re-check access for methods which we didn't
19781f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    // manage to match during parsing.
19791f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    if (!D->getPreviousDecl())
19801f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall      SemaRef.CheckFriendAccess(Method);
19811f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall
19821f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    Record->makeDeclVisibleInContext(Method);
19831f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall
19841f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // Otherwise, add the declaration.  We don't need to do this for
19851f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // class-scope specializations because we'll have matched them with
19861f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  // the appropriate template.
19871f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall  } else if (!IsClassScopeSpecialization) {
19881f2e1a96bec2ba6418ae7f2d2b525a3575203b6aJohn McCall    Owner->addDecl(Method);
1989b0cb022daec8671406ab25f4b5d5a6d48d823bc4John McCall  }
1990eb88ae5f9acdd17ec76fb83e151a77e25e4e8f31Sean Hunt
19912dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor  return Method;
19922dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor}
19932dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor
1994615c5d4674355ba830b9978f462ca7a8c5d15f85Douglas GregorDecl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1995dec06664a1c4d8984251083db2215875aea1c80dDouglas Gregor  return VisitCXXMethodDecl(D);
1996615c5d4674355ba830b9978f462ca7a8c5d15f85Douglas Gregor}
1997615c5d4674355ba830b9978f462ca7a8c5d15f85Douglas Gregor
199803b2b07aaef3a585aec13048a33356c7f635de72Douglas GregorDecl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
199917e32f30e2d1eaf6639d3d4e2196a8d7c709fbacDouglas Gregor  return VisitCXXMethodDecl(D);
200003b2b07aaef3a585aec13048a33356c7f635de72Douglas Gregor}
200103b2b07aaef3a585aec13048a33356c7f635de72Douglas Gregor
2002bb969ed4193e2eadabfaa0dfd0b94312b6146349Douglas GregorDecl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
200365ec1fda479688d143fe2403242cd9c730c800a1Douglas Gregor  return VisitCXXMethodDecl(D);
2004bb969ed4193e2eadabfaa0dfd0b94312b6146349Douglas Gregor}
2005bb969ed4193e2eadabfaa0dfd0b94312b6146349Douglas Gregor
2006ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
200766874fb18afbffb8b2ca05576851a64534be3352David Blaikie  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
200866874fb18afbffb8b2ca05576851a64534be3352David Blaikie                                  /*ExpectParameterPack=*/ false);
20092dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor}
20102dc0e64e57b2a1786fa53a7dbd1d5c8e255eadb0Douglas Gregor
2011e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCallDecl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2012e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall                                                    TemplateTypeParmDecl *D) {
2013e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  // TODO: don't always clone when decls are refcounted.
20144fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth  assert(D->getTypeForDecl()->isTemplateTypeParmType());
20151eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2016e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  TemplateTypeParmDecl *Inst =
2017344577e6b58f42d18dc8118c8903b49a85dc005eAbramo Bagnara    TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
2018344577e6b58f42d18dc8118c8903b49a85dc005eAbramo Bagnara                                 D->getLocStart(), D->getLocation(),
20194fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth                                 D->getDepth() - TemplateArgs.getNumLevels(),
20204fb86f8c4585e53c21c847ad3de9e3b2de123cd9Chandler Carruth                                 D->getIndex(), D->getIdentifier(),
2021e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall                                 D->wasDeclaredWithTypename(),
2022e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall                                 D->isParameterPack());
20239a299e0575ce235f491014627c7267e2d2cd73deDouglas Gregor  Inst->setAccess(AS_public);
2024a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
202587d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
20269d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer    TypeSourceInfo *InstantiatedDefaultArg =
20279d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer        SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
20289d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer                          D->getDefaultArgumentLoc(), D->getDeclName());
20299d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer    if (InstantiatedDefaultArg)
2030b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      Inst->setDefaultArgument(InstantiatedDefaultArg);
20319d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer  }
2032e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
2033a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  // Introduce this template parameter's instantiation into the instantiation
2034550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // scope.
2035550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2036a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
2037e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  return Inst;
2038e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall}
2039e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
204033642df30088f2ddb0b22c609523ab8df9dff595Douglas GregorDecl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
204133642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor                                                 NonTypeTemplateParmDecl *D) {
204233642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor  // Substitute into the type of the non-type template parameter.
20436952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
20445f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
20455f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<QualType, 4> ExpandedParameterPackTypes;
20466952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor  bool IsExpandedParameterPack = false;
2047a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  TypeSourceInfo *DI;
204833642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor  QualType T;
204933642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor  bool Invalid = false;
20506952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor
20516952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor  if (D->isExpandedParameterPack()) {
2052a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    // The non-type template parameter pack is an already-expanded pack
20536952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    // expansion of types. Substitute into each of the expanded types.
20546952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
20556952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
20566952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
20576952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
20586952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                               TemplateArgs,
2059a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                               D->getLocation(),
20606952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                               D->getDeclName());
20616952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      if (!NewDI)
20626bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
2063a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
20646952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
20656952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
20666952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                              D->getLocation());
20676952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      if (NewT.isNull())
20686bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
20696952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      ExpandedParameterPackTypes.push_back(NewT);
20706952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    }
2071a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
20726952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    IsExpandedParameterPack = true;
20736952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    DI = D->getTypeSourceInfo();
20746952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    T = DI->getType();
20756964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  } else if (D->isPackExpansion()) {
20766952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    // The non-type template parameter pack's type is a pack expansion of types.
20776952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    // Determine whether we need to expand this parameter pack into separate
20786952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    // types.
207939e6ab4be93d9c5e729a578ddd9d415cd2d49872David Blaikie    PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
20806952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    TypeLoc Pattern = Expansion.getPatternLoc();
20815f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
20826952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2083a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
20846952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    // Determine whether the set of unexpanded parameter packs can and should
20856952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    // be expanded.
20866952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    bool Expand = true;
20876952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    bool RetainExpansion = false;
2088dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie    Optional<unsigned> OrigNumExpansions
20896952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      = Expansion.getTypePtr()->getNumExpansions();
2090dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie    Optional<unsigned> NumExpansions = OrigNumExpansions;
20916952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
20926952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                Pattern.getSourceRange(),
2093a71f9d0a5e1f8cafdd23a17e292de22fdc8e99ffDavid Blaikie                                                Unexpanded,
20946952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                TemplateArgs,
2095a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                                Expand, RetainExpansion,
20966952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                NumExpansions))
20976bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
2098a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
20996952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    if (Expand) {
21006952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      for (unsigned I = 0; I != *NumExpansions; ++I) {
21016952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
21026952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2103a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                                  D->getLocation(),
21046952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                  D->getDeclName());
21056952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor        if (!NewDI)
21066bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines          return nullptr;
2107a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
21086952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
21096952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor        QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
21106952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                              NewDI->getType(),
21116952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                              D->getLocation());
21126952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor        if (NewT.isNull())
21136bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines          return nullptr;
21146952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor        ExpandedParameterPackTypes.push_back(NewT);
21156952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      }
2116a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
21176952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      // Note that we have an expanded parameter pack. The "type" of this
21186952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      // expanded parameter pack is the original expansion type, but callers
21196952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      // will end up using the expanded parameter pack types for type-checking.
21206952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      IsExpandedParameterPack = true;
21216952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      DI = D->getTypeSourceInfo();
21226952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      T = DI->getType();
21236952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    } else {
21246952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      // We cannot fully expand the pack expansion now, so substitute into the
21256952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      // pattern and create a new pack expansion type.
21266952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
21276952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2128a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                                     D->getLocation(),
21296952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                     D->getDeclName());
21306952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      if (!NewPattern)
21316bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
2132a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
21336952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
21346952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                      NumExpansions);
21356952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      if (!DI)
21366bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
2137a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
21386952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      T = DI->getType();
21396952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    }
21406952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor  } else {
21416952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    // Simple case: substitution into a parameter that is not a parameter pack.
2142a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
21436952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                           D->getLocation(), D->getDeclName());
21446952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    if (!DI)
21456bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
2146a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
21476952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    // Check that this type is acceptable for a non-type template parameter.
2148a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
21496952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                                  D->getLocation());
21506952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    if (T.isNull()) {
21516952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      T = SemaRef.Context.IntTy;
21526952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor      Invalid = true;
21536952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor    }
215433642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor  }
2155a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
21566952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor  NonTypeTemplateParmDecl *Param;
21576952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor  if (IsExpandedParameterPack)
21584967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Param = NonTypeTemplateParmDecl::Create(
21594967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
21604967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        D->getDepth() - TemplateArgs.getNumLevels(), D->getPosition(),
21614967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
21624967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        ExpandedParameterPackTypesAsWritten);
21636952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor  else
2164a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2165ff676cb48fe8bf7be2feaa251dc7c5fb15af4730Abramo Bagnara                                            D->getInnerLocStart(),
21666952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                            D->getLocation(),
2167a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                    D->getDepth() - TemplateArgs.getNumLevels(),
2168a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                            D->getPosition(),
2169a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                            D->getIdentifier(), T,
21706952f1e4256c5b43aee5e98cea4e9b663bd1d413Douglas Gregor                                            D->isParameterPack(), DI);
2171a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
21729a299e0575ce235f491014627c7267e2d2cd73deDouglas Gregor  Param->setAccess(AS_public);
217333642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor  if (Invalid)
217433642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor    Param->setInvalidDecl();
2175a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
217687d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
21774967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
21784967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                                       Sema::ConstantEvaluated);
21799d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer    ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
21809d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer    if (!Value.isInvalid())
2181b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      Param->setDefaultArgument(Value.get());
21829d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer  }
2183a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
2184a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  // Introduce this template parameter's instantiation into the instantiation
2185550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // scope.
2186550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
218733642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor  return Param;
218833642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor}
218933642df30088f2ddb0b22c609523ab8df9dff595Douglas Gregor
21906964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smithstatic void collectUnexpandedParameterPacks(
21916964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    Sema &S,
21926964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    TemplateParameterList *Params,
21936964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
219487d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  for (const auto &P : *Params) {
219587d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    if (P->isTemplateParameterPack())
21966964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      continue;
219787d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
21986964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
21996964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                        Unexpanded);
220087d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
22016964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
22026964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                      Unexpanded);
22036964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  }
22046964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith}
22056964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith
22060dde18e5a713bc186062ca1ebc9967500b07faeeAnders CarlssonDecl *
22079106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas GregorTemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
22089106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor                                                  TemplateTemplateParmDecl *D) {
22099106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor  // Instantiate the template parameter list of the template template parameter.
22109106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor  TemplateParameterList *TempParams = D->getTemplateParameters();
22119106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor  TemplateParameterList *InstParams;
22126964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  SmallVector<TemplateParameterList*, 8> ExpandedParams;
22136964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith
22146964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  bool IsExpandedParameterPack = false;
22156964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith
22166964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  if (D->isExpandedParameterPack()) {
22176964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    // The template template parameter pack is an already-expanded pack
22186964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    // expansion of template parameters. Substitute into each of the expanded
22196964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    // parameters.
22206964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
22216964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
22226964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith         I != N; ++I) {
22236964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      LocalInstantiationScope Scope(SemaRef);
22246964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      TemplateParameterList *Expansion =
22256964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith        SubstTemplateParams(D->getExpansionTemplateParameters(I));
22266964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      if (!Expansion)
22276bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
22286964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      ExpandedParams.push_back(Expansion);
22296964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    }
22306964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith
22316964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    IsExpandedParameterPack = true;
22326964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    InstParams = TempParams;
22336964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  } else if (D->isPackExpansion()) {
22346964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    // The template template parameter pack expands to a pack of template
22356964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    // template parameters. Determine whether we need to expand this parameter
22366964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    // pack into separate parameters.
22376964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
22386964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
22396964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                    Unexpanded);
22406964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith
22416964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    // Determine whether the set of unexpanded parameter packs can and should
22426964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    // be expanded.
22436964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    bool Expand = true;
22446964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    bool RetainExpansion = false;
2245dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie    Optional<unsigned> NumExpansions;
22466964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
22476964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                                TempParams->getSourceRange(),
22486964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                                Unexpanded,
22496964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                                TemplateArgs,
22506964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                                Expand, RetainExpansion,
22516964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                                NumExpansions))
22526bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
22536964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith
22546964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    if (Expand) {
22556964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      for (unsigned I = 0; I != *NumExpansions; ++I) {
22566964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
22576964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith        LocalInstantiationScope Scope(SemaRef);
22586964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith        TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
22596964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith        if (!Expansion)
22606bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines          return nullptr;
22616964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith        ExpandedParams.push_back(Expansion);
22626964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      }
22636964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith
22646964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      // Note that we have an expanded parameter pack. The "type" of this
22656964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      // expanded parameter pack is the original expansion type, but callers
22666964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      // will end up using the expanded parameter pack types for type-checking.
22676964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      IsExpandedParameterPack = true;
22686964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      InstParams = TempParams;
22696964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    } else {
22706964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      // We cannot fully expand the pack expansion now, so just substitute
22716964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      // into the pattern.
22726964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
22736964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith
22746964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      LocalInstantiationScope Scope(SemaRef);
22756964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      InstParams = SubstTemplateParams(TempParams);
22766964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith      if (!InstParams)
22776bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        return nullptr;
22786964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    }
22796964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  } else {
22809106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor    // Perform the actual substitution of template parameters within a new,
22819106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor    // local instantiation scope.
22822a7fb27913999d132cf9e10e03dc5271faa2e9d3John McCall    LocalInstantiationScope Scope(SemaRef);
22839106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor    InstParams = SubstTemplateParams(TempParams);
22849106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor    if (!InstParams)
22856bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
2286a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  }
2287a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
22889106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor  // Build the template template parameter.
22896964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  TemplateTemplateParmDecl *Param;
22906964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  if (IsExpandedParameterPack)
22916964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
22926964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                             D->getLocation(),
22936964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                   D->getDepth() - TemplateArgs.getNumLevels(),
22946964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                             D->getPosition(),
22956964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                             D->getIdentifier(), InstParams,
22966964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                             ExpandedParams);
22976964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith  else
22986964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith    Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
22996964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                             D->getLocation(),
2300a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                   D->getDepth() - TemplateArgs.getNumLevels(),
23016964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                             D->getPosition(),
23026964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                             D->isParameterPack(),
23036964b3f80ce1ba489e7e25e7cd58062699af9b0cRichard Smith                                             D->getIdentifier(), InstParams);
230487d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
23059d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer    NestedNameSpecifierLoc QualifierLoc =
23069d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer        D->getDefaultArgument().getTemplateQualifierLoc();
23079d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer    QualifierLoc =
23089d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer        SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
23099d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer    TemplateName TName = SemaRef.SubstTemplateName(
23109d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer        QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
23119d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer        D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
23129d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer    if (!TName.isNull())
23139d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer      Param->setDefaultArgument(
2314b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar          SemaRef.Context,
23159d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer          TemplateArgumentLoc(TemplateArgument(TName),
23169d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer                              D->getDefaultArgument().getTemplateQualifierLoc(),
2317b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar                              D->getDefaultArgument().getTemplateNameLoc()));
23189d57b8dea3b139dc2e2976ffccef50c74ac03873David Majnemer  }
23199a299e0575ce235f491014627c7267e2d2cd73deDouglas Gregor  Param->setAccess(AS_public);
2320a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
2321a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  // Introduce this template parameter's instantiation into the instantiation
23229106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor  // scope.
23239106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2324a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
23259106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor  return Param;
23269106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor}
23279106ef78f8fcc9df1a60c7a5b64c7d967194207eDouglas Gregor
232848c32a7e7c977f317dc1dc19524c2f54d29c7270Douglas GregorDecl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2329db9924191092b4d426cc066637d81698211846aaDouglas Gregor  // Using directives are never dependent (and never contain any types or
2330db9924191092b4d426cc066637d81698211846aaDouglas Gregor  // expressions), so they require no explicit instantiation work.
2331a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
233248c32a7e7c977f317dc1dc19524c2f54d29c7270Douglas Gregor  UsingDirectiveDecl *Inst
233348c32a7e7c977f317dc1dc19524c2f54d29c7270Douglas Gregor    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2334a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                 D->getNamespaceKeyLocation(),
2335db9924191092b4d426cc066637d81698211846aaDouglas Gregor                                 D->getQualifierLoc(),
2336a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                 D->getIdentLocation(),
2337a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                 D->getNominatedNamespace(),
233848c32a7e7c977f317dc1dc19524c2f54d29c7270Douglas Gregor                                 D->getCommonAncestor());
2339536afbeb5609db87d98da8402ed0fd58f61f5d3aAbramo Bagnara
2340536afbeb5609db87d98da8402ed0fd58f61f5d3aAbramo Bagnara  // Add the using directive to its declaration context
2341536afbeb5609db87d98da8402ed0fd58f61f5d3aAbramo Bagnara  // only if this is not a function or method.
2342536afbeb5609db87d98da8402ed0fd58f61f5d3aAbramo Bagnara  if (!Owner->isFunctionOrMethod())
2343536afbeb5609db87d98da8402ed0fd58f61f5d3aAbramo Bagnara    Owner->addDecl(Inst);
2344536afbeb5609db87d98da8402ed0fd58f61f5d3aAbramo Bagnara
234548c32a7e7c977f317dc1dc19524c2f54d29c7270Douglas Gregor  return Inst;
234648c32a7e7c977f317dc1dc19524c2f54d29c7270Douglas Gregor}
234748c32a7e7c977f317dc1dc19524c2f54d29c7270Douglas Gregor
2348ed97649e9574b9d854fa4d6109c9333ae0993554John McCallDecl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
23491b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor
23501b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor  // The nested name specifier may be dependent, for example
23511b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor  //     template <typename T> struct t {
23521b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor  //       struct s1 { T f1(); };
23531b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor  //       struct s2 : s1 { using s1::f1; };
23541b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor  //     };
23551b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor  //     template struct t<int>;
23561b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor  // Here, in using s1::f1, s1 refers to t<T>::s1;
23571b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor  // we need to substitute for t<int>::s1.
23585149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  NestedNameSpecifierLoc QualifierLoc
23595149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
23605149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor                                          TemplateArgs);
23615149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  if (!QualifierLoc)
23626bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
23631b398205267ea69f35230eea50e0225db22ebb7eDouglas Gregor
23644967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // For an inheriting constructor declaration, the name of the using
23654967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // declaration is the name of a constructor in this class, not in the
23664967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // base class.
2367ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara  DeclarationNameInfo NameInfo = D->getNameInfo();
23684967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
23694967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
23704967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
23714967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2372ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
23739f54ad4381370c6b771424b53d219e661d6d6706John McCall  // We only need to do redeclaration lookups if we're in a class
23749f54ad4381370c6b771424b53d219e661d6d6706John McCall  // scope (in fact, it's not really even possible in non-class
23759f54ad4381370c6b771424b53d219e661d6d6706John McCall  // scopes).
23769f54ad4381370c6b771424b53d219e661d6d6706John McCall  bool CheckRedeclaration = Owner->isRecord();
23779f54ad4381370c6b771424b53d219e661d6d6706John McCall
2378ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2379ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara                    Sema::ForRedeclaration);
23809f54ad4381370c6b771424b53d219e661d6d6706John McCall
2381ed97649e9574b9d854fa4d6109c9333ae0993554John McCall  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
23828d030c7a6f36438f6c7dd977f8be0de0cc781ad5Enea Zaffanella                                       D->getUsingLoc(),
23835149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor                                       QualifierLoc,
2384ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara                                       NameInfo,
23858d030c7a6f36438f6c7dd977f8be0de0cc781ad5Enea Zaffanella                                       D->hasTypename());
2386ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
23875149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  CXXScopeSpec SS;
23885149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  SS.Adopt(QualifierLoc);
23899f54ad4381370c6b771424b53d219e661d6d6706John McCall  if (CheckRedeclaration) {
23909f54ad4381370c6b771424b53d219e661d6d6706John McCall    Prev.setHideTags(false);
23919f54ad4381370c6b771424b53d219e661d6d6706John McCall    SemaRef.LookupQualifiedName(Prev, Owner);
23929f54ad4381370c6b771424b53d219e661d6d6706John McCall
23939f54ad4381370c6b771424b53d219e661d6d6706John McCall    // Check for invalid redeclarations.
23948d030c7a6f36438f6c7dd977f8be0de0cc781ad5Enea Zaffanella    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
23958d030c7a6f36438f6c7dd977f8be0de0cc781ad5Enea Zaffanella                                            D->hasTypename(), SS,
23969f54ad4381370c6b771424b53d219e661d6d6706John McCall                                            D->getLocation(), Prev))
23979f54ad4381370c6b771424b53d219e661d6d6706John McCall      NewUD->setInvalidDecl();
23989f54ad4381370c6b771424b53d219e661d6d6706John McCall
23999f54ad4381370c6b771424b53d219e661d6d6706John McCall  }
24009f54ad4381370c6b771424b53d219e661d6d6706John McCall
24019f54ad4381370c6b771424b53d219e661d6d6706John McCall  if (!NewUD->isInvalidDecl() &&
2402651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
2403ed97649e9574b9d854fa4d6109c9333ae0993554John McCall                                      D->getLocation()))
2404ed97649e9574b9d854fa4d6109c9333ae0993554John McCall    NewUD->setInvalidDecl();
24059f54ad4381370c6b771424b53d219e661d6d6706John McCall
2406ed97649e9574b9d854fa4d6109c9333ae0993554John McCall  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2407ed97649e9574b9d854fa4d6109c9333ae0993554John McCall  NewUD->setAccess(D->getAccess());
2408ed97649e9574b9d854fa4d6109c9333ae0993554John McCall  Owner->addDecl(NewUD);
2409ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
24109f54ad4381370c6b771424b53d219e661d6d6706John McCall  // Don't process the shadow decls for an invalid decl.
24119f54ad4381370c6b771424b53d219e661d6d6706John McCall  if (NewUD->isInvalidDecl())
24129f54ad4381370c6b771424b53d219e661d6d6706John McCall    return NewUD;
24139f54ad4381370c6b771424b53d219e661d6d6706John McCall
24144967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
24156bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2416c5a89a1cc2f168ad0a115c560b8de5f1c952d8c5Richard Smith
2417323c310efa0abd7a786b0303501186b5f33eb8d7John McCall  bool isFunctionScope = Owner->isFunctionOrMethod();
2418323c310efa0abd7a786b0303501186b5f33eb8d7John McCall
24199f54ad4381370c6b771424b53d219e661d6d6706John McCall  // Process the shadow decls.
2420651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  for (auto *Shadow : D->shadows()) {
24214967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
24224967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    // reconstruct it in the case where it matters.
24234967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    NamedDecl *OldTarget = Shadow->getTargetDecl();
24244967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
24254967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
24264967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        OldTarget = BaseShadow;
24274967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
24289f54ad4381370c6b771424b53d219e661d6d6706John McCall    NamedDecl *InstTarget =
2429f06a2893bc9778857295c64ee32b4a899a338480Richard Smith        cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
24304967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar            Shadow->getLocation(), OldTarget, TemplateArgs));
2431b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor    if (!InstTarget)
24326bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
24339f54ad4381370c6b771424b53d219e661d6d6706John McCall
24346bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    UsingShadowDecl *PrevDecl = nullptr;
2435f06a2893bc9778857295c64ee32b4a899a338480Richard Smith    if (CheckRedeclaration) {
2436f06a2893bc9778857295c64ee32b4a899a338480Richard Smith      if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2437f06a2893bc9778857295c64ee32b4a899a338480Richard Smith        continue;
2438176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    } else if (UsingShadowDecl *OldPrev =
2439176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                   getPreviousDeclForInstantiation(Shadow)) {
2440f06a2893bc9778857295c64ee32b4a899a338480Richard Smith      PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2441f06a2893bc9778857295c64ee32b4a899a338480Richard Smith          Shadow->getLocation(), OldPrev, TemplateArgs));
2442f06a2893bc9778857295c64ee32b4a899a338480Richard Smith    }
24439f54ad4381370c6b771424b53d219e661d6d6706John McCall
2444f06a2893bc9778857295c64ee32b4a899a338480Richard Smith    UsingShadowDecl *InstShadow =
24456bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
24466bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                     PrevDecl);
24479f54ad4381370c6b771424b53d219e661d6d6706John McCall    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2448323c310efa0abd7a786b0303501186b5f33eb8d7John McCall
2449323c310efa0abd7a786b0303501186b5f33eb8d7John McCall    if (isFunctionScope)
2450323c310efa0abd7a786b0303501186b5f33eb8d7John McCall      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
24519f54ad4381370c6b771424b53d219e661d6d6706John McCall  }
2452ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
2453ed97649e9574b9d854fa4d6109c9333ae0993554John McCall  return NewUD;
2454ed97649e9574b9d854fa4d6109c9333ae0993554John McCall}
2455ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
2456ed97649e9574b9d854fa4d6109c9333ae0993554John McCallDecl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
24579f54ad4381370c6b771424b53d219e661d6d6706John McCall  // Ignore these;  we handle them in bulk when processing the UsingDecl.
24586bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  return nullptr;
2459ed97649e9574b9d854fa4d6109c9333ae0993554John McCall}
2460ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
24614967a710c84587c654b56c828382219c3937dacbPirama Arumuga NainarDecl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
24624967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    ConstructorUsingShadowDecl *D) {
24634967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // Ignore these;  we handle them in bulk when processing the UsingDecl.
24644967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  return nullptr;
24654967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar}
24664967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
24677ba107a1863ddfa1664555854f0d7bdb3c491c92John McCallDecl * TemplateDeclInstantiator
24687ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall    ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
24695149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  NestedNameSpecifierLoc QualifierLoc
2470a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
24715149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor                                          TemplateArgs);
24725149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  if (!QualifierLoc)
24736bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
24747ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall
24757ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall  CXXScopeSpec SS;
24765149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  SS.Adopt(QualifierLoc);
24777ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall
2478ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara  // Since NameInfo refers to a typename, it cannot be a C++ special name.
2479accaf19bc1129c0273ec50dba52318e60bc29103Benjamin Kramer  // Hence, no transformation is required for it.
2480ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara  DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
24817ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall  NamedDecl *UD =
24826bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
24836bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                  D->getUsingLoc(), SS, NameInfo, nullptr,
24847ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall                                  /*instantiation*/ true,
24857ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall                                  /*typename*/ true, D->getTypenameLoc());
24864469e8a97cdca3725b4f8f366916143113c029acDouglas Gregor  if (UD)
2487ed97649e9574b9d854fa4d6109c9333ae0993554John McCall    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2488ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
24897ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall  return UD;
24907ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall}
24917ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall
24927ba107a1863ddfa1664555854f0d7bdb3c491c92John McCallDecl * TemplateDeclInstantiator
24937ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall    ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
24945149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  NestedNameSpecifierLoc QualifierLoc
24955149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor      = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
24965149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  if (!QualifierLoc)
24976bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2498a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
24990dde18e5a713bc186062ca1ebc9967500b07faeeAnders Carlsson  CXXScopeSpec SS;
25005149f37cfc736d03233bf92b5ba7c6e866c6647bDouglas Gregor  SS.Adopt(QualifierLoc);
25011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
2502ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara  DeclarationNameInfo NameInfo
2503ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2504ef3dce817d43faadbf21ce9102d33a9d84b02e09Abramo Bagnara
25051eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  NamedDecl *UD =
25066bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
25076bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                  D->getUsingLoc(), SS, NameInfo, nullptr,
25087ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall                                  /*instantiation*/ true,
25097ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall                                  /*typename*/ false, SourceLocation());
25104469e8a97cdca3725b4f8f366916143113c029acDouglas Gregor  if (UD)
2511ed97649e9574b9d854fa4d6109c9333ae0993554John McCall    SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2512ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
25130d8df780aef1acda5962347a32591efc629b6748Anders Carlsson  return UD;
25140dde18e5a713bc186062ca1ebc9967500b07faeeAnders Carlsson}
25150dde18e5a713bc186062ca1ebc9967500b07faeeAnders Carlsson
2516af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet
2517af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois PichetDecl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2518af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet                                     ClassScopeFunctionSpecializationDecl *Decl) {
2519af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  CXXMethodDecl *OldFD = Decl->getSpecialization();
25200e2c34f92f00628d48968dfea096d36381f494cbStephen Hines  CXXMethodDecl *NewFD =
25210e2c34f92f00628d48968dfea096d36381f494cbStephen Hines    cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
25220e2c34f92f00628d48968dfea096d36381f494cbStephen Hines  if (!NewFD)
25230e2c34f92f00628d48968dfea096d36381f494cbStephen Hines    return nullptr;
2524af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet
2525af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2526af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet                        Sema::ForRedeclaration);
2527af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet
25286b02009359a462ffe633696a4441313b462e6566Nico Weber  TemplateArgumentListInfo TemplateArgs;
25296bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
25306b02009359a462ffe633696a4441313b462e6566Nico Weber  if (Decl->hasExplicitTemplateArgs()) {
25316b02009359a462ffe633696a4441313b462e6566Nico Weber    TemplateArgs = Decl->templateArgs();
25326b02009359a462ffe633696a4441313b462e6566Nico Weber    TemplateArgsPtr = &TemplateArgs;
25336b02009359a462ffe633696a4441313b462e6566Nico Weber  }
25346b02009359a462ffe633696a4441313b462e6566Nico Weber
2535af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
25366b02009359a462ffe633696a4441313b462e6566Nico Weber  if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
25376b02009359a462ffe633696a4441313b462e6566Nico Weber                                                  Previous)) {
2538af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet    NewFD->setInvalidDecl();
2539af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet    return NewFD;
2540af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  }
2541af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet
2542af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  // Associate the specialization with the pattern.
2543af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2544af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  assert(Specialization && "Class scope Specialization is null");
2545af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2546af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet
2547af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  return NewFD;
2548af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet}
2549af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet
2550c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey BataevDecl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2551c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev                                     OMPThreadPrivateDecl *D) {
25526af701f29be43e49a25ab098c79940ae4cbb69c7Alexey Bataev  SmallVector<Expr *, 5> Vars;
2553651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  for (auto *I : D->varlists()) {
2554c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2555c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev    assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
25566af701f29be43e49a25ab098c79940ae4cbb69c7Alexey Bataev    Vars.push_back(Var);
2557c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev  }
2558c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev
2559c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev  OMPThreadPrivateDecl *TD =
2560c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev    SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2561c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev
2562651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  TD->setAccess(AS_public);
2563651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  Owner->addDecl(TD);
2564651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
2565c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev  return TD;
2566c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev}
2567c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev
25684967a710c84587c654b56c828382219c3937dacbPirama Arumuga NainarDecl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
25694967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    OMPDeclareReductionDecl *D) {
25704967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // Instantiate type and check if it is allowed.
25714967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  QualType SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
25724967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      D->getLocation(),
25734967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
25744967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                         D->getLocation(), DeclarationName())));
25754967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (SubstReductionType.isNull())
25764967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    return nullptr;
25774967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  bool IsCorrect = !SubstReductionType.isNull();
25784967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // Create instantiated copy.
25794967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  std::pair<QualType, SourceLocation> ReductionTypes[] = {
25804967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      std::make_pair(SubstReductionType, D->getLocation())};
25814967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  auto *PrevDeclInScope = D->getPrevDeclInScope();
25824967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
25834967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    PrevDeclInScope = cast<OMPDeclareReductionDecl>(
25844967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
25854967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar            ->get<Decl *>());
25864967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  }
25874967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
25884967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
25894967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      PrevDeclInScope);
25904967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
25914967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (isDeclWithinFunction(NewDRD))
25924967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
25934967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  Expr *SubstCombiner = nullptr;
25944967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  Expr *SubstInitializer = nullptr;
25954967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // Combiners instantiation sequence.
25964967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (D->getCombiner()) {
25974967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
25984967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        /*S=*/nullptr, NewDRD);
25994967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    const char *Names[] = {"omp_in", "omp_out"};
26004967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    for (auto &Name : Names) {
26014967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      DeclarationName DN(&SemaRef.Context.Idents.get(Name));
26024967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      auto OldLookup = D->lookup(DN);
26034967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      auto Lookup = NewDRD->lookup(DN);
26044967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      if (!OldLookup.empty() && !Lookup.empty()) {
26054967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        assert(Lookup.size() == 1 && OldLookup.size() == 1);
26064967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldLookup.front(),
26074967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                                             Lookup.front());
26084967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      }
26094967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    }
26104967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
26114967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
26124967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    // Initializers instantiation sequence.
26134967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (D->getInitializer()) {
26144967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
26154967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          /*S=*/nullptr, NewDRD);
26164967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      const char *Names[] = {"omp_orig", "omp_priv"};
26174967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      for (auto &Name : Names) {
26184967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        DeclarationName DN(&SemaRef.Context.Idents.get(Name));
26194967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        auto OldLookup = D->lookup(DN);
26204967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        auto Lookup = NewDRD->lookup(DN);
26214967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        if (!OldLookup.empty() && !Lookup.empty()) {
26224967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          assert(Lookup.size() == 1 && OldLookup.size() == 1);
26234967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          SemaRef.CurrentInstantiationScope->InstantiatedLocal(
26244967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar              OldLookup.front(), Lookup.front());
26254967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        }
26264967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      }
26274967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      SubstInitializer =
26284967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
26294967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD,
26304967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                                        SubstInitializer);
26314967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    }
26324967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    IsCorrect = IsCorrect && SubstCombiner &&
26334967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                (!D->getInitializer() || SubstInitializer);
26344967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  } else
26354967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    IsCorrect = false;
26364967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
26374967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
26384967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                                        IsCorrect);
26394967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
26404967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  return NewDRD;
26414967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar}
26424967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
26434967a710c84587c654b56c828382219c3937dacbPirama Arumuga NainarDecl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
26444967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    OMPCapturedExprDecl * /*D*/) {
26454967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  llvm_unreachable("Should not be met in templates");
26464967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar}
26474967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
2648ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanDecl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
26496bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  return VisitFunctionDecl(D, nullptr);
2650ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman}
2651ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman
2652ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanDecl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
26536bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  return VisitCXXMethodDecl(D, nullptr);
2654ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman}
2655ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman
2656ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanDecl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2657ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman  llvm_unreachable("There are only CXXRecordDecls in C++");
2658ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman}
2659ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman
2660ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanDecl *
2661ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanTemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2662ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman    ClassTemplateSpecializationDecl *D) {
2663b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // As a MS extension, we permit class-scope explicit specialization
2664b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // of member class templates.
2665b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2666b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  assert(ClassTemplate->getDeclContext()->isRecord() &&
2667b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling         D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2668b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling         "can only instantiate an explicit specialization "
2669b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling         "for a member class template");
2670b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2671b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Lookup the already-instantiated declaration in the instantiation
2672b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // of the class template. FIXME: Diagnose or assert if this fails?
2673b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  DeclContext::lookup_result Found
2674b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling    = Owner->lookup(ClassTemplate->getDeclName());
2675b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (Found.empty())
26766bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2677b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  ClassTemplateDecl *InstClassTemplate
2678b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling    = dyn_cast<ClassTemplateDecl>(Found.front());
2679b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (!InstClassTemplate)
26806bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2681b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2682b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Substitute into the template arguments of the class template explicit
2683b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // specialization.
2684b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2685b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                        castAs<TemplateSpecializationTypeLoc>();
2686b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2687b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                            Loc.getRAngleLoc());
2688b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2689b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2690b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling    ArgLocs.push_back(Loc.getArgLoc(I));
2691b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2692b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                    InstTemplateArgs, TemplateArgs))
26936bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2694b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2695b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Check that the template argument list is well-formed for this
2696b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // class template.
2697b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  SmallVector<TemplateArgument, 4> Converted;
2698b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2699b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                        D->getLocation(),
2700b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                        InstTemplateArgs,
2701b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                        false,
2702b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                        Converted))
27036bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2704b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2705b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Figure out where to insert this class template explicit specialization
2706b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // in the member template's set of class template explicit specializations.
27076bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  void *InsertPos = nullptr;
2708b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  ClassTemplateSpecializationDecl *PrevDecl =
2709c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      InstClassTemplate->findSpecialization(Converted, InsertPos);
2710b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2711b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Check whether we've already seen a conflicting instantiation of this
2712b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // declaration (for instance, if there was a prior implicit instantiation).
2713b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  bool Ignored;
2714b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (PrevDecl &&
2715b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling      SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2716b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                                     D->getSpecializationKind(),
2717b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                                     PrevDecl,
2718b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                                     PrevDecl->getSpecializationKind(),
2719b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                                     PrevDecl->getPointOfInstantiation(),
2720b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                                     Ignored))
27216bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2722b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2723b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // If PrevDecl was a definition and D is also a definition, diagnose.
2724b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // This happens in cases like:
2725b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //
2726b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //   template<typename T, typename U>
2727b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //   struct Outer {
2728b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //     template<typename X> struct Inner;
2729b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //     template<> struct Inner<T> {};
2730b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //     template<> struct Inner<U> {};
2731b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //   };
2732b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //
2733b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //   Outer<int, int> outer; // error: the explicit specializations of Inner
2734b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  //                          // have the same signature.
2735b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (PrevDecl && PrevDecl->getDefinition() &&
2736b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling      D->isThisDeclarationADefinition()) {
2737b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling    SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2738b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling    SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2739b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                 diag::note_previous_definition);
27406bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2741b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  }
2742b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2743b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Create the class template partial specialization declaration.
2744b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  ClassTemplateSpecializationDecl *InstD
2745b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling    = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2746b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                              D->getTagKind(),
2747b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                              Owner,
2748b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                              D->getLocStart(),
2749b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                              D->getLocation(),
2750b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                              InstClassTemplate,
27514967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                              Converted,
2752b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                                              PrevDecl);
2753b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2754b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Add this partial specialization to the set of class template partial
2755b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // specializations.
2756b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (!PrevDecl)
2757b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling    InstClassTemplate->AddSpecialization(InstD, InsertPos);
2758b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2759b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Substitute the nested name specifier, if any.
2760b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (SubstQualifier(D, InstD))
27616bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2762b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2763b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Build the canonical type that describes the converted template
2764b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // arguments of the class template explicit specialization.
2765b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
27664967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      TemplateName(InstClassTemplate), Converted,
2767b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling      SemaRef.Context.getRecordType(InstD));
2768b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2769b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Build the fully-sugared type for this class template
2770b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // specialization as the user wrote in the specialization
2771b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // itself. This means that we'll pretty-print the type retrieved
2772b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // from the specialization's declaration the way that the user
2773b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // actually wrote the specialization, rather than formatting the
2774b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // name based on the "canonical" representation used to store the
2775b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // template arguments in the specialization.
2776b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2777b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling      TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2778b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling      CanonType);
2779b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2780b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  InstD->setAccess(D->getAccess());
2781b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2782b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  InstD->setSpecializationKind(D->getSpecializationKind());
2783b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  InstD->setTypeAsWritten(WrittenTy);
2784b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  InstD->setExternLoc(D->getExternLoc());
2785b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2786b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2787b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  Owner->addDecl(InstD);
2788b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2789b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // Instantiate the members of the class-scope explicit specialization eagerly.
2790b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // We don't have support for lazy instantiation of an explicit specialization
2791b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  // yet, and MSVC eagerly instantiates in this case.
2792b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  if (D->isThisDeclarationADefinition() &&
2793b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling      SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2794b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                               TSK_ImplicitInstantiation,
2795b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling                               /*Complain=*/true))
27966bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2797b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling
2798b3617be53923ac3e5885ff5001aa748bd0223102Bill Wendling  return InstD;
2799ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman}
2800ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman
2801ef4579cda09b73e3d4d98af48201da25adc29326Larisse VoufoDecl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2802ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarTemplateSpecializationDecl *D) {
2803ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2804ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TemplateArgumentListInfo VarTemplateArgsInfo;
2805ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2806ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  assert(VarTemplate &&
2807ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo         "A template specialization without specialized template?");
2808ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2809ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Substitute the current template arguments.
2810ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2811ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2812ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2813ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2814ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2815ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                    TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
28166bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2817ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2818ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Check that the template argument list is well-formed for this template.
2819ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  SmallVector<TemplateArgument, 4> Converted;
2820ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (SemaRef.CheckTemplateArgumentList(
2821ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo          VarTemplate, VarTemplate->getLocStart(),
2822ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo          const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2823651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines          Converted))
28246bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2825ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2826ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Find the variable template specialization declaration that
2827ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // corresponds to these arguments.
28286bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  void *InsertPos = nullptr;
2829ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2830c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines          Converted, InsertPos))
2831ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // If we already have a variable template specialization, return it.
2832ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    return VarSpec;
2833ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2834ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2835ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                                            VarTemplateArgsInfo, Converted);
2836ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
2837ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2838ef4579cda09b73e3d4d98af48201da25adc29326Larisse VoufoDecl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2839ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2840ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    const TemplateArgumentListInfo &TemplateArgsInfo,
2841c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    ArrayRef<TemplateArgument> Converted) {
2842ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2843ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Do substitution on the type of the declaration
2844ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TypeSourceInfo *DI =
2845ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2846ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                        D->getTypeSpecStartLoc(), D->getDeclName());
2847ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (!DI)
28486bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2849ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2850ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (DI->getType()->isFunctionType()) {
2851ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2852ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        << D->isStaticDataMember() << DI->getType();
28536bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2854ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
2855ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2856ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Build the instantiated declaration
2857ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2858ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
28594967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
2860ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  Var->setTemplateArgsInfo(TemplateArgsInfo);
2861d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  if (InsertPos)
2862d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    VarTemplate->AddSpecialization(Var, InsertPos);
2863ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2864ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Substitute the nested name specifier, if any.
2865ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (SubstQualifier(D, Var))
28666bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2867ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2868ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2869a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith                                     Owner, StartingScope);
2870ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2871ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  return Var;
2872ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
2873ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
2874ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanDecl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2875ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman  llvm_unreachable("@defs is not supported in Objective-C++");
2876ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman}
2877ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman
2878ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanDecl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2879ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman  // FIXME: We need to be able to instantiate FriendTemplateDecls.
2880ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2881ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman                                               DiagnosticsEngine::Error,
2882ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman                                               "cannot instantiate %0 yet");
2883ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman  SemaRef.Diag(D->getLocation(), DiagID)
2884ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman    << D->getDeclKindName();
2885ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman
28866bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  return nullptr;
2887ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman}
2888ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman
2889ded9979a2997336cee8797deb6bb3194fccc2068Eli FriedmanDecl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2890ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman  llvm_unreachable("Unexpected decl");
2891ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman}
2892ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman
2893ce3ff2bd3a3386dbc209d3cba4b8769173b274c1John McCallDecl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2894d6350aefb1396b299e199c7f1fe51bb40c12e75eDouglas Gregor                      const MultiLevelTemplateArgumentList &TemplateArgs) {
28957e06390f8a60440d6fc5f0e633acdc2edd8ee924Douglas Gregor  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
28962fa98001f832836e3f652c211a9d2f80501d659aDouglas Gregor  if (D->isInvalidDecl())
28976bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
28982fa98001f832836e3f652c211a9d2f80501d659aDouglas Gregor
28998dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor  return Instantiator.Visit(D);
29008dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor}
29018dbc2694424b4e842b1d5ea39744a137b58600c3Douglas Gregor
2902e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall/// \brief Instantiates a nested template parameter list in the current
2903e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall/// instantiation context.
2904e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall///
2905e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall/// \param L The parameter list to instantiate
2906e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall///
2907e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall/// \returns NULL if there was an error
2908e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCallTemplateParameterList *
2909ce3ff2bd3a3386dbc209d3cba4b8769173b274c1John McCallTemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2910e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  // Get errors for all the parameters before bailing out.
2911e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  bool Invalid = false;
2912e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
2913e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  unsigned N = L->size();
29145f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  typedef SmallVector<NamedDecl *, 8> ParamVector;
2915e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  ParamVector Params;
2916e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  Params.reserve(N);
291787d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar  for (auto &P : *L) {
291887d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
2919e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall    Params.push_back(D);
29209148c3f5829f4d031249faeb1043e7be914539e8Douglas Gregor    Invalid = Invalid || !D || D->isInvalidDecl();
2921e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  }
2922e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
2923e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  // Clean up if we had an error.
2924ff331c15729f7d4439d253c97f4d60f2a7ffd0c6Douglas Gregor  if (Invalid)
29256bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2926e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
2927e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  TemplateParameterList *InstL
2928e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
29294967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                    L->getLAngleLoc(), Params,
2930e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall                                    L->getRAngleLoc());
2931e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall  return InstL;
29321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump}
2933e29ba20148e9b7835ad463b39cd4ee9223eafbbfJohn McCall
2934a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi/// \brief Instantiate the declaration of a class template partial
2935ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor/// specialization.
2936ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor///
2937ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor/// \param ClassTemplate the (instantiated) class template that is partially
2938ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor// specialized by the instantiation of \p PartialSpec.
2939ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor///
2940a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi/// \param PartialSpec the (uninstantiated) class template partial
2941ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor/// specialization that we are instantiating.
2942ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor///
2943d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor/// \returns The instantiated partial specialization, if successful; otherwise,
2944d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor/// NULL to indicate an error.
2945d65587f7a6d38965fa37158d3f57990a7faf3836Douglas GregorClassTemplatePartialSpecializationDecl *
2946ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas GregorTemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2947ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                                            ClassTemplateDecl *ClassTemplate,
2948ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
2949550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // Create a local instantiation scope for this class template partial
2950550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // specialization, which will contain the instantiations of the template
2951550d9b28fd586db541eb6dd36f3c10d114e483d8Douglas Gregor  // parameters.
29522a7fb27913999d132cf9e10e03dc5271faa2e9d3John McCall  LocalInstantiationScope Scope(SemaRef);
2953a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
2954ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Substitute into the template parameters of the class template partial
2955ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // specialization.
2956ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2957ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2958ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  if (!InstParams)
29596bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2960a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
2961ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Substitute into the template arguments of the class template partial
2962ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // specialization.
2963c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella  const ASTTemplateArgumentListInfo *TemplArgInfo
2964c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella    = PartialSpec->getTemplateArgsAsWritten();
2965c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2966c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella                                            TemplArgInfo->RAngleLoc);
2967c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2968c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella                    TemplArgInfo->NumTemplateArgs,
2969e02e26293cf8e3bad1059b39cea75c6582896da6Douglas Gregor                    InstTemplateArgs, TemplateArgs))
29706bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2971a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
2972ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Check that the template argument list is well-formed for this
2973ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // class template.
29745f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner  SmallVector<TemplateArgument, 4> Converted;
2975a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2976ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                                        PartialSpec->getLocation(),
2977a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                        InstTemplateArgs,
2978ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                                        false,
2979ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                                        Converted))
29806bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
2981ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor
2982ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Figure out where to insert this class template partial specialization
2983ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // in the member template's set of class template partial specializations.
29846bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  void *InsertPos = nullptr;
2985ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  ClassTemplateSpecializationDecl *PrevDecl
2986c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
2987a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
2988ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Build the canonical type that describes the converted template
2989ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // arguments of the class template partial specialization.
2990a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  QualType CanonType
2991ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
29924967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                                    Converted);
2993ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor
2994ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Build the fully-sugared type for this class template
2995ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // specialization as the user wrote in the specialization
2996ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // itself. This means that we'll pretty-print the type retrieved
2997ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // from the specialization's declaration the way that the user
2998ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // actually wrote the specialization, rather than formatting the
2999ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // name based on the "canonical" representation used to store the
3000ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // template arguments in the specialization.
30013cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall  TypeSourceInfo *WrittenTy
30023cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall    = SemaRef.Context.getTemplateSpecializationTypeInfo(
30033cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall                                                    TemplateName(ClassTemplate),
30043cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall                                                    PartialSpec->getLocation(),
3005d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall                                                    InstTemplateArgs,
3006ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                                                    CanonType);
3007a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
3008ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  if (PrevDecl) {
3009ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    // We've already seen a partial specialization with the same template
3010ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    // parameters and template arguments. This can happen, for example, when
3011ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    // substituting the outer template arguments ends up causing two
3012ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    // class template partial specializations of a member class template
3013ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    // to have identical forms, e.g.,
3014ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //
3015ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //   template<typename T, typename U>
3016ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //   struct Outer {
3017ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //     template<typename X, typename Y> struct Inner;
3018ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //     template<typename Y> struct Inner<T, Y>;
3019ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //     template<typename Y> struct Inner<U, Y>;
3020ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //   };
3021ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //
3022ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //   Outer<int, int> outer; // error: the partial specializations of Inner
3023ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    //                          // have the same signature.
3024ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3025d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor      << WrittenTy->getType();
3026ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3027ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor      << SemaRef.Context.getTypeDeclType(PrevDecl);
30286bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3029ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  }
3030a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
3031a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
3032ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Create the class template partial specialization declaration.
3033ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  ClassTemplatePartialSpecializationDecl *InstPartialSpec
3034a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
303513c8577201e4fc0ddac5f09d05fd1778832137d1Douglas Gregor                                                     PartialSpec->getTagKind(),
3036a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                                     Owner,
3037ba877adeb49ed6dc17f27fa3a3bcd0cca713fd68Abramo Bagnara                                                     PartialSpec->getLocStart(),
3038ba877adeb49ed6dc17f27fa3a3bcd0cca713fd68Abramo Bagnara                                                     PartialSpec->getLocation(),
3039ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                                                     InstParams,
3040a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                                     ClassTemplate,
30414967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                                     Converted,
3042d5532b6cfff2977e0c59fa6ead7f7973984a620dJohn McCall                                                     InstTemplateArgs,
30433cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall                                                     CanonType,
30446bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                                     nullptr);
3045b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall  // Substitute the nested name specifier, if any.
3046b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall  if (SubstQualifier(PartialSpec, InstPartialSpec))
30476bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3048b6217665c6a987f2d6c8665fd70365d7719ac4dfJohn McCall
3049ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
30504469e8a97cdca3725b4f8f366916143113c029acDouglas Gregor  InstPartialSpec->setTypeAsWritten(WrittenTy);
3051a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
3052ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // Add this partial specialization to the set of class template partial
3053ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  // specializations.
30546bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
30556bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines                                          /*InsertPos=*/nullptr);
3056d65587f7a6d38965fa37158d3f57990a7faf3836Douglas Gregor  return InstPartialSpec;
3057ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor}
3058ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor
3059ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// \brief Instantiate the declaration of a variable template partial
3060ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// specialization.
3061ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo///
3062ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// \param VarTemplate the (instantiated) variable template that is partially
3063ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// specialized by the instantiation of \p PartialSpec.
3064ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo///
3065ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// \param PartialSpec the (uninstantiated) variable template partial
3066ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// specialization that we are instantiating.
3067ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo///
3068ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// \returns The instantiated partial specialization, if successful; otherwise,
3069ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// NULL to indicate an error.
3070ef4579cda09b73e3d4d98af48201da25adc29326Larisse VoufoVarTemplatePartialSpecializationDecl *
3071ef4579cda09b73e3d4d98af48201da25adc29326Larisse VoufoTemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3072ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarTemplateDecl *VarTemplate,
3073ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarTemplatePartialSpecializationDecl *PartialSpec) {
3074ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Create a local instantiation scope for this variable template partial
3075ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // specialization, which will contain the instantiations of the template
3076ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // parameters.
3077ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  LocalInstantiationScope Scope(SemaRef);
3078ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3079ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Substitute into the template parameters of the variable template partial
3080ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // specialization.
3081ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3082ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3083ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (!InstParams)
30846bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3085ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3086ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Substitute into the template arguments of the variable template partial
3087ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // specialization.
3088c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella  const ASTTemplateArgumentListInfo *TemplArgInfo
3089c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella    = PartialSpec->getTemplateArgsAsWritten();
3090c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3091c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella                                            TemplArgInfo->RAngleLoc);
3092c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella  if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3093c1cef0892e049fcd31084f02d1efdd9985d4dfa4Enea Zaffanella                    TemplArgInfo->NumTemplateArgs,
3094ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                    InstTemplateArgs, TemplateArgs))
30956bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3096ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3097ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Check that the template argument list is well-formed for this
3098ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // class template.
3099ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  SmallVector<TemplateArgument, 4> Converted;
3100ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3101ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                                        InstTemplateArgs, false, Converted))
31026bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3103ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3104ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Figure out where to insert this variable template partial specialization
3105ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // in the member template's set of variable template partial specializations.
31066bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  void *InsertPos = nullptr;
3107ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateSpecializationDecl *PrevDecl =
3108c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      VarTemplate->findPartialSpecialization(Converted, InsertPos);
3109ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3110ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Build the canonical type that describes the converted template
3111ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // arguments of the variable template partial specialization.
3112ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
31134967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      TemplateName(VarTemplate), Converted);
3114ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3115ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Build the fully-sugared type for this variable template
3116ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // specialization as the user wrote in the specialization
3117ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // itself. This means that we'll pretty-print the type retrieved
3118ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // from the specialization's declaration the way that the user
3119ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // actually wrote the specialization, rather than formatting the
3120ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // name based on the "canonical" representation used to store the
3121ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // template arguments in the specialization.
3122ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3123ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3124ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      CanonType);
3125ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3126ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (PrevDecl) {
3127ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // We've already seen a partial specialization with the same template
3128ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // parameters and template arguments. This can happen, for example, when
3129ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // substituting the outer template arguments ends up causing two
3130ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // variable template partial specializations of a member variable template
3131ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // to have identical forms, e.g.,
3132ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //
3133ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //   template<typename T, typename U>
3134ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //   struct Outer {
3135ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //     template<typename X, typename Y> pair<X,Y> p;
3136ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //     template<typename Y> pair<T, Y> p;
3137ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //     template<typename Y> pair<U, Y> p;
3138ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //   };
3139ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //
3140ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //   Outer<int, int> outer; // error: the partial specializations of Inner
3141ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    //                          // have the same signature.
3142ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    SemaRef.Diag(PartialSpec->getLocation(),
3143ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                 diag::err_var_partial_spec_redeclared)
3144ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        << WrittenTy->getType();
3145ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    SemaRef.Diag(PrevDecl->getLocation(),
3146ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                 diag::note_var_prev_partial_spec_here);
31476bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3148ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
3149ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3150ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Do substitution on the type of the declaration
3151ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TypeSourceInfo *DI = SemaRef.SubstType(
3152ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      PartialSpec->getTypeSourceInfo(), TemplateArgs,
3153ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3154ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (!DI)
31556bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3156ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3157ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (DI->getType()->isFunctionType()) {
3158ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    SemaRef.Diag(PartialSpec->getLocation(),
3159ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                 diag::err_variable_instantiates_to_function)
3160ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        << PartialSpec->isStaticDataMember() << DI->getType();
31616bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3162ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
3163ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3164ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Create the variable template partial specialization declaration.
3165ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplatePartialSpecializationDecl *InstPartialSpec =
3166ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      VarTemplatePartialSpecializationDecl::Create(
3167ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo          SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3168ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo          PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
31694967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3170ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3171ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Substitute the nested name specifier, if any.
3172ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (SubstQualifier(PartialSpec, InstPartialSpec))
31736bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3174ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3175ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3176ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  InstPartialSpec->setTypeAsWritten(WrittenTy);
3177ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3178ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Add this partial specialization to the set of variable template partial
3179ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // specializations. The instantiation of the initializer is not necessary.
31806bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
318104592e7c1260a6a671a24d91dab16f5d5a024fe0Larisse Voufo
318204592e7c1260a6a671a24d91dab16f5d5a024fe0Larisse Voufo  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3183a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith                                     LateAttrs, Owner, StartingScope);
318404592e7c1260a6a671a24d91dab16f5d5a024fe0Larisse Voufo
3185ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  return InstPartialSpec;
3186ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
3187ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
318821ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCallTypeSourceInfo*
318921ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCallTemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
31905f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner                              SmallVectorImpl<ParmVarDecl *> &Params) {
319121ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCall  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
319221ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCall  assert(OldTInfo && "substituting function without type source info");
319321ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCall  assert(Params.empty() && "parameter vector is non-empty at start");
31946bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines
31956bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  CXXRecordDecl *ThisContext = nullptr;
3196cefc3afac14d29de5aba7810cc8fe6c858949e9dDouglas Gregor  unsigned ThisTypeQuals = 0;
3197cefc3afac14d29de5aba7810cc8fe6c858949e9dDouglas Gregor  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3198cafeb948e6067b8dc897c441da522367917b06f9Richard Smith    ThisContext = cast<CXXRecordDecl>(Owner);
3199cefc3afac14d29de5aba7810cc8fe6c858949e9dDouglas Gregor    ThisTypeQuals = Method->getTypeQualifiers();
3200cefc3afac14d29de5aba7810cc8fe6c858949e9dDouglas Gregor  }
3201cefc3afac14d29de5aba7810cc8fe6c858949e9dDouglas Gregor
32026cd3b9fb8a29bb70fff01719bdde238723d67c10John McCall  TypeSourceInfo *NewTInfo
32036cd3b9fb8a29bb70fff01719bdde238723d67c10John McCall    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
32046cd3b9fb8a29bb70fff01719bdde238723d67c10John McCall                                    D->getTypeSpecStartLoc(),
3205cefc3afac14d29de5aba7810cc8fe6c858949e9dDouglas Gregor                                    D->getDeclName(),
3206cefc3afac14d29de5aba7810cc8fe6c858949e9dDouglas Gregor                                    ThisContext, ThisTypeQuals);
320721ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCall  if (!NewTInfo)
32086bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
32095545e166a956a20d7a6b58408e251a1119025485Douglas Gregor
3210c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3211c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3212c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    if (NewTInfo != OldTInfo) {
3213c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner      // Get parameters from the new type info.
3214140a2bd77539b4537010d8cd6a0a3805ce724b3eAbramo Bagnara      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
321539e6ab4be93d9c5e729a578ddd9d415cd2d49872David Blaikie      FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3216500d729e85028944355a119f9823ac99fa5ddcabRichard Smith      unsigned NewIdx = 0;
3217651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
321812c9c00024a01819e3a70ef6d951d32efaeb9312Douglas Gregor           OldIdx != NumOldParams; ++OldIdx) {
3219651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3220500d729e85028944355a119f9823ac99fa5ddcabRichard Smith        LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3221500d729e85028944355a119f9823ac99fa5ddcabRichard Smith
3222dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie        Optional<unsigned> NumArgumentsInExpansion;
3223500d729e85028944355a119f9823ac99fa5ddcabRichard Smith        if (OldParam->isParameterPack())
3224500d729e85028944355a119f9823ac99fa5ddcabRichard Smith          NumArgumentsInExpansion =
3225500d729e85028944355a119f9823ac99fa5ddcabRichard Smith              SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3226500d729e85028944355a119f9823ac99fa5ddcabRichard Smith                                                 TemplateArgs);
3227500d729e85028944355a119f9823ac99fa5ddcabRichard Smith        if (!NumArgumentsInExpansion) {
3228a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi          // Simple case: normal parameter, or a parameter pack that's
322912c9c00024a01819e3a70ef6d951d32efaeb9312Douglas Gregor          // instantiated to a (still-dependent) parameter pack.
3230651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines          ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
323112c9c00024a01819e3a70ef6d951d32efaeb9312Douglas Gregor          Params.push_back(NewParam);
3232500d729e85028944355a119f9823ac99fa5ddcabRichard Smith          Scope->InstantiatedLocal(OldParam, NewParam);
3233500d729e85028944355a119f9823ac99fa5ddcabRichard Smith        } else {
3234500d729e85028944355a119f9823ac99fa5ddcabRichard Smith          // Parameter pack expansion: make the instantiation an argument pack.
3235500d729e85028944355a119f9823ac99fa5ddcabRichard Smith          Scope->MakeInstantiatedLocalArgPack(OldParam);
3236500d729e85028944355a119f9823ac99fa5ddcabRichard Smith          for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3237651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines            ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3238500d729e85028944355a119f9823ac99fa5ddcabRichard Smith            Params.push_back(NewParam);
3239500d729e85028944355a119f9823ac99fa5ddcabRichard Smith            Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3240500d729e85028944355a119f9823ac99fa5ddcabRichard Smith          }
324112c9c00024a01819e3a70ef6d951d32efaeb9312Douglas Gregor        }
32426920cdce298ac9ba50dc7ebb7dea982a300b0664Douglas Gregor      }
3243c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    } else {
3244c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner      // The function type itself was not dependent and therefore no
3245c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner      // substitution occurred. However, we still need to instantiate
3246c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner      // the function parameters themselves.
3247c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner      const FunctionProtoType *OldProto =
3248c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner          cast<FunctionProtoType>(OldProtoLoc.getType());
3249651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3250651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines           ++i) {
3251651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines        ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3252c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner        if (!OldParam) {
3253c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner          Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3254651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines              D, D->getLocation(), OldProto->getParamType(i)));
3255c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner          continue;
3256c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner        }
3257c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner
3258ded9979a2997336cee8797deb6bb3194fccc2068Eli Friedman        ParmVarDecl *Parm =
3259c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner            cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
32606920cdce298ac9ba50dc7ebb7dea982a300b0664Douglas Gregor        if (!Parm)
32616bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines          return nullptr;
32626920cdce298ac9ba50dc7ebb7dea982a300b0664Douglas Gregor        Params.push_back(Parm);
32636920cdce298ac9ba50dc7ebb7dea982a300b0664Douglas Gregor      }
3264cb27b0f70d2017295776afafe3616e0bcd74ab51Douglas Gregor    }
3265c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner  } else {
3266c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    // If the type of this function, after ignoring parentheses, is not
3267c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    // *directly* a function type, then we're instantiating a function that
3268c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    // was declared via a typedef or with attributes, e.g.,
3269c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    //
3270c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    //   typedef int functype(int, int);
3271c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    //   functype func;
3272c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    //   int __cdecl meth(int, int);
3273c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    //
3274c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    // In this case, we'll just go instantiate the ParmVarDecls that we
3275c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    // synthesized in the method declaration.
3276c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner    SmallVector<QualType, 4> ParamTypes;
32774967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Sema::ExtParameterInfoBuilder ExtParamInfos;
32784967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
32794967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                               TemplateArgs, ParamTypes, &Params,
32804967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                               ExtParamInfos))
32816bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
3282cb27b0f70d2017295776afafe3616e0bcd74ab51Douglas Gregor  }
3283c66e7e99d5acc560de5cea50909fcea22ef12ca5Reid Kleckner
328421ef0fa27b0783ec0bc6aa5b524feb2ec840f952John McCall  return NewTInfo;
32855545e166a956a20d7a6b58408e251a1119025485Douglas Gregor}
32865545e166a956a20d7a6b58408e251a1119025485Douglas Gregor
3287e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith/// Introduce the instantiated function parameters into the local
3288e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith/// instantiation scope, and set the parameter names to those used
3289e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith/// in the template.
3290176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hinesstatic bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3291e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith                                             const FunctionDecl *PatternDecl,
3292e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith                                             LocalInstantiationScope &Scope,
3293e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3294e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  unsigned FParamIdx = 0;
3295e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3296e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3297e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    if (!PatternParam->isParameterPack()) {
3298e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      // Simple case: not a parameter pack.
3299e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      assert(FParamIdx < Function->getNumParams());
3300e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3301176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      FunctionParam->setDeclName(PatternParam->getDeclName());
3302651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      // If the parameter's type is not dependent, update it to match the type
3303651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      // in the pattern. They can differ in top-level cv-qualifiers, and we want
3304651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      // the pattern's type here. If the type is dependent, they can't differ,
3305176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      // per core issue 1668. Substitute into the type from the pattern, in case
3306176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      // it's instantiation-dependent.
3307651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      // FIXME: Updating the type to work around this is at best fragile.
3308176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      if (!PatternDecl->getType()->isDependentType()) {
3309176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3310176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                 FunctionParam->getLocation(),
3311176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                 FunctionParam->getDeclName());
3312176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        if (T.isNull())
3313176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines          return true;
3314176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        FunctionParam->setType(T);
3315176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      }
3316651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
3317e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      Scope.InstantiatedLocal(PatternParam, FunctionParam);
3318e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      ++FParamIdx;
3319e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      continue;
3320e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    }
3321e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
3322e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    // Expand the parameter pack.
3323e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    Scope.MakeInstantiatedLocalArgPack(PatternParam);
3324dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie    Optional<unsigned> NumArgumentsInExpansion
3325e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3326500d729e85028944355a119f9823ac99fa5ddcabRichard Smith    assert(NumArgumentsInExpansion &&
3327500d729e85028944355a119f9823ac99fa5ddcabRichard Smith           "should only be called when all template arguments are known");
3328176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    QualType PatternType =
3329176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3330500d729e85028944355a119f9823ac99fa5ddcabRichard Smith    for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3331e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3332e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      FunctionParam->setDeclName(PatternParam->getDeclName());
3333176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      if (!PatternDecl->getType()->isDependentType()) {
3334176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3335176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        QualType T = S.SubstType(PatternType, TemplateArgs,
3336176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                 FunctionParam->getLocation(),
3337176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                 FunctionParam->getDeclName());
3338e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith        if (T.isNull())
3339176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines          return true;
3340176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        FunctionParam->setType(T);
3341e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      }
3342e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
3343176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3344176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      ++FParamIdx;
3345e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    }
3346e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  }
3347e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
3348176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  return false;
3349e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith}
3350e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
3351e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smithvoid Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3352e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith                                    FunctionDecl *Decl) {
335313bffc532bafd45d4a77867993c1afb83c7661beRichard Smith  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
335413bffc532bafd45d4a77867993c1afb83c7661beRichard Smith  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3355e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    return;
3356e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
3357e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3358e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith                             InstantiatingTemplate::ExceptionSpecification());
3359d69f37b5822420e3c3a1b2e875b122aca8248533Alp Toker  if (Inst.isInvalid()) {
3360b9d0b76e42fd2d4cdfd135220302458d03ad09feRichard Smith    // We hit the instantiation depth limit. Clear the exception specification
3361b9d0b76e42fd2d4cdfd135220302458d03ad09feRichard Smith    // so that our callers don't have to cope with EST_Uninstantiated.
3362176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    UpdateExceptionSpec(Decl, EST_None);
3363e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    return;
3364b9d0b76e42fd2d4cdfd135220302458d03ad09feRichard Smith  }
3365e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
3366e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  // Enter the scope of this instantiation. We don't use
3367e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  // PushDeclContext because we don't have a scope.
3368e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  Sema::ContextRAII savedContext(*this, Decl);
3369e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  LocalInstantiationScope Scope(*this);
3370e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
3371e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  MultiLevelTemplateArgumentList TemplateArgs =
33726bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3373e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
337413bffc532bafd45d4a77867993c1afb83c7661beRichard Smith  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3375176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3376176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                       TemplateArgs)) {
3377176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    UpdateExceptionSpec(Decl, EST_None);
3378176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    return;
3379176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  }
3380e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
3381176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3382176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                     TemplateArgs);
3383e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith}
3384e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith
33851eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// \brief Initializes the common fields of an instantiation function
3386e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor/// declaration (New) from the corresponding fields of its template (Tmpl).
3387e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor///
3388e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor/// \returns true if there was an error
33891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpbool
33901eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpTemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3391e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor                                                    FunctionDecl *Tmpl) {
339285f485a70fbec54c9b4562dfc4d95188ea6c9b48David Blaikie  if (Tmpl->isDeleted())
339310620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt    New->setDeletedAsWritten();
33941eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3395651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  // Forward the mangling number from the template to the instantiated decl.
3396651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  SemaRef.Context.setManglingNumber(New,
3397651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines                                    SemaRef.Context.getManglingNumber(Tmpl));
3398651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
3399cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  // If we are performing substituting explicitly-specified template arguments
3400cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  // or deduced template arguments into a function template and we reach this
3401cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  // point, we are now past the point where SFINAE applies and have committed
34021eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // to keeping the new function template specialization. We therefore
34031eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  // convert the active template instantiation for the function template
3404cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  // into a template instantiation for this specific function template
3405cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  // specialization, which is not a SFINAE context, so that we diagnose any
3406cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  // further errors in the declaration itself.
3407cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3408cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3409cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3410cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor      ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
34111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    if (FunctionTemplateDecl *FunTmpl
34124a9e60fc7c36e323ae376601cc704fed4beb68aeNick Lewycky          = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
34131eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3414cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor             "Deduction from the wrong function template?");
3415bcbb8bd3326a86aa70b7df386ae3c86c9ad255c5Daniel Dunbar      (void) FunTmpl;
3416cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
34174a9e60fc7c36e323ae376601cc704fed4beb68aeNick Lewycky      ActiveInst.Entity = New;
3418cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor    }
3419cca9e9674a5e50a283185d8e9d8a5c3414eb008eDouglas Gregor  }
34201eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
34210ae7b3f1d5403265f693ed75384603ca8fbba74dDouglas Gregor  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
34220ae7b3f1d5403265f693ed75384603ca8fbba74dDouglas Gregor  assert(Proto && "Function template without prototype?");
34230ae7b3f1d5403265f693ed75384603ca8fbba74dDouglas Gregor
342460618fa7f88d5162bb5b40988b6b38d4d75d6fc6Sebastian Redl  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3425e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3426e23cf437fe76b1ed02d63c3f61b456fd48a915f5John McCall
3427e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    // DR1330: In C++11, defer instantiation of a non-trivial
3428e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    // exception specification.
342987d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    // DR1484: Local classes and their members are instantiated along with the
343087d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar    // containing function.
343180ad52f327b532bded5c5b0ee38779d841c6cd35Richard Smith    if (SemaRef.getLangOpts().CPlusPlus11 &&
3432176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        EPI.ExceptionSpec.Type != EST_None &&
3433176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        EPI.ExceptionSpec.Type != EST_DynamicNone &&
343487d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar        EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
343587d948ecccffea9e9e37d0d053b246e2d6d6c47bPirama Arumuga Nainar        !Tmpl->isLexicallyWithinFunctionOrMethod()) {
343613bffc532bafd45d4a77867993c1afb83c7661beRichard Smith      FunctionDecl *ExceptionSpecTemplate = Tmpl;
3437176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3438176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
34394841ca5f83bf970f910ac7d154cdd71d2a3cf481Richard Smith      ExceptionSpecificationType NewEST = EST_Uninstantiated;
3440176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      if (EPI.ExceptionSpec.Type == EST_Unevaluated)
34414841ca5f83bf970f910ac7d154cdd71d2a3cf481Richard Smith        NewEST = EST_Unevaluated;
344213bffc532bafd45d4a77867993c1afb83c7661beRichard Smith
3443e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      // Mark the function has having an uninstantiated exception specification.
3444e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      const FunctionProtoType *NewProto
3445e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith        = New->getType()->getAs<FunctionProtoType>();
3446e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      assert(NewProto && "Template instantiation without function prototype?");
3447e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith      EPI = NewProto->getExtProtoInfo();
3448176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      EPI.ExceptionSpec.Type = NewEST;
3449176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      EPI.ExceptionSpec.SourceDecl = New;
3450176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
34510567a79130a251bf464ce21ecf3f8b9fb5207900Reid Kleckner      New->setType(SemaRef.Context.getFunctionType(
3452651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines          NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3453e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    } else {
3454176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3455e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith    }
34560ae7b3f1d5403265f693ed75384603ca8fbba74dDouglas Gregor  }
34570ae7b3f1d5403265f693ed75384603ca8fbba74dDouglas Gregor
345819f74acdf8842ceece578b7307884f5ba22d7f59Rafael Espindola  // Get the definition. Leaves the variable unchanged if undefined.
3459e6975e9b0985ad7f7ff9187e38d95bfe9ac4181bRichard Smith  const FunctionDecl *Definition = Tmpl;
346019f74acdf8842ceece578b7307884f5ba22d7f59Rafael Espindola  Tmpl->isDefined(Definition);
346119f74acdf8842ceece578b7307884f5ba22d7f59Rafael Espindola
346223323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
346323323e0253716ff03c95a00fb6903019daafe3aaDeLesley Hutchins                           LateAttrs, StartingScope);
34647cf84d66965a7706004d8590b5af5fe54b85f525Douglas Gregor
3465e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor  return false;
3466e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor}
3467e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor
34685545e166a956a20d7a6b58408e251a1119025485Douglas Gregor/// \brief Initializes common fields of an instantiated method
34695545e166a956a20d7a6b58408e251a1119025485Douglas Gregor/// declaration (New) from the corresponding fields of its template
34705545e166a956a20d7a6b58408e251a1119025485Douglas Gregor/// (Tmpl).
34715545e166a956a20d7a6b58408e251a1119025485Douglas Gregor///
34725545e166a956a20d7a6b58408e251a1119025485Douglas Gregor/// \returns true if there was an error
34731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpbool
34741eb4433ac451dc16f4133a88af2d002ac26c58efMike StumpTemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
34755545e166a956a20d7a6b58408e251a1119025485Douglas Gregor                                                  CXXMethodDecl *Tmpl) {
3476e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor  if (InitFunctionInstantiation(New, Tmpl))
3477e53060fa78ad7e98352049f72787bdb7543e2a48Douglas Gregor    return true;
34781eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
34795545e166a956a20d7a6b58408e251a1119025485Douglas Gregor  New->setAccess(Tmpl->getAccess());
3480e7184df728bb339633d88c774b5097dd9318cc8aFariborz Jahanian  if (Tmpl->isVirtualAsWritten())
348185606ebf3dd1b5dd81a59ef25b5ad47627664774Douglas Gregor    New->setVirtualAsWritten(true);
34825545e166a956a20d7a6b58408e251a1119025485Douglas Gregor
34835545e166a956a20d7a6b58408e251a1119025485Douglas Gregor  // FIXME: New needs a pointer to Tmpl
34845545e166a956a20d7a6b58408e251a1119025485Douglas Gregor  return false;
34855545e166a956a20d7a6b58408e251a1119025485Douglas Gregor}
3486a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor
3487a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor/// \brief Instantiate the definition of the given function from its
3488a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor/// template.
3489a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor///
3490b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor/// \param PointOfInstantiation the point at which the instantiation was
3491b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor/// required. Note that this is not precisely a "point of instantiation"
3492b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor/// for the function, but it's close.
3493b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor///
3494a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor/// \param Function the already-instantiated declaration of a
3495b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor/// function template specialization or member function of a class template
3496b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor/// specialization.
3497b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor///
3498b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor/// \param Recursive if true, recursively instantiates any functions that
3499b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor/// are required by this instantiation.
3500e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor///
3501e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor/// \param DefinitionRequired if true, then we are performing an explicit
3502e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor/// instantiation where the body of the function is required. Complain if
3503e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor/// there is no such body.
3504f3e7ce4bd9837cdab6a096235922865f95467d3dDouglas Gregorvoid Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3505b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor                                         FunctionDecl *Function,
3506e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor                                         bool Recursive,
35074967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                         bool DefinitionRequired,
35084967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                         bool AtEndOfTU) {
350910620eb5164e31208fcbf0437cd79ae535ed0559Sean Hunt  if (Function->isInvalidDecl() || Function->isDefined())
351054dabfca850ca9e60e9ffb60003529f868d4d127Douglas Gregor    return;
351154dabfca850ca9e60e9ffb60003529f868d4d127Douglas Gregor
3512af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  // Never instantiate an explicit specialization except if it is a class scope
3513af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  // explicit specialization.
3514af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3515af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet      !Function->getClassScopeSpecializationPattern())
3516251b4ff2578e26959a4c036140ccd61c5e9292f2Douglas Gregor    return;
35176cfacfe54c75baa4d67f1fbdf4f80644b662818eDouglas Gregor
35181eee0e753fb390b04848846e837714ec774b7bfdDouglas Gregor  // Find the function body that we'll be substituting.
35193b846b6c252972a6f142aa226c1e65aebd0feecaDouglas Gregor  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3520f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt  assert(PatternDecl && "instantiating a non-template");
3521f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt
3522f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt  Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3523f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt  assert(PatternDecl && "template definition is not a template");
3524f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt  if (!Pattern) {
3525f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt    // Try to find a defaulted definition
3526f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt    PatternDecl->isDefined(PatternDecl);
3527dfab854e6855dad076c0207b29859d452e398437Sean Hunt  }
3528f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt  assert(PatternDecl && "template definition is not a template");
35291eee0e753fb390b04848846e837714ec774b7bfdDouglas Gregor
35308387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet  // Postpone late parsed template instantiations.
3531f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt  if (PatternDecl->isLateTemplateParsed() &&
35328a29bc047a374df2464869b55581c24def68c2ecNick Lewycky      !LateTemplateParser) {
35338387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    PendingInstantiations.push_back(
35348387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet      std::make_pair(Function, PointOfInstantiation));
35358387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    return;
35368387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet  }
35378387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet
3538176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // If we're performing recursive template instantiation, create our own
3539176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // queue of pending implicit instantiations that we will instantiate later,
3540176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // while we're still within our own instantiation context.
3541176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // This has to happen before LateTemplateParser below is called, so that
3542176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  // it marks vtables used in late parsed templates as used.
3543176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  SavePendingLocalImplicitInstantiationsRAII
3544176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      SavedPendingLocalImplicitInstantiations(*this);
35450e2c34f92f00628d48968dfea096d36381f494cbStephen Hines  SavePendingInstantiationsAndVTableUsesRAII
35460e2c34f92f00628d48968dfea096d36381f494cbStephen Hines      SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3547176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
3548360d23ef628bf891514e77c519d1d77305ca1743David Majnemer  // Call the LateTemplateParser callback if there is a need to late parse
3549a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  // a templated function definition.
3550f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
35518387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet      LateTemplateParser) {
3552ac32d9044b9c1e7492cef929a322d23ce899d276Richard Smith    // FIXME: Optimize to allow individual templates to be deserialized.
3553ac32d9044b9c1e7492cef929a322d23ce899d276Richard Smith    if (PatternDecl->isFromASTFile())
3554ac32d9044b9c1e7492cef929a322d23ce899d276Richard Smith      ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3555ac32d9044b9c1e7492cef929a322d23ce899d276Richard Smith
3556ac32d9044b9c1e7492cef929a322d23ce899d276Richard Smith    LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3557ac32d9044b9c1e7492cef929a322d23ce899d276Richard Smith    assert(LPT && "missing LateParsedTemplate");
3558ac32d9044b9c1e7492cef929a322d23ce899d276Richard Smith    LateTemplateParser(OpaqueParser, *LPT);
35598387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet    Pattern = PatternDecl->getBody(PatternDecl);
35608387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet  }
35618387e2a41eef6fa17fb140a18c29b6eee9dd2b8aFrancois Pichet
35624967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // FIXME: Check that the definition is visible before trying to instantiate
35634967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // it. This requires us to track the instantiation stack in order to know
35644967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // which definitions should be visible.
35654967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
3566f996e051d9953550982b57132daad8a5e3f7bd65Sean Hunt  if (!Pattern && !PatternDecl->isDefaulted()) {
3567e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor    if (DefinitionRequired) {
3568e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor      if (Function->getPrimaryTemplate())
3569a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi        Diag(PointOfInstantiation,
3570e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor             diag::err_explicit_instantiation_undefined_func_template)
3571e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor          << Function->getPrimaryTemplate();
3572e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor      else
3573a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi        Diag(PointOfInstantiation,
3574e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor             diag::err_explicit_instantiation_undefined_member)
3575e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor          << 1 << Function->getDeclName() << Function->getDeclContext();
3576a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
3577e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor      if (PatternDecl)
3578a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi        Diag(PatternDecl->getLocation(),
3579e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor             diag::note_explicit_instantiation_here);
3580cfe833be882f600206f1587f157b025b368497d7Douglas Gregor      Function->setInvalidDecl();
358158e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth    } else if (Function->getTemplateSpecializationKind()
358258e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth                 == TSK_ExplicitInstantiationDefinition) {
3583176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      assert(!Recursive);
358462c78d54bee499dd87f768f48b21c9b5ec15e516Chandler Carruth      PendingInstantiations.push_back(
358558e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth        std::make_pair(Function, PointOfInstantiation));
35864967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    } else if (Function->getTemplateSpecializationKind()
35874967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                 == TSK_ImplicitInstantiation) {
35884967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
35894967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        Diag(PointOfInstantiation, diag::warn_func_template_missing)
35904967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          << Function;
35914967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
35924967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        if (getLangOpts().CPlusPlus11)
35934967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
35944967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar            << Function;
35954967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      }
3596e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor    }
359758e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth
35981eee0e753fb390b04848846e837714ec774b7bfdDouglas Gregor    return;
3599e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor  }
36001eee0e753fb390b04848846e837714ec774b7bfdDouglas Gregor
360160e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  // C++1y [temp.explicit]p10:
360260e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  //   Except for inline functions, declarations with types deduced from their
360360e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  //   initializer or return value, and class template specializations, other
360460e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  //   explicit instantiation declarations have the effect of suppressing the
360560e141e1f87211ca831de6821003d80fe20a06f3Richard Smith  //   implicit instantiation of the entity to which they refer.
3606651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if (Function->getTemplateSpecializationKind() ==
3607651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines          TSK_ExplicitInstantiationDeclaration &&
360860e141e1f87211ca831de6821003d80fe20a06f3Richard Smith      !PatternDecl->isInlined() &&
3609651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      !PatternDecl->getReturnType()->getContainedAutoType())
3610d0e3daf2b980b505e535d35b432c938c6d0208efDouglas Gregor    return;
36111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3612c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines  if (PatternDecl->isInlined()) {
3613c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    // Function, and all later redeclarations of it (from imported modules,
3614c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    // for instance), are now implicitly inline.
3615c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    for (auto *D = Function->getMostRecentDecl(); /**/;
3616c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines         D = D->getPreviousDecl()) {
3617c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      D->setImplicitlyInline();
3618c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      if (D == Function)
3619c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines        break;
3620c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines    }
3621c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines  }
3622d4497dde6fc8f5ce79e0ec37682b8dc920bbbef0Richard Smith
3623f3e7ce4bd9837cdab6a096235922865f95467d3dDouglas Gregor  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3624d69f37b5822420e3c3a1b2e875b122aca8248533Alp Toker  if (Inst.isInvalid())
3625a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi    return;
36264967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
36274967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                      "instantiating function definition");
3628a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
3629e994624c001143ee2b8a7a4715aaad5efcd71f18Abramo Bagnara  // Copy the inner loc start from the pattern.
3630e994624c001143ee2b8a7a4715aaad5efcd71f18Abramo Bagnara  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3631e994624c001143ee2b8a7a4715aaad5efcd71f18Abramo Bagnara
3632a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  EnterExpressionEvaluationContext EvalContext(*this,
3633f312b1ea179f1c44371f9ee0cd0bc006f612de11John McCall                                               Sema::PotentiallyEvaluated);
3634e2c31ff0bc622e6fd7d47d7e08b53840f3be6c89Douglas Gregor
363554dabfca850ca9e60e9ffb60003529f868d4d127Douglas Gregor  // Introduce a new scope where local variable instantiations will be
363660406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  // recorded, unless we're actually a member function within a local
363760406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  // class, in which case we need to merge our results with the parent
363860406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  // scope (of the enclosing function).
363960406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  bool MergeWithParentScope = false;
364060406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
364160406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor    MergeWithParentScope = Rec->isLocalClass();
364260406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor
364360406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  LocalInstantiationScope Scope(*this, MergeWithParentScope);
36441eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
36451d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith  if (PatternDecl->isDefaulted())
36461d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith    SetDeclDefaulted(Function, PatternDecl->getLocation());
36471d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith  else {
3648176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    MultiLevelTemplateArgumentList TemplateArgs =
3649176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3650176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
3651176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    // Substitute into the qualifier; we can get a substitution failure here
3652176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    // through evil use of alias templates.
3653176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3654176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    // of the) lexical context of the pattern?
3655176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3656176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
36576bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    ActOnStartOfFunctionDef(nullptr, Function);
36587c5d28b6342229fb648aea59dc063f67ff16bc81Richard Smith
36591d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith    // Enter the scope of this instantiation. We don't use
36601d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith    // PushDeclContext because we don't have a scope.
36611d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith    Sema::ContextRAII savedContext(*this, Function);
36627c5d28b6342229fb648aea59dc063f67ff16bc81Richard Smith
3663176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3664176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                         TemplateArgs))
3665176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      return;
36661eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3667cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt    // If this is a constructor, instantiate the member initializers.
3668cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt    if (const CXXConstructorDecl *Ctor =
3669cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt          dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3670cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt      InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3671cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt                                 TemplateArgs);
3672cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt    }
3673cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt
3674cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt    // Instantiate the function body.
3675cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt    StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3676cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt
3677cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt    if (Body.isInvalid())
3678cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt      Function->setInvalidDecl();
3679a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
3680cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt    ActOnFinishFunctionBody(Function, Body.get(),
3681cd10dec673680fd18a2e5a27646173780c059d32Sean Hunt                            /*IsInstantiation=*/true);
3682b9f1b8d877541e76390cd3807c2dcff2f950360aDouglas Gregor
36831d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith    PerformDependentDiagnostics(PatternDecl, TemplateArgs);
36840c01d18094100db92d38daa923c95661512db203John McCall
3685651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    if (auto *Listener = getASTMutationListener())
3686651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      Listener->FunctionDefinitionInstantiated(Function);
3687651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
36881d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith    savedContext.pop();
36891d28caf3b5254e60d3e3a1d2d37e5df2e5924111Richard Smith  }
3690aba43bb13b3aa3e81990989375fba3a902bfe1c2Douglas Gregor
3691aba43bb13b3aa3e81990989375fba3a902bfe1c2Douglas Gregor  DeclGroupRef DG(Function);
3692aba43bb13b3aa3e81990989375fba3a902bfe1c2Douglas Gregor  Consumer.HandleTopLevelDecl(DG);
36931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
369460406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  // This class may have local implicit instantiations that need to be
369560406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  // instantiation within this scope.
369662c78d54bee499dd87f768f48b21c9b5ec15e516Chandler Carruth  PerformPendingInstantiations(/*LocalOnly=*/true);
369760406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  Scope.Exit();
369860406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor
3699b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor  if (Recursive) {
37002a5f99eb4e2af771faacfceb9f78e230129c5e5aNick Lewycky    // Define any pending vtables.
37012a5f99eb4e2af771faacfceb9f78e230129c5e5aNick Lewycky    DefineUsedVTables();
37022a5f99eb4e2af771faacfceb9f78e230129c5e5aNick Lewycky
3703b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor    // Instantiate any pending implicit instantiations found during the
37041eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // instantiation of this template.
370562c78d54bee499dd87f768f48b21c9b5ec15e516Chandler Carruth    PerformPendingInstantiations();
37061eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
37070e2c34f92f00628d48968dfea096d36381f494cbStephen Hines    // PendingInstantiations and VTableUses are restored through
37080e2c34f92f00628d48968dfea096d36381f494cbStephen Hines    // SavePendingInstantiationsAndVTableUses's destructor.
3709b33fe2ff12676bff9db595fdf77e29014d7ba397Douglas Gregor  }
3710a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor}
3711a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor
3712ef4579cda09b73e3d4d98af48201da25adc29326Larisse VoufoVarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3713ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3714ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    const TemplateArgumentList &TemplateArgList,
3715ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    const TemplateArgumentListInfo &TemplateArgsInfo,
3716ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    SmallVectorImpl<TemplateArgument> &Converted,
3717ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    SourceLocation PointOfInstantiation, void *InsertPos,
3718ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    LateInstantiatedAttrVec *LateAttrs,
3719ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    LocalInstantiationScope *StartingScope) {
3720ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (FromVar->isInvalidDecl())
37216bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3722ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3723ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3724d69f37b5822420e3c3a1b2e875b122aca8248533Alp Toker  if (Inst.isInvalid())
37256bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3726ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3727ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  MultiLevelTemplateArgumentList TemplateArgLists;
3728ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3729ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3730d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // Instantiate the first declaration of the variable template: for a partial
3731d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // specialization of a static data member template, the first declaration may
3732d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // or may not be the declaration in the class; if it's in the class, we want
3733d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // to instantiate a member in the class (a declaration), and if it's outside,
3734d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // we want to instantiate a definition.
3735651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  //
3736651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  // If we're instantiating an explicitly-specialized member template or member
3737651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  // partial specialization, don't do this. The member specialization completely
3738651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  // replaces the original declaration in this case.
3739651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  bool IsMemberSpec = false;
3740651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if (VarTemplatePartialSpecializationDecl *PartialSpec =
3741651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines          dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3742651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    IsMemberSpec = PartialSpec->isMemberSpecialization();
3743651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3744651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    IsMemberSpec = FromTemplate->isMemberSpecialization();
3745651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if (!IsMemberSpec)
3746651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    FromVar = FromVar->getFirstDecl();
3747d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
37482e563c28c456b48f43f38f5a92a4bc292d5cda91Manuel Klimek  MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
37492e563c28c456b48f43f38f5a92a4bc292d5cda91Manuel Klimek  TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
37502e563c28c456b48f43f38f5a92a4bc292d5cda91Manuel Klimek                                        MultiLevelList);
3751ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3752ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // TODO: Set LateAttrs and StartingScope ...
3753ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3754ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  return cast_or_null<VarTemplateSpecializationDecl>(
3755ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      Instantiator.VisitVarTemplateSpecializationDecl(
3756ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo          VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3757ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
3758ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3759ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// \brief Instantiates a variable template specialization by completing it
3760ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// with appropriate type information and initializer.
3761ef4579cda09b73e3d4d98af48201da25adc29326Larisse VoufoVarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3762ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3763ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    const MultiLevelTemplateArgumentList &TemplateArgs) {
3764ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3765ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Do substitution on the type of the declaration
3766ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  TypeSourceInfo *DI =
3767d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3768ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3769ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (!DI)
37706bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
3771ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3772ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Update the type of this variable template specialization.
3773ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarSpec->setType(DI->getType());
3774ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3775ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Instantiate the initializer.
3776ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3777ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3778ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  return VarSpec;
3779ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
3780ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3781ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// BuildVariableInstantiation - Used after a new variable has been created.
3782ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// Sets basic variable data and decides whether to postpone the
3783ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// variable instantiation.
3784ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufovoid Sema::BuildVariableInstantiation(
3785ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarDecl *NewVar, VarDecl *OldVar,
3786ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    const MultiLevelTemplateArgumentList &TemplateArgs,
3787a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3788a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    LocalInstantiationScope *StartingScope,
3789567f917df048d42732997a479b2b257403fc88efLarisse Voufo    bool InstantiatingVarTemplate) {
3790ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3791a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  // If we are instantiating a local extern declaration, the
3792a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  // instantiation belongs lexically to the containing function.
3793ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // If we are instantiating a static data member defined
3794ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // out-of-line, the instantiation will have the same lexical
3795ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // context (which will be a namespace scope) as the template.
3796a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  if (OldVar->isLocalExternDecl()) {
3797a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    NewVar->setLocalExternDecl();
3798a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    NewVar->setLexicalDeclContext(Owner);
3799a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  } else if (OldVar->isOutOfLine())
3800ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3801ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  NewVar->setTSCSpec(OldVar->getTSCSpec());
3802ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  NewVar->setInitStyle(OldVar->getInitStyle());
3803ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3804ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  NewVar->setConstexpr(OldVar->isConstexpr());
380504fa7a33279808dc3e5117c41b5f84c40eeb7362Richard Smith  NewVar->setInitCapture(OldVar->isInitCapture());
3806dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith  NewVar->setPreviousDeclInSameBlockScope(
3807dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith      OldVar->isPreviousDeclInSameBlockScope());
3808ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  NewVar->setAccess(OldVar->getAccess());
3809ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
381090618ff0b53f063a880c4933d44c70d6c1cb8dc0Richard Smith  if (!OldVar->isStaticDataMember()) {
3811e7bd89af8aa96a779c0031baf1a21e960a51d0f0Rafael Espindola    if (OldVar->isUsed(false))
3812e7bd89af8aa96a779c0031baf1a21e960a51d0f0Rafael Espindola      NewVar->setIsUsed();
3813ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    NewVar->setReferenced(OldVar->isReferenced());
3814ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
3815ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3816ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3817ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3818a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  LookupResult Previous(
3819a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith      *this, NewVar->getDeclName(), NewVar->getLocation(),
3820a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith      NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3821a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith                                  : Sema::LookupOrdinaryName,
3822a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith      Sema::ForRedeclaration);
3823ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3824651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3825651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3826651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines       OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3827dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith    // We have a previous declaration. Use that one, so we merge with the
3828dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith    // right type.
3829dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith    if (NamedDecl *NewPrev = FindInstantiatedDecl(
3830dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith            NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3831dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith      Previous.addDecl(NewPrev);
3832dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith  } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3833dd9459f8869f66409f7ea429053b453e33f6499cRichard Smith             OldVar->hasLinkage())
3834ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3835567f917df048d42732997a479b2b257403fc88efLarisse Voufo  CheckVariableDeclaration(NewVar, Previous);
3836ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3837a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  if (!InstantiatingVarTemplate) {
3838a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3839a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith    if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3840ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3841a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  }
3842a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith
3843a41c97a5d1912ffd184381d269fd8e5a25ee5e59Richard Smith  if (!OldVar->isOutOfLine()) {
3844ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    if (NewVar->getDeclContext()->isFunctionOrMethod())
3845ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3846ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
3847ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3848ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Link instantiations of static data members back to the template from
3849ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // which they were instantiated.
3850567f917df048d42732997a479b2b257403fc88efLarisse Voufo  if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3851ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    NewVar->setInstantiationOfStaticDataMember(OldVar,
3852ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                                               TSK_ImplicitInstantiation);
3853ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3854651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  // Forward the mangling number from the template to the instantiated decl.
3855651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3856651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3857651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines
38584967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // Delay instantiation of the initializer for variable templates or inline
38594967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // static data members until a definition of the variable is needed. We need
38604967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // it right away if the type contains 'auto'.
3861651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
38624967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar       !InstantiatingVarTemplate &&
38634967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar       !(OldVar->isInline() && OldVar->isThisDeclarationADefinition())) ||
3864651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines      NewVar->getType()->isUndeducedType())
3865ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3866ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3867ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // Diagnose unused local variables with dependent types, where the diagnostic
3868ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // will have been deferred.
3869ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (!NewVar->isInvalidDecl() &&
3870176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      NewVar->getDeclContext()->isFunctionOrMethod() &&
3871ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      OldVar->getType()->isDependentType())
3872ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    DiagnoseUnusedDecl(NewVar);
3873ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
3874ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3875ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo/// \brief Instantiate the initializer of a variable.
3876ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufovoid Sema::InstantiateVariableInitializer(
3877ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    VarDecl *Var, VarDecl *OldVar,
3878ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    const MultiLevelTemplateArgumentList &TemplateArgs) {
38794967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // We propagate the 'inline' flag with the initializer, because it
38804967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // would otherwise imply that the variable is a definition for a
38814967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // non-static data member.
38824967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (OldVar->isInlineSpecified())
38834967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Var->setInlineSpecified();
38844967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  else if (OldVar->isInline())
38854967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Var->setImplicitlyInline();
3886ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3887ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (Var->getAnyInitializer())
3888ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // We already have an initializer in the class.
3889ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    return;
3890ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3891ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (OldVar->getInit()) {
3892ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3893ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3894ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    else
3895ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3896ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3897ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // Instantiate the initializer.
38984967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    ExprResult Init;
38994967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
39004967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    {
39014967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      ContextRAII SwitchContext(*this, Var->getDeclContext());
39024967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
39034967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                              OldVar->getInitStyle() == VarDecl::CallInit);
39044967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    }
39054967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
3906ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    if (!Init.isInvalid()) {
3907ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      bool TypeMayContainAuto = true;
3908c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      Expr *InitExpr = Init.get();
3909c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines
3910176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      if (Var->hasAttr<DLLImportAttr>() &&
3911176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines          (!InitExpr ||
3912176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines           !InitExpr->isConstantInitializer(getASTContext(), false))) {
3913c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines        // Do not dynamically initialize dllimport variables.
3914c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      } else if (InitExpr) {
3915ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        bool DirectInit = OldVar->isDirectInit();
3916c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines        AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
3917ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      } else
3918ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        ActOnUninitializedDecl(Var, TypeMayContainAuto);
3919ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    } else {
3920ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      // FIXME: Not too happy about invalidating the declaration
3921ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      // because of a bogus initializer.
3922ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      Var->setInvalidDecl();
3923ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    }
3924ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3925ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    PopExpressionEvaluationContext();
3926ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3927ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo             !Var->isCXXForRangeDecl())
3928ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    ActOnUninitializedDecl(Var, false);
3929ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
3930ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3931a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor/// \brief Instantiate the definition of the given variable from its
3932a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor/// template.
3933a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor///
39347caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor/// \param PointOfInstantiation the point at which the instantiation was
39357caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor/// required. Note that this is not precisely a "point of instantiation"
39367caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor/// for the function, but it's close.
39377caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor///
39387caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor/// \param Var the already-instantiated declaration of a static member
39397caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor/// variable of a class template specialization.
39407caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor///
39417caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor/// \param Recursive if true, recursively instantiates any functions that
39427caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor/// are required by this instantiation.
3943e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor///
3944e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor/// \param DefinitionRequired if true, then we are performing an explicit
3945e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor/// instantiation where an out-of-line definition of the member variable
3946e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor/// is required. Complain if there is no such definition.
39477caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregorvoid Sema::InstantiateStaticDataMemberDefinition(
39487caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor                                          SourceLocation PointOfInstantiation,
39497caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor                                                 VarDecl *Var,
3950e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor                                                 bool Recursive,
3951e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor                                                 bool DefinitionRequired) {
3952ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3953ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                                DefinitionRequired);
3954ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo}
3955ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3956ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufovoid Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3957ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                                         VarDecl *Var, bool Recursive,
39584967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                      bool DefinitionRequired, bool AtEndOfTU) {
39597caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  if (Var->isInvalidDecl())
39607caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    return;
39611eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
3962ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  VarTemplateSpecializationDecl *VarSpec =
3963ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      dyn_cast<VarTemplateSpecializationDecl>(Var);
39646bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  VarDecl *PatternDecl = nullptr, *Def = nullptr;
3965d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  MultiLevelTemplateArgumentList TemplateArgs =
3966d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      getTemplateInstantiationArgs(Var);
3967ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3968ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (VarSpec) {
3969d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // If this is a variable template specialization, make sure that it is
3970d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // non-dependent, then find its instantiation pattern.
3971ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    bool InstantiationDependent = false;
3972ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3973ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo               VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3974ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo           "Only instantiate variable template specializations that are "
3975ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo           "not type-dependent");
39763151b7c6dd49947b0a91b3e22c31f4864629e355Larisse Voufo    (void)InstantiationDependent;
3977ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
3978d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // Find the variable initialization that we'll be substituting. If the
3979d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // pattern was instantiated from a member template, look back further to
3980d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // find the real pattern.
3981ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    assert(VarSpec->getSpecializedTemplate() &&
3982ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo           "Specialization without specialized template?");
3983ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    llvm::PointerUnion<VarTemplateDecl *,
3984ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                       VarTemplatePartialSpecializationDecl *> PatternPtr =
3985ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        VarSpec->getSpecializedTemplateOrPartial();
3986439d665f4d1066ee5ebd8dd0938d85be83d490c4Larisse Voufo    if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3987d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      VarTemplatePartialSpecializationDecl *Tmpl =
3988d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith          PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3989d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      while (VarTemplatePartialSpecializationDecl *From =
3990d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith                 Tmpl->getInstantiatedFromMember()) {
3991d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        if (Tmpl->isMemberSpecialization())
3992d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith          break;
3993439d665f4d1066ee5ebd8dd0938d85be83d490c4Larisse Voufo
3994d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        Tmpl = From;
3995d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      }
3996d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      PatternDecl = Tmpl;
3997439d665f4d1066ee5ebd8dd0938d85be83d490c4Larisse Voufo    } else {
3998d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3999d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      while (VarTemplateDecl *From =
4000d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith                 Tmpl->getInstantiatedFromMemberTemplate()) {
4001d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        if (Tmpl->isMemberSpecialization())
4002d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith          break;
4003d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4004d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        Tmpl = From;
4005d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      }
4006d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      PatternDecl = Tmpl->getTemplatedDecl();
4007d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    }
4008d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4009d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // If this is a static data member template, there might be an
4010d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // uninstantiated initializer on the declaration. If so, instantiate
4011d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // it now.
4012d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    if (PatternDecl->isStaticDataMember() &&
4013bc6509175e1ce5cc1b48d1b97ac8d23d8b74167cRafael Espindola        (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4014d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        !Var->hasInit()) {
4015d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // FIXME: Factor out the duplicated instantiation context setup/tear down
4016d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // code here.
4017d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4018d69f37b5822420e3c3a1b2e875b122aca8248533Alp Toker      if (Inst.isInvalid())
4019d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        return;
40204967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
40214967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                          "instantiating variable initializer");
4022d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4023d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // If we're performing recursive template instantiation, create our own
4024d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // queue of pending implicit instantiations that we will instantiate
4025d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // later, while we're still within our own instantiation context.
40260e2c34f92f00628d48968dfea096d36381f494cbStephen Hines      SavePendingInstantiationsAndVTableUsesRAII
40270e2c34f92f00628d48968dfea096d36381f494cbStephen Hines          SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4028d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4029d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      LocalInstantiationScope Local(*this);
4030d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4031d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // Enter the scope of this instantiation. We don't use
4032d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // PushDeclContext because we don't have a scope.
4033d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      ContextRAII PreviousContext(*this, Var->getDeclContext());
4034d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4035d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      PreviousContext.pop();
4036d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4037d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // FIXME: Need to inform the ASTConsumer that we instantiated the
4038d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // initializer?
4039d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4040d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // This variable may have local implicit instantiations that need to be
4041d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // instantiated within this scope.
4042d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      PerformPendingInstantiations(/*LocalOnly=*/true);
4043d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4044d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      Local.Exit();
4045d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4046d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      if (Recursive) {
4047d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        // Define any newly required vtables.
4048d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        DefineUsedVTables();
4049d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4050d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        // Instantiate any pending implicit instantiations found during the
4051d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        // instantiation of this template.
4052d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        PerformPendingInstantiations();
4053439d665f4d1066ee5ebd8dd0938d85be83d490c4Larisse Voufo
40540e2c34f92f00628d48968dfea096d36381f494cbStephen Hines        // PendingInstantiations and VTableUses are restored through
40550e2c34f92f00628d48968dfea096d36381f494cbStephen Hines        // SavePendingInstantiationsAndVTableUses's destructor.
4056d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      }
4057439d665f4d1066ee5ebd8dd0938d85be83d490c4Larisse Voufo    }
4058ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
4059d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // Find actual definition
4060d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    Def = PatternDecl->getDefinition(getASTContext());
4061d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  } else {
4062d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // If this is a static data member, find its out-of-line definition.
4063d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    assert(Var->isStaticDataMember() && "not a static data member?");
4064d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    PatternDecl = Var->getInstantiatedFromStaticDataMember();
4065d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4066d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    assert(PatternDecl && "data member was not instantiated from a template?");
4067d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    assert(PatternDecl->isStaticDataMember() && "not a static data member?");
40684967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    Def = PatternDecl->getDefinition();
4069ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
4070ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
40714967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // FIXME: Check that the definition is visible before trying to instantiate
40724967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // it. This requires us to track the instantiation stack in order to know
40734967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  // which definitions should be visible.
40744967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar
4075d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // If we don't have a definition of the variable template, we won't perform
4076d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // any instantiation. Rather, we rely on the user to instantiate this
4077d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // definition (or provide a specialization for it) in another translation
4078d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // unit.
4079d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  if (!Def) {
4080e2d3a3de71b2fa35614cb732a6da95a41fa38ad9Douglas Gregor    if (DefinitionRequired) {
4081d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      if (VarSpec)
4082ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        Diag(PointOfInstantiation,
4083d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith             diag::err_explicit_instantiation_undefined_var_template) << Var;
4084d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      else
4085ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        Diag(PointOfInstantiation,
4086ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo             diag::err_explicit_instantiation_undefined_member)
4087d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith            << 2 << Var->getDeclName() << Var->getDeclContext();
4088d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      Diag(PatternDecl->getLocation(),
4089d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith           diag::note_explicit_instantiation_here);
4090ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      if (VarSpec)
4091ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        Var->setInvalidDecl();
409258e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth    } else if (Var->getTemplateSpecializationKind()
409358e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth                 == TSK_ExplicitInstantiationDefinition) {
409462c78d54bee499dd87f768f48b21c9b5ec15e516Chandler Carruth      PendingInstantiations.push_back(
409558e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth        std::make_pair(Var, PointOfInstantiation));
40964967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    } else if (Var->getTemplateSpecializationKind()
40974967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                 == TSK_ImplicitInstantiation) {
40984967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      // Warn about missing definition at the end of translation unit.
40994967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
41004967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        Diag(PointOfInstantiation, diag::warn_var_template_missing)
41014967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          << Var;
41024967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
41034967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar        if (getLangOpts().CPlusPlus11)
41044967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar          Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
41054967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar      }
410658e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth    }
410758e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth
41087caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    return;
41097caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  }
41107caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor
4111234fe654a3dd2888be42ae5db34db96c5c2c4ba3Rafael Espindola  TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
4112234fe654a3dd2888be42ae5db34db96c5c2c4ba3Rafael Espindola
4113251b4ff2578e26959a4c036140ccd61c5e9292f2Douglas Gregor  // Never instantiate an explicit specialization.
4114234fe654a3dd2888be42ae5db34db96c5c2c4ba3Rafael Espindola  if (TSK == TSK_ExplicitSpecialization)
4115251b4ff2578e26959a4c036140ccd61c5e9292f2Douglas Gregor    return;
4116a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
4117ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // C++11 [temp.explicit]p10:
4118ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  //   Except for inline functions, [...] explicit instantiation declarations
4119ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  //   have the effect of suppressing the implicit instantiation of the entity
4120ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  //   to which they refer.
4121234fe654a3dd2888be42ae5db34db96c5c2c4ba3Rafael Espindola  if (TSK == TSK_ExplicitInstantiationDeclaration)
4122251b4ff2578e26959a4c036140ccd61c5e9292f2Douglas Gregor    return;
41231eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4124afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis  // Make sure to pass the instantiated variable to the consumer at the end.
4125afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis  struct PassToConsumerRAII {
4126afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis    ASTConsumer &Consumer;
4127afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis    VarDecl *Var;
4128afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis
4129afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis    PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4130afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis      : Consumer(Consumer), Var(Var) { }
4131afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis
4132afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis    ~PassToConsumerRAII() {
4133d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4134afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis    }
4135afda905e60151f0bc34c187d51a798b4265f69afArgyrios Kyrtzidis  } PassToConsumerRAII(Consumer, Var);
4136025039377d7247620750205dbd61ca1ba336f7e0Rafael Espindola
4137d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  // If we already have a definition, we're done.
4138d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  if (VarDecl *Def = Var->getDefinition()) {
4139d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // We may be explicitly instantiating something we've already implicitly
4140d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // instantiated.
4141d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4142d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith                                       PointOfInstantiation);
4143d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    return;
414495e3872918557b55b62121a7df5f1ee76d45881aNick Lewycky  }
4145f15748a28c8443eef2924ef83689c358c661e9c5Douglas Gregor
41467caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4147d69f37b5822420e3c3a1b2e875b122aca8248533Alp Toker  if (Inst.isInvalid())
41487caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    return;
41494967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
41504967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                      "instantiating variable definition");
41511eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
41527caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  // If we're performing recursive template instantiation, create our own
41537caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  // queue of pending implicit instantiations that we will instantiate later,
41547caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  // while we're still within our own instantiation context.
415565173e04eacb68ff89a58fbff14979eb318896c9Bill Wendling  SavePendingLocalImplicitInstantiationsRAII
415665173e04eacb68ff89a58fbff14979eb318896c9Bill Wendling      SavedPendingLocalImplicitInstantiations(*this);
41570e2c34f92f00628d48968dfea096d36381f494cbStephen Hines  SavePendingInstantiationsAndVTableUsesRAII
41580e2c34f92f00628d48968dfea096d36381f494cbStephen Hines      SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
41591eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
41607caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  // Enter the scope of this instantiation. We don't use
41617caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  // PushDeclContext because we don't have a scope.
4162ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  ContextRAII PreviousContext(*this, Var->getDeclContext());
41637bdc15252ca2415f149ad812f0e5184d758e6105Douglas Gregor  LocalInstantiationScope Local(*this);
4164ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
41651028c9f0afc1cc5f4951b39b7067fa57c1fea07bDouglas Gregor  VarDecl *OldVar = Var;
41664967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
41674967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    // We're instantiating an inline static data member whose definition was
41684967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    // provided inside the class.
41694967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    // FIXME: Update record?
41704967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar    InstantiateVariableInitializer(Var, Def, TemplateArgs);
41714967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  } else if (!VarSpec) {
4172ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4173d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith                                          TemplateArgs));
41744967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar  } else if (Var->isStaticDataMember() &&
41754967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar             Var->getLexicalDeclContext()->isRecord()) {
4176d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // We need to instantiate the definition of a static data member template,
4177d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // and all we have is the in-class declaration of it. Instantiate a separate
4178d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // declaration of the definition.
4179d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4180d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith                                          TemplateArgs);
4181d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
41826bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines        VarSpec->getSpecializedTemplate(), Def, nullptr,
4183d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4184d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    if (Var) {
4185d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      llvm::PointerUnion<VarTemplateDecl *,
4186d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith                         VarTemplatePartialSpecializationDecl *> PatternPtr =
4187d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith          VarSpec->getSpecializedTemplateOrPartial();
4188d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      if (VarTemplatePartialSpecializationDecl *Partial =
4189d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith          PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4190d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith        cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4191d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith            Partial, &VarSpec->getTemplateInstantiationArgs());
4192d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4193d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // Merge the definition with the declaration.
4194d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4195d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith                     LookupOrdinaryName, ForRedeclaration);
4196d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      R.addDecl(OldVar);
4197d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      MergeVarDecl(Var, R);
4198d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith
4199d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      // Attach the initializer.
4200d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith      InstantiateVariableInitializer(Var, Def, TemplateArgs);
4201d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    }
4202d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith  } else
4203d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // Complete the existing variable's definition with an appropriately
4204d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    // substituted type and initializer.
4205d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4206f5ba7e089daadcd60b0f6e31d932be8bb6045281John McCall
4207ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  PreviousContext.pop();
42087caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor
42097caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  if (Var) {
4210ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    PassToConsumerRAII.Var = Var;
4211d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith    Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4212d0629eb137d06bf6d46a430abdb7fa044909298bRichard Smith                                       OldVar->getPointOfInstantiation());
42137caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  }
4214ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
4215ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // This variable may have local implicit instantiations that need to be
4216ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // instantiated within this scope.
4217ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  PerformPendingInstantiations(/*LocalOnly=*/true);
4218ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
42197bdc15252ca2415f149ad812f0e5184d758e6105Douglas Gregor  Local.Exit();
42207bdc15252ca2415f149ad812f0e5184d758e6105Douglas Gregor
42217caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  if (Recursive) {
42228155910a192dafa423d6b932b7d127d48e4641e8Nick Lewycky    // Define any newly required vtables.
42238155910a192dafa423d6b932b7d127d48e4641e8Nick Lewycky    DefineUsedVTables();
42248155910a192dafa423d6b932b7d127d48e4641e8Nick Lewycky
42257caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    // Instantiate any pending implicit instantiations found during the
42261eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump    // instantiation of this template.
422762c78d54bee499dd87f768f48b21c9b5ec15e516Chandler Carruth    PerformPendingInstantiations();
42281eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
42290e2c34f92f00628d48968dfea096d36381f494cbStephen Hines    // PendingInstantiations and VTableUses are restored through
42300e2c34f92f00628d48968dfea096d36381f494cbStephen Hines    // SavePendingInstantiationsAndVTableUses's destructor.
42311eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  }
4232a58861f6490780baec50689e06ca65f7438b85dcDouglas Gregor}
4233815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
4234090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlssonvoid
4235090253155017b7eec031bbd7bf07824a448e1d7aAnders CarlssonSema::InstantiateMemInitializers(CXXConstructorDecl *New,
4236090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson                                 const CXXConstructorDecl *Tmpl,
4237090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson                           const MultiLevelTemplateArgumentList &TemplateArgs) {
42381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
423990ab75b5ad328d2b155ec83fd4e80cd0f7af5729Richard Trieu  SmallVector<CXXCtorInitializer*, 4> NewInits;
424054b3ba8cf2eb4886a88cdb8adedb15f43333ff1dRichard Smith  bool AnyErrors = Tmpl->isInvalidDecl();
4241a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
4242090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson  // Instantiate all the initializers.
4243651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  for (const auto *Init : Tmpl->inits()) {
4244030ef472f31709e175895853fcb43d61d09022c7Chandler Carruth    // Only instantiate written initializers, let Sema re-construct implicit
4245030ef472f31709e175895853fcb43d61d09022c7Chandler Carruth    // ones.
4246030ef472f31709e175895853fcb43d61d09022c7Chandler Carruth    if (!Init->isWritten())
4247030ef472f31709e175895853fcb43d61d09022c7Chandler Carruth      continue;
4248030ef472f31709e175895853fcb43d61d09022c7Chandler Carruth
42493fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor    SourceLocation EllipsisLoc;
4250a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
42513fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor    if (Init->isPackExpansion()) {
42523fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor      // This is a pack expansion. We should expand it now.
425376852c218a207ef43583515cb835b6e855353a0fDouglas Gregor      TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
425498a75581e155a7dac853a69b0151960f8e2aacbdNick Lewycky      SmallVector<UnexpandedParameterPack, 4> Unexpanded;
42553fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor      collectUnexpandedParameterPacks(BaseTL, Unexpanded);
425698a75581e155a7dac853a69b0151960f8e2aacbdNick Lewycky      collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
42573fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor      bool ShouldExpand = false;
4258d3731198193eee92796ddeb493973b7a598b003eDouglas Gregor      bool RetainExpansion = false;
4259dc84cd5efdd3430efb22546b4ac656aa0540b210David Blaikie      Optional<unsigned> NumExpansions;
4260a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi      if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
42613fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor                                          BaseTL.getSourceRange(),
4262a71f9d0a5e1f8cafdd23a17e292de22fdc8e99ffDavid Blaikie                                          Unexpanded,
4263a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                          TemplateArgs, ShouldExpand,
4264d3731198193eee92796ddeb493973b7a598b003eDouglas Gregor                                          RetainExpansion,
42653fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor                                          NumExpansions)) {
42663fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        AnyErrors = true;
42673fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        New->setInvalidDecl();
42683fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        continue;
42693fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor      }
42703fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor      assert(ShouldExpand && "Partial instantiation of base initializer?");
4271a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
4272a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi      // Loop over all of the arguments in the argument pack(s),
4273cded4f649cd4b7ba7d461c25c6482ef52b8d3a2aDouglas Gregor      for (unsigned I = 0; I != *NumExpansions; ++I) {
42743fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
42753fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor
42763fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        // Instantiate the initializer.
42775b9cc5df25c2198f270dd1d5c438fdce70d4051dSebastian Redl        ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
42785b9cc5df25c2198f270dd1d5c438fdce70d4051dSebastian Redl                                               /*CXXDirectInit=*/true);
42795b9cc5df25c2198f270dd1d5c438fdce70d4051dSebastian Redl        if (TempInit.isInvalid()) {
42803fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor          AnyErrors = true;
42813fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor          break;
42823fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        }
42833fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor
42843fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        // Instantiate the base type.
428576852c218a207ef43583515cb835b6e855353a0fDouglas Gregor        TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4286a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                              TemplateArgs,
4287a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi                                              Init->getSourceLocation(),
42883fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor                                              New->getDeclName());
42893fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        if (!BaseTInfo) {
42903fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor          AnyErrors = true;
42913fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor          break;
42923fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        }
42933fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor
42943fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        // Build the initializer.
42956df6548e44a61c444bd85dccd0398cba047c79b1Sebastian Redl        MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4296c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines                                                     BaseTInfo, TempInit.get(),
42973fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor                                                     New->getParent(),
42983fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor                                                     SourceLocation());
42993fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        if (NewInit.isInvalid()) {
43003fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor          AnyErrors = true;
43013fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor          break;
43023fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        }
4303a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
43043fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor        NewInits.push_back(NewInit.get());
43053fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor      }
4306a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
43073fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor      continue;
43083fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor    }
43093fb9e4b89f72823f162096086f0f964e6dcf66d6Douglas Gregor
43106b98b2e5f33ce2dcdb7fa385f7e21672d49f1a69Douglas Gregor    // Instantiate the initializer.
43115b9cc5df25c2198f270dd1d5c438fdce70d4051dSebastian Redl    ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
43125b9cc5df25c2198f270dd1d5c438fdce70d4051dSebastian Redl                                           /*CXXDirectInit=*/true);
43135b9cc5df25c2198f270dd1d5c438fdce70d4051dSebastian Redl    if (TempInit.isInvalid()) {
43146b98b2e5f33ce2dcdb7fa385f7e21672d49f1a69Douglas Gregor      AnyErrors = true;
43156b98b2e5f33ce2dcdb7fa385f7e21672d49f1a69Douglas Gregor      continue;
4316090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson    }
4317a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
4318090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson    MemInitResult NewInit;
431976852c218a207ef43583515cb835b6e855353a0fDouglas Gregor    if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
432076852c218a207ef43583515cb835b6e855353a0fDouglas Gregor      TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
432176852c218a207ef43583515cb835b6e855353a0fDouglas Gregor                                        TemplateArgs,
432276852c218a207ef43583515cb835b6e855353a0fDouglas Gregor                                        Init->getSourceLocation(),
432376852c218a207ef43583515cb835b6e855353a0fDouglas Gregor                                        New->getDeclName());
432476852c218a207ef43583515cb835b6e855353a0fDouglas Gregor      if (!TInfo) {
43259db7dbb918ca49f4ee6c181e4917e7b6ec547353Douglas Gregor        AnyErrors = true;
4326802ab45fea51beff12f386329d4928811a479c6eDouglas Gregor        New->setInvalidDecl();
4327802ab45fea51beff12f386329d4928811a479c6eDouglas Gregor        continue;
4328802ab45fea51beff12f386329d4928811a479c6eDouglas Gregor      }
43296df6548e44a61c444bd85dccd0398cba047c79b1Sebastian Redl
433076852c218a207ef43583515cb835b6e855353a0fDouglas Gregor      if (Init->isBaseInitializer())
4331c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines        NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
433276852c218a207ef43583515cb835b6e855353a0fDouglas Gregor                                       New->getParent(), EllipsisLoc);
433376852c218a207ef43583515cb835b6e855353a0fDouglas Gregor      else
4334c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines        NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
433576852c218a207ef43583515cb835b6e855353a0fDouglas Gregor                                  cast<CXXRecordDecl>(CurContext->getParent()));
4336090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson    } else if (Init->isMemberInitializer()) {
4337b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor      FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
433800eb3f9c5b33e3d99aee1f8b75dd9c9678fdd66bFrancois Pichet                                                     Init->getMemberLocation(),
433900eb3f9c5b33e3d99aee1f8b75dd9c9678fdd66bFrancois Pichet                                                     Init->getMember(),
434000eb3f9c5b33e3d99aee1f8b75dd9c9678fdd66bFrancois Pichet                                                     TemplateArgs));
4341b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor      if (!Member) {
4342b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor        AnyErrors = true;
4343b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor        New->setInvalidDecl();
4344b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor        continue;
4345b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor      }
43461eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4347c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      NewInit = BuildMemberInitializer(Member, TempInit.get(),
43486df6548e44a61c444bd85dccd0398cba047c79b1Sebastian Redl                                       Init->getSourceLocation());
434900eb3f9c5b33e3d99aee1f8b75dd9c9678fdd66bFrancois Pichet    } else if (Init->isIndirectMemberInitializer()) {
435000eb3f9c5b33e3d99aee1f8b75dd9c9678fdd66bFrancois Pichet      IndirectFieldDecl *IndirectMember =
4351b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor         cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
435200eb3f9c5b33e3d99aee1f8b75dd9c9678fdd66bFrancois Pichet                                 Init->getMemberLocation(),
435300eb3f9c5b33e3d99aee1f8b75dd9c9678fdd66bFrancois Pichet                                 Init->getIndirectMember(), TemplateArgs));
435400eb3f9c5b33e3d99aee1f8b75dd9c9678fdd66bFrancois Pichet
4355b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor      if (!IndirectMember) {
4356b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor        AnyErrors = true;
4357b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor        New->setInvalidDecl();
43586df6548e44a61c444bd85dccd0398cba047c79b1Sebastian Redl        continue;
4359b710722d2348cd0945d2b4f02062c7f685146eb0Douglas Gregor      }
43606df6548e44a61c444bd85dccd0398cba047c79b1Sebastian Redl
4361c568f1e98938584c0ef0b12ae5018ff7d90a4072Stephen Hines      NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
43626df6548e44a61c444bd85dccd0398cba047c79b1Sebastian Redl                                       Init->getSourceLocation());
4363090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson    }
4364090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson
43659db7dbb918ca49f4ee6c181e4917e7b6ec547353Douglas Gregor    if (NewInit.isInvalid()) {
43669db7dbb918ca49f4ee6c181e4917e7b6ec547353Douglas Gregor      AnyErrors = true;
4367090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson      New->setInvalidDecl();
43689db7dbb918ca49f4ee6c181e4917e7b6ec547353Douglas Gregor    } else {
436990ab75b5ad328d2b155ec83fd4e80cd0f7af5729Richard Trieu      NewInits.push_back(NewInit.get());
4370090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson    }
4371090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson  }
43721eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4373090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson  // Assign all the initializers to the new constructor.
4374d226f65006733ed7f709c3174f22ce33391cb58fJohn McCall  ActOnMemInitializers(New,
4375090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson                       /*FIXME: ColonLoc */
4376090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson                       SourceLocation(),
437793c8617bec98aeb769ee9f569d7ed439eec03249David Blaikie                       NewInits,
43789db7dbb918ca49f4ee6c181e4917e7b6ec547353Douglas Gregor                       AnyErrors);
4379090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson}
4380090253155017b7eec031bbd7bf07824a448e1d7aAnders Carlsson
438152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall// TODO: this could be templated if the various decl types used the
438252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall// same method name.
438352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCallstatic bool isInstantiationOf(ClassTemplateDecl *Pattern,
438452a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall                              ClassTemplateDecl *Instance) {
438552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  Pattern = Pattern->getCanonicalDecl();
438652a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
438752a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  do {
438852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getCanonicalDecl();
438952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    if (Pattern == Instance) return true;
439052a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getInstantiatedFromMemberTemplate();
439152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  } while (Instance);
439252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
439352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  return false;
439452a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall}
439552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
43960d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregorstatic bool isInstantiationOf(FunctionTemplateDecl *Pattern,
43970d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor                              FunctionTemplateDecl *Instance) {
43980d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor  Pattern = Pattern->getCanonicalDecl();
4399a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
44000d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor  do {
44010d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor    Instance = Instance->getCanonicalDecl();
44020d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor    if (Pattern == Instance) return true;
44030d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor    Instance = Instance->getInstantiatedFromMemberTemplate();
44040d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor  } while (Instance);
4405a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
44060d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor  return false;
44070d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor}
44080d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor
4409a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumistatic bool
4410ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas GregorisInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4411ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                  ClassTemplatePartialSpecializationDecl *Instance) {
4412a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi  Pattern
4413ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4414ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  do {
4415ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    Instance = cast<ClassTemplatePartialSpecializationDecl>(
4416ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                                                Instance->getCanonicalDecl());
4417ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    if (Pattern == Instance)
4418ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor      return true;
4419ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    Instance = Instance->getInstantiatedFromMember();
4420ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  } while (Instance);
4421a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
4422ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  return false;
4423ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor}
4424ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor
442552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCallstatic bool isInstantiationOf(CXXRecordDecl *Pattern,
442652a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall                              CXXRecordDecl *Instance) {
442752a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  Pattern = Pattern->getCanonicalDecl();
442852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
442952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  do {
443052a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getCanonicalDecl();
443152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    if (Pattern == Instance) return true;
443252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getInstantiatedFromMemberClass();
443352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  } while (Instance);
443452a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
443552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  return false;
443652a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall}
443752a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
443852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCallstatic bool isInstantiationOf(FunctionDecl *Pattern,
443952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall                              FunctionDecl *Instance) {
444052a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  Pattern = Pattern->getCanonicalDecl();
444152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
444252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  do {
444352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getCanonicalDecl();
444452a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    if (Pattern == Instance) return true;
444552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getInstantiatedFromMemberFunction();
444652a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  } while (Instance);
444752a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
444852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  return false;
444952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall}
445052a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
445152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCallstatic bool isInstantiationOf(EnumDecl *Pattern,
445252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall                              EnumDecl *Instance) {
445352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  Pattern = Pattern->getCanonicalDecl();
445452a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
445552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  do {
445652a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getCanonicalDecl();
445752a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    if (Pattern == Instance) return true;
445852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getInstantiatedFromMemberEnum();
445952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  } while (Instance);
446052a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
446152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  return false;
446252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall}
446352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
4464ed97649e9574b9d854fa4d6109c9333ae0993554John McCallstatic bool isInstantiationOf(UsingShadowDecl *Pattern,
4465ed97649e9574b9d854fa4d6109c9333ae0993554John McCall                              UsingShadowDecl *Instance,
4466ed97649e9574b9d854fa4d6109c9333ae0993554John McCall                              ASTContext &C) {
4467176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4468176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                            Pattern);
4469ed97649e9574b9d854fa4d6109c9333ae0993554John McCall}
4470ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
4471ed97649e9574b9d854fa4d6109c9333ae0993554John McCallstatic bool isInstantiationOf(UsingDecl *Pattern,
4472ed97649e9574b9d854fa4d6109c9333ae0993554John McCall                              UsingDecl *Instance,
4473ed97649e9574b9d854fa4d6109c9333ae0993554John McCall                              ASTContext &C) {
4474176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4475ed97649e9574b9d854fa4d6109c9333ae0993554John McCall}
4476ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
44777ba107a1863ddfa1664555854f0d7bdb3c491c92John McCallstatic bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
44787ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall                              UsingDecl *Instance,
44797ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall                              ASTContext &C) {
4480176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
44817ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall}
44827ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall
44837ba107a1863ddfa1664555854f0d7bdb3c491c92John McCallstatic bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
44840d8df780aef1acda5962347a32591efc629b6748Anders Carlsson                              UsingDecl *Instance,
44850d8df780aef1acda5962347a32591efc629b6748Anders Carlsson                              ASTContext &C) {
4486176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines  return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
44870d8df780aef1acda5962347a32591efc629b6748Anders Carlsson}
44880d8df780aef1acda5962347a32591efc629b6748Anders Carlsson
448952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCallstatic bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
449052a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall                                              VarDecl *Instance) {
449152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  assert(Instance->isStaticDataMember());
449252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
449352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  Pattern = Pattern->getCanonicalDecl();
449452a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
449552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  do {
449652a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getCanonicalDecl();
449752a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    if (Pattern == Instance) return true;
449852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    Instance = Instance->getInstantiatedFromStaticDataMember();
449952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  } while (Instance);
450052a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
450152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  return false;
450252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall}
450352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
4504ed97649e9574b9d854fa4d6109c9333ae0993554John McCall// Other is the prospective instantiation
4505ed97649e9574b9d854fa4d6109c9333ae0993554John McCall// D is the prospective pattern
4506815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregorstatic bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
45070d8df780aef1acda5962347a32591efc629b6748Anders Carlsson  if (D->getKind() != Other->getKind()) {
45087ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall    if (UnresolvedUsingTypenameDecl *UUD
45097ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall          = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
45107ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
45117ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall        return isInstantiationOf(UUD, UD, Ctx);
45127ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall      }
45137ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall    }
45147ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall
45157ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall    if (UnresolvedUsingValueDecl *UUD
45167ba107a1863ddfa1664555854f0d7bdb3c491c92John McCall          = dyn_cast<UnresolvedUsingValueDecl>(D)) {
45170d8df780aef1acda5962347a32591efc629b6748Anders Carlsson      if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
45180d8df780aef1acda5962347a32591efc629b6748Anders Carlsson        return isInstantiationOf(UUD, UD, Ctx);
45190d8df780aef1acda5962347a32591efc629b6748Anders Carlsson      }
45200d8df780aef1acda5962347a32591efc629b6748Anders Carlsson    }
4521815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
45220d8df780aef1acda5962347a32591efc629b6748Anders Carlsson    return false;
45230d8df780aef1acda5962347a32591efc629b6748Anders Carlsson  }
45241eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
452552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
452652a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
45271eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
452852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
452952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    return isInstantiationOf(cast<FunctionDecl>(D), Function);
4530815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
453152a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
453252a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    return isInstantiationOf(cast<EnumDecl>(D), Enum);
4533815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
45347caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor  if (VarDecl *Var = dyn_cast<VarDecl>(Other))
453552a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    if (Var->isStaticDataMember())
453652a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall      return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
453752a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
453852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall  if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
453952a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4540a5bf7f13d7772b164750997f95ab18487bbc4114Douglas Gregor
45410d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
45420d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor    return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
45430d696533420fca4cf32694621e3edf582ad4d06eDouglas Gregor
4544ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor  if (ClassTemplatePartialSpecializationDecl *PartialSpec
4545ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor        = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4546ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor    return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4547ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor                             PartialSpec);
4548ed9c0f90b7e0811c209b95e39fe07c211c531285Douglas Gregor
4549d8b285fee4471f393da8ee30f552ceacdc362afaAnders Carlsson  if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4550d8b285fee4471f393da8ee30f552ceacdc362afaAnders Carlsson    if (!Field->getDeclName()) {
4551d8b285fee4471f393da8ee30f552ceacdc362afaAnders Carlsson      // This is an unnamed field.
4552176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4553176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines                                cast<FieldDecl>(D));
4554d8b285fee4471f393da8ee30f552ceacdc362afaAnders Carlsson    }
4555d8b285fee4471f393da8ee30f552ceacdc362afaAnders Carlsson  }
45561eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4557ed97649e9574b9d854fa4d6109c9333ae0993554John McCall  if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4558ed97649e9574b9d854fa4d6109c9333ae0993554John McCall    return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4559ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
4560ed97649e9574b9d854fa4d6109c9333ae0993554John McCall  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4561ed97649e9574b9d854fa4d6109c9333ae0993554John McCall    return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4562ed97649e9574b9d854fa4d6109c9333ae0993554John McCall
4563815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor  return D->getDeclName() && isa<NamedDecl>(Other) &&
4564815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4565815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor}
4566815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
4567815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregortemplate<typename ForwardIterator>
45681eb4433ac451dc16f4133a88af2d002ac26c58efMike Stumpstatic NamedDecl *findInstantiationOf(ASTContext &Ctx,
4569815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor                                      NamedDecl *D,
4570815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor                                      ForwardIterator first,
4571815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor                                      ForwardIterator last) {
4572815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor  for (; first != last; ++first)
4573815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    if (isInstantiationOf(Ctx, D, *first))
4574815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      return cast<NamedDecl>(*first);
4575815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
45766bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines  return nullptr;
4577815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor}
4578815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
457902cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall/// \brief Finds the instantiation of the given declaration context
458002cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall/// within the current instantiation.
458102cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall///
458202cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall/// \returns NULL if there was an error
45837c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas GregorDeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4584e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor                          const MultiLevelTemplateArgumentList &TemplateArgs) {
458502cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
45867c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor    Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
458702cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall    return cast_or_null<DeclContext>(ID);
458802cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall  } else return DC;
458902cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall}
459002cace78cf48cc26686bd5b07c78606abca13bcdJohn McCall
4591ed961e7fffc268eeace169869f5a059bcbd5fcbdDouglas Gregor/// \brief Find the instantiation of the given declaration within the
4592ed961e7fffc268eeace169869f5a059bcbd5fcbdDouglas Gregor/// current instantiation.
4593815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///
4594815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// This routine is intended to be used when \p D is a declaration
4595815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// referenced from within a template, that needs to mapped into the
4596815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// corresponding declaration within an instantiation. For example,
4597815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// given:
4598815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///
4599815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// \code
4600815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// template<typename T>
4601815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// struct X {
4602815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///   enum Kind {
4603815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///     KnownValue = sizeof(T)
4604815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///   };
4605815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///
4606815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///   bool getKind() const { return KnownValue; }
4607815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// };
4608815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///
4609815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// template struct X<int>;
4610815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor/// \endcode
4611815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor///
4612041d10caff48859c0de6d001559a73185f5e0601Serge Pavlov/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4613041d10caff48859c0de6d001559a73185f5e0601Serge Pavlov/// \p EnumConstantDecl for \p KnownValue (which refers to
4614041d10caff48859c0de6d001559a73185f5e0601Serge Pavlov/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4615041d10caff48859c0de6d001559a73185f5e0601Serge Pavlov/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4616041d10caff48859c0de6d001559a73185f5e0601Serge Pavlov/// this mapping from within the instantiation of <tt>X<int></tt>.
46177c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas GregorNamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4618e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor                          const MultiLevelTemplateArgumentList &TemplateArgs) {
4619815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor  DeclContext *ParentDC = D->getDeclContext();
4620a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // FIXME: Parmeters of pointer to functions (y below) that are themselves
4621a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // parameters (p below) can have their ParentDC set to the translation-unit
4622a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // - thus we can not consistently check if the ParentDC of such a parameter
4623a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // is Dependent or/and a FunctionOrMethod.
4624a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // For e.g. this code, during Template argument deduction tries to
4625a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // find an instantiated decl for (T y) when the ParentDC for y is
4626a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // the translation unit.
4627a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4628651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  //   float baz(float(*)()) { return 0.0; }
4629a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  //   Foo(baz);
4630a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4631a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // it gets here, always has a FunctionOrMethod as its ParentDC??
4632a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  // For now:
4633a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  //  - as long as we have a ParmVarDecl whose parent is non-dependent and
4634a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  //    whose type is not instantiation dependent, do nothing to the decl
4635a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  //  - otherwise find its instantiated decl.
4636a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali  if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4637a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali      !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4638a3d311e468bce37defb97ed75105f8d36942b651Faisal Vali    return D;
463980f2b2e693422f84ec3735f16a08614a527b0bc5Rafael Espindola  if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
46406d3e627dacdb2f749195635ab587fd067ef813e1Douglas Gregor      isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
46417bdc15252ca2415f149ad812f0e5184d758e6105Douglas Gregor      (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
46427bdc15252ca2415f149ad812f0e5184d758e6105Douglas Gregor      (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
46432bba76b0ec4c2f2134eebb1a2bbfe102f36c2f6eDouglas Gregor    // D is a local of some kind. Look into the map of local
46442bba76b0ec4c2f2134eebb1a2bbfe102f36c2f6eDouglas Gregor    // declarations to their instantiations.
4645176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines    if (CurrentInstantiationScope) {
4646176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4647176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        if (Decl *FD = Found->dyn_cast<Decl *>())
4648176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines          return cast<NamedDecl>(FD);
4649176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines
4650176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        int PackIdx = ArgumentPackSubstitutionIndex;
4651176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        assert(PackIdx != -1 &&
4652176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines               "found declaration pack but not pack expanding");
4653176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4654176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines        return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4655176edba5311f6eff0cad2631449885ddf4fbc9eaStephen Hines      }
465657ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner    }
465757ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner
4658dc49d523db70a1c9005b7c09de80b22ccb1ed6a4Serge Pavlov    // If we're performing a partial substitution during template argument
4659dc49d523db70a1c9005b7c09de80b22ccb1ed6a4Serge Pavlov    // deduction, we may not have values for template parameters yet. They
4660dc49d523db70a1c9005b7c09de80b22ccb1ed6a4Serge Pavlov    // just map to themselves.
4661dc49d523db70a1c9005b7c09de80b22ccb1ed6a4Serge Pavlov    if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4662dc49d523db70a1c9005b7c09de80b22ccb1ed6a4Serge Pavlov        isa<TemplateTemplateParmDecl>(D))
4663dc49d523db70a1c9005b7c09de80b22ccb1ed6a4Serge Pavlov      return D;
4664dc49d523db70a1c9005b7c09de80b22ccb1ed6a4Serge Pavlov
466529a46e63490176608efe13f13b293a6ce9862059Serge Pavlov    if (D->isInvalidDecl())
46666bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines      return nullptr;
466729a46e63490176608efe13f13b293a6ce9862059Serge Pavlov
4668b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // Normally this function only searches for already instantiated declaration
4669b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // however we have to make an exclusion for local types used before
4670b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // definition as in the code:
4671b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    //
4672b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    //   template<typename T> void f1() {
4673b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    //     void g1(struct x1);
4674b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    //     struct x1 {};
4675b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    //   }
4676b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    //
4677b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // In this case instantiation of the type of 'g1' requires definition of
4678b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // 'x1', which is defined later. Error recovery may produce an enum used
4679b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // before definition. In these cases we need to instantiate relevant
4680b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    // declarations here.
4681b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    bool NeedInstantiate = false;
4682b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4683b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      NeedInstantiate = RD->isLocalClass();
4684b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    else
4685b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      NeedInstantiate = isa<EnumDecl>(D);
4686b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    if (NeedInstantiate) {
4687b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4688b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4689b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar      return cast<TypeDecl>(Inst);
4690b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar    }
4691b6d6993e6e6d3daf4d9876794254d20a134e37c2Pirama Arumuga Nainar
469257ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner    // If we didn't find the decl, then we must have a label decl that hasn't
469357ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner    // been found yet.  Lazily instantiate it and return it now.
469457ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner    assert(isa<LabelDecl>(D));
4695a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
469657ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner    Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
469757ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner    assert(Inst && "Failed to instantiate label??");
4698a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
469957ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner    CurrentInstantiationScope->InstantiatedLocal(D, Inst);
470057ad37823e198f977cac605dbfbaefb4daf325e9Chris Lattner    return cast<LabelDecl>(Inst);
47012bba76b0ec4c2f2134eebb1a2bbfe102f36c2f6eDouglas Gregor  }
4702815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
4703ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // For variable template specializations, update those that are still
4704ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  // type-dependent.
4705ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  if (VarTemplateSpecializationDecl *VarSpec =
4706ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo          dyn_cast<VarTemplateSpecializationDecl>(D)) {
4707ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    bool InstantiationDependent = false;
4708ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    const TemplateArgumentListInfo &VarTemplateArgs =
4709ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo        VarSpec->getTemplateArgsInfo();
4710ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    if (TemplateSpecializationType::anyDependentTemplateArguments(
4711ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo            VarTemplateArgs, InstantiationDependent))
4712ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo      D = cast<NamedDecl>(
4713ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo          SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4714ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    return D;
4715ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  }
4716ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
4717e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4718e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor    if (!Record->isDependentContext())
4719e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor      return D;
4720a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
47212c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor    // Determine whether this record is the "templated" declaration describing
47222c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor    // a class template or class template partial specialization.
4723e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor    ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
47242c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor    if (ClassTemplate)
47252c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      ClassTemplate = ClassTemplate->getCanonicalDecl();
47262c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor    else if (ClassTemplatePartialSpecializationDecl *PartialSpec
47272c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor               = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
47282c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4729ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
47302c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor    // Walk the current context to find either the record or an instantiation of
47312c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor    // it.
47322c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor    DeclContext *DC = CurContext;
47332c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor    while (!DC->isFileContext()) {
47342c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      // If we're performing substitution while we're inside the template
47352c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      // definition, we'll find our own context. We're done.
47362c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      if (DC->Equals(Record))
47372c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        return Record;
4738ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
47392c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
47402c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        // Check whether we're in the process of instantiating a class template
47412c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        // specialization of the template we're mapping.
47422c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        if (ClassTemplateSpecializationDecl *InstSpec
47432c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor                      = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
47442c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor          ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
47452c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor          if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
47462c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor            return InstRecord;
47472c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        }
4748ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
47492c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        // Check whether we're in the process of instantiating a member class.
47502c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        if (isInstantiationOf(Record, InstRecord))
47512c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor          return InstRecord;
4752e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor      }
4753ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
47542c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      // Move to the outer template scope.
47552c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
47562c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
47572c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor          DC = FD->getLexicalDeclContext();
47582c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor          continue;
47592c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor        }
476052a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall      }
4761ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
47622c1227c4da661bdc0b1976740c3ff203ed7609b2Douglas Gregor      DC = DC->getParent();
476352a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall    }
47648b013bdbf6474ed25d4017635cac851e51163c25Douglas Gregor
4765e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor    // Fall through to deal with other dependent record types (e.g.,
4766e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor    // anonymous unions in class templates).
4767e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor  }
476852a575a5ce7b27b6612357cdba5aa4ec1574ad5eJohn McCall
4769e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor  if (!ParentDC->isDependentContext())
4770e95b40961302c2130968ddfc3ba162e138f2118eDouglas Gregor    return D;
4771a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
47727c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor  ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
47731eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  if (!ParentDC)
47746bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    return nullptr;
47751eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4776815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor  if (ParentDC != D->getDeclContext()) {
4777815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    // We performed some kind of instantiation in the parent context,
4778815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    // so now we need to look into the instantiated parent context to
4779815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    // find the instantiation of the declaration D.
47807c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor
47813cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall    // If our context used to be dependent, we may need to instantiate
47823cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall    // it before performing lookup into that context.
4783eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor    bool IsBeingInstantiated = false;
47843cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall    if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
47857c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor      if (!Spec->isDependentContext()) {
47867c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor        QualType T = Context.getTypeDeclType(Spec);
47873cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall        const RecordType *Tag = T->getAs<RecordType>();
47883cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall        assert(Tag && "type of non-dependent record is not a RecordType");
4789eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        if (Tag->isBeingDefined())
4790eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor          IsBeingInstantiated = true;
47913cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall        if (!Tag->isBeingDefined() &&
47923cb0ebd5f76abcb776f7cb4062bd79e3268c0dc4John McCall            RequireCompleteType(Loc, T, diag::err_incomplete_type))
47936bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines          return nullptr;
4794a43064c7b721a51ab2c0d0ccdc4f84064aa7ceccDouglas Gregor
4795a43064c7b721a51ab2c0d0ccdc4f84064aa7ceccDouglas Gregor        ParentDC = Tag->getDecl();
47967c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor      }
47977c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor    }
47987c1e98f1cb37b40e619a0c8aee8b337f037b432bDouglas Gregor
47996bcf27bb9a4b5c3f79cb44c0e4654a6d7619ad89Stephen Hines    NamedDecl *Result = nullptr;
4800815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    if (D->getDeclName()) {
480117945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis      DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
48023bc93e3124ad5e7191c4a12dc981c8ee53578193David Blaikie      Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4803815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    } else {
4804815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      // Since we don't have a name for the entity we're looking for,
4805815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      // our only option is to walk through all of the declarations to
4806815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      // find that name. This will occur in a few cases:
4807815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      //
4808815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      //   - anonymous struct/union within a template
4809815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      //   - unnamed class/struct/union/enum within a template
4810815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      //
4811815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor      // FIXME: Find a better way to find these instantiations!
48121eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump      Result = findInstantiationOf(Context, D,
481317945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis                                   ParentDC->decls_begin(),
481417945a0f64fe03ff6ec0c2146005a87636e3ac12Argyrios Kyrtzidis                                   ParentDC->decls_end());
4815815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    }
48161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4817eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor    if (!Result) {
4818eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor      if (isa<UsingShadowDecl>(D)) {
4819eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // UsingShadowDecls can instantiate to nothing because of using hiding.
4820eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor      } else if (Diags.hasErrorOccurred()) {
4821eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // We've already complained about something, so most likely this
4822eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // declaration failed to instantiate. There's no point in complaining
4823eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // further, since this is normal in invalid code.
4824eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor      } else if (IsBeingInstantiated) {
4825a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi        // The class in which this member exists is currently being
4826eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // instantiated, and we haven't gotten around to instantiating this
4827eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // member yet. This can happen when the code uses forward declarations
4828eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // of member classes, and introduces ordering dependencies via
4829eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // template instantiation.
4830eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        Diag(Loc, diag::err_member_not_yet_instantiated)
4831eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor          << D->getDeclName()
4832eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor          << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4833eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        Diag(D->getLocation(), diag::note_non_instantiated_member_here);
48340724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith      } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
48350724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith        // This enumeration constant was found when the template was defined,
48360724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith        // but can't be found in the instantiation. This can happen if an
48370724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith        // unscoped enumeration member is explicitly specialized.
48380724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith        EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
48390724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith        EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
48400724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith                                                             TemplateArgs));
48410724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith        assert(Spec->getTemplateSpecializationKind() ==
48420724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith                 TSK_ExplicitSpecialization);
48430724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith        Diag(Loc, diag::err_enumerator_does_not_exist)
48440724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith          << D->getDeclName()
48450724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith          << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
48460724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith        Diag(Spec->getLocation(), diag::note_enum_specialized_here)
48470724b7c43007d978c46f890dcd2ab3c8d3c22920Richard Smith          << Context.getTypeDeclType(Spec);
4848eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor      } else {
4849eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        // We should have found something, but didn't.
4850eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor        llvm_unreachable("Unable to find instantiation of declaration!");
4851eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor      }
4852eff1dbec93999bfc5406eb861efd8add9de23633Douglas Gregor    }
4853a789ca9b967abe47b84df83bcf4afb150856a8d9NAKAMURA Takumi
4854815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor    D = Result;
4855815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor  }
4856815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor
4857815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor  return D;
4858815215daf8f642b53a28212313fca7b9f77e5b9dDouglas Gregor}
4859d7f37bf8b9a211455c5037df7b7e88e5a9510119Douglas Gregor
48601eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// \brief Performs template instantiation for all implicit template
4861d7f37bf8b9a211455c5037df7b7e88e5a9510119Douglas Gregor/// instantiations we have seen until this point.
48628155910a192dafa423d6b932b7d127d48e4641e8Nick Lewyckyvoid Sema::PerformPendingInstantiations(bool LocalOnly) {
486360406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor  while (!PendingLocalImplicitInstantiations.empty() ||
486462c78d54bee499dd87f768f48b21c9b5ec15e516Chandler Carruth         (!LocalOnly && !PendingInstantiations.empty())) {
486560406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor    PendingImplicitInstantiation Inst;
486660406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor
486760406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor    if (PendingLocalImplicitInstantiations.empty()) {
486862c78d54bee499dd87f768f48b21c9b5ec15e516Chandler Carruth      Inst = PendingInstantiations.front();
486962c78d54bee499dd87f768f48b21c9b5ec15e516Chandler Carruth      PendingInstantiations.pop_front();
487060406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor    } else {
487160406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor      Inst = PendingLocalImplicitInstantiations.front();
487260406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor      PendingLocalImplicitInstantiations.pop_front();
487360406bede202b66ebdd98cac0c38d20f9698aecaDouglas Gregor    }
48741eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
48757caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    // Instantiate function definitions
48767caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
487758e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth      bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
487858e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth                                TSK_ExplicitInstantiationDefinition;
487958e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth      InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
48804967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                    DefinitionRequired, true);
48817caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor      continue;
48827caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    }
48831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
4884ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // Instantiate variable definitions
48857caa6825f42a0f7e97d6fc06233133c42b218e46Douglas Gregor    VarDecl *Var = cast<VarDecl>(Inst.first);
4886ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
4887ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    assert((Var->isStaticDataMember() ||
4888ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo            isa<VarTemplateSpecializationDecl>(Var)) &&
4889ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo           "Not a static data member, nor a variable template"
4890ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo           " specialization?");
4891c17fb7bd9a06b027c792c7dfad7e9fa430277affAnders Carlsson
4892291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    // Don't try to instantiate declarations if the most recent redeclaration
4893291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    // is invalid.
4894ef96ee0be5f100789f451641542a69cd719144d2Douglas Gregor    if (Var->getMostRecentDecl()->isInvalidDecl())
4895291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth      continue;
4896291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth
4897291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    // Check if the most recent declaration has changed the specialization kind
4898291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    // and removed the need for implicit instantiation.
4899ef96ee0be5f100789f451641542a69cd719144d2Douglas Gregor    switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4900291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    case TSK_Undeclared:
4901b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie      llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4902291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    case TSK_ExplicitInstantiationDeclaration:
4903291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    case TSK_ExplicitSpecialization:
490458e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth      continue;  // No longer need to instantiate this type.
490558e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth    case TSK_ExplicitInstantiationDefinition:
490658e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth      // We only need an instantiation if the pending instantiation *is* the
490758e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth      // explicit instantiation.
4908ef96ee0be5f100789f451641542a69cd719144d2Douglas Gregor      if (Var != Var->getMostRecentDecl()) continue;
4909291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    case TSK_ImplicitInstantiation:
4910291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth      break;
4911291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth    }
4912291b441a095b289c30d9f311fe37a2cf5ed6fd45Chandler Carruth
4913ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4914ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo                                        "instantiating variable definition");
491558e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth    bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
491658e390ef491c8fb11ae17445054ee09527b492d3Chandler Carruth                              TSK_ExplicitInstantiationDefinition;
4917ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo
4918ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // Instantiate static data member definitions or variable template
4919ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    // specializations.
4920ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo    InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
49214967a710c84587c654b56c828382219c3937dacbPirama Arumuga Nainar                                  DefinitionRequired, true);
4922d7f37bf8b9a211455c5037df7b7e88e5a9510119Douglas Gregor  }
4923d7f37bf8b9a211455c5037df7b7e88e5a9510119Douglas Gregor}
49240c01d18094100db92d38daa923c95661512db203John McCall
49250c01d18094100db92d38daa923c95661512db203John McCallvoid Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
49260c01d18094100db92d38daa923c95661512db203John McCall                       const MultiLevelTemplateArgumentList &TemplateArgs) {
4927651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  for (auto DD : Pattern->ddiags()) {
49280c01d18094100db92d38daa923c95661512db203John McCall    switch (DD->getKind()) {
49290c01d18094100db92d38daa923c95661512db203John McCall    case DependentDiagnostic::Access:
49300c01d18094100db92d38daa923c95661512db203John McCall      HandleDependentAccessCheck(*DD, TemplateArgs);
49310c01d18094100db92d38daa923c95661512db203John McCall      break;
49320c01d18094100db92d38daa923c95661512db203John McCall    }
49330c01d18094100db92d38daa923c95661512db203John McCall  }
49340c01d18094100db92d38daa923c95661512db203John McCall}
4935