Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//===----------------------------------------------------------------------===/
7
//
8
//  This file implements C++ template instantiation for declarations.
9
//
10
//===----------------------------------------------------------------------===/
11
12
#include "TreeTransform.h"
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTMutationListener.h"
16
#include "clang/AST/DeclTemplate.h"
17
#include "clang/AST/DeclVisitor.h"
18
#include "clang/AST/DependentDiagnostic.h"
19
#include "clang/AST/Expr.h"
20
#include "clang/AST/ExprCXX.h"
21
#include "clang/AST/PrettyDeclStackTrace.h"
22
#include "clang/AST/TypeLoc.h"
23
#include "clang/Basic/SourceManager.h"
24
#include "clang/Basic/TargetInfo.h"
25
#include "clang/Sema/Initialization.h"
26
#include "clang/Sema/Lookup.h"
27
#include "clang/Sema/ScopeInfo.h"
28
#include "clang/Sema/SemaInternal.h"
29
#include "clang/Sema/Template.h"
30
#include "clang/Sema/TemplateInstCallback.h"
31
#include "llvm/Support/TimeProfiler.h"
32
33
using namespace clang;
34
35
2.97k
static bool isDeclWithinFunction(const Decl *D) {
36
2.97k
  const DeclContext *DC = D->getDeclContext();
37
2.97k
  if (DC->isFunctionOrMethod())
38
70
    return true;
39
40
2.90k
  if (DC->isRecord())
41
2.90k
    return cast<CXXRecordDecl>(DC)->isLocalClass();
42
43
0
  return false;
44
2.90k
}
45
46
template<typename DeclT>
47
static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
48
1.31M
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
49
1.31M
  if (!OldDecl->getQualifierLoc())
50
1.29M
    return false;
51
52
20.6k
  assert((NewDecl->getFriendObjectKind() ||
53
20.6k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
54
20.6k
         "non-friend with qualified name defined in dependent context");
55
0
  Sema::ContextRAII SavedContext(
56
20.6k
      SemaRef,
57
20.6k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
58
20.6k
                                    ? 
NewDecl->getLexicalDeclContext()10
59
20.6k
                                    : 
OldDecl->getLexicalDeclContext()20.6k
));
60
61
20.6k
  NestedNameSpecifierLoc NewQualifierLoc
62
20.6k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63
20.6k
                                            TemplateArgs);
64
65
20.6k
  if (!NewQualifierLoc)
66
2
    return true;
67
68
20.6k
  NewDecl->setQualifierInfo(NewQualifierLoc);
69
20.6k
  return false;
70
20.6k
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::DeclaratorDecl>(clang::Sema&, clang::DeclaratorDecl const*, clang::DeclaratorDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
48
349k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
49
349k
  if (!OldDecl->getQualifierLoc())
50
338k
    return false;
51
52
10.7k
  assert((NewDecl->getFriendObjectKind() ||
53
10.7k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
54
10.7k
         "non-friend with qualified name defined in dependent context");
55
0
  Sema::ContextRAII SavedContext(
56
10.7k
      SemaRef,
57
10.7k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
58
10.7k
                                    ? 
NewDecl->getLexicalDeclContext()0
59
10.7k
                                    : OldDecl->getLexicalDeclContext()));
60
61
10.7k
  NestedNameSpecifierLoc NewQualifierLoc
62
10.7k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63
10.7k
                                            TemplateArgs);
64
65
10.7k
  if (!NewQualifierLoc)
66
1
    return true;
67
68
10.7k
  NewDecl->setQualifierInfo(NewQualifierLoc);
69
10.7k
  return false;
70
10.7k
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::TagDecl>(clang::Sema&, clang::TagDecl const*, clang::TagDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
48
784k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
49
784k
  if (!OldDecl->getQualifierLoc())
50
784k
    return false;
51
52
9
  assert((NewDecl->getFriendObjectKind() ||
53
9
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
54
9
         "non-friend with qualified name defined in dependent context");
55
0
  Sema::ContextRAII SavedContext(
56
9
      SemaRef,
57
9
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
58
9
                                    ? 
NewDecl->getLexicalDeclContext()0
59
9
                                    : OldDecl->getLexicalDeclContext()));
60
61
9
  NestedNameSpecifierLoc NewQualifierLoc
62
9
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63
9
                                            TemplateArgs);
64
65
9
  if (!NewQualifierLoc)
66
0
    return true;
67
68
9
  NewDecl->setQualifierInfo(NewQualifierLoc);
69
9
  return false;
70
9
}
SemaTemplateInstantiateDecl.cpp:bool SubstQualifier<clang::FunctionDecl>(clang::Sema&, clang::FunctionDecl const*, clang::FunctionDecl*, clang::MultiLevelTemplateArgumentList const&)
Line
Count
Source
48
185k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
49
185k
  if (!OldDecl->getQualifierLoc())
50
175k
    return false;
51
52
9.87k
  assert((NewDecl->getFriendObjectKind() ||
53
9.87k
          !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
54
9.87k
         "non-friend with qualified name defined in dependent context");
55
0
  Sema::ContextRAII SavedContext(
56
9.87k
      SemaRef,
57
9.87k
      const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
58
9.87k
                                    ? 
NewDecl->getLexicalDeclContext()10
59
9.87k
                                    : 
OldDecl->getLexicalDeclContext()9.86k
));
60
61
9.87k
  NestedNameSpecifierLoc NewQualifierLoc
62
9.87k
      = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63
9.87k
                                            TemplateArgs);
64
65
9.87k
  if (!NewQualifierLoc)
66
1
    return true;
67
68
9.87k
  NewDecl->setQualifierInfo(NewQualifierLoc);
69
9.87k
  return false;
70
9.87k
}
71
72
bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
73
349k
                                              DeclaratorDecl *NewDecl) {
74
349k
  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
75
349k
}
76
77
bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
78
784k
                                              TagDecl *NewDecl) {
79
784k
  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
80
784k
}
81
82
// Include attribute instantiation code.
83
#include "clang/Sema/AttrTemplateInstantiate.inc"
84
85
static void instantiateDependentAlignedAttr(
86
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
87
183
    const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
88
183
  if (Aligned->isAlignmentExpr()) {
89
    // The alignment expression is a constant expression.
90
183
    EnterExpressionEvaluationContext Unevaluated(
91
183
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
92
183
    ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
93
183
    if (!Result.isInvalid())
94
183
      S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
95
183
  } else {
96
0
    TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
97
0
                                         TemplateArgs, Aligned->getLocation(),
98
0
                                         DeclarationName());
99
0
    if (Result)
100
0
      S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
101
0
  }
102
183
}
103
104
static void instantiateDependentAlignedAttr(
105
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
106
181
    const AlignedAttr *Aligned, Decl *New) {
107
181
  if (!Aligned->isPackExpansion()) {
108
166
    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
109
166
    return;
110
166
  }
111
112
15
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
113
15
  if (Aligned->isAlignmentExpr())
114
15
    S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
115
15
                                      Unexpanded);
116
0
  else
117
0
    S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
118
0
                                      Unexpanded);
119
15
  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
120
121
  // Determine whether we can expand this attribute pack yet.
122
0
  bool Expand = true, RetainExpansion = false;
123
15
  Optional<unsigned> NumExpansions;
124
  // FIXME: Use the actual location of the ellipsis.
125
15
  SourceLocation EllipsisLoc = Aligned->getLocation();
126
15
  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
127
15
                                        Unexpanded, TemplateArgs, Expand,
128
15
                                        RetainExpansion, NumExpansions))
129
1
    return;
130
131
14
  if (!Expand) {
132
0
    Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
133
0
    instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
134
14
  } else {
135
31
    for (unsigned I = 0; I != *NumExpansions; 
++I17
) {
136
17
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
137
17
      instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
138
17
    }
139
14
  }
140
14
}
141
142
static void instantiateDependentAssumeAlignedAttr(
143
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
144
10
    const AssumeAlignedAttr *Aligned, Decl *New) {
145
  // The alignment expression is a constant expression.
146
10
  EnterExpressionEvaluationContext Unevaluated(
147
10
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
148
149
10
  Expr *E, *OE = nullptr;
150
10
  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
151
10
  if (Result.isInvalid())
152
2
    return;
153
8
  E = Result.getAs<Expr>();
154
155
8
  if (Aligned->getOffset()) {
156
3
    Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
157
3
    if (Result.isInvalid())
158
0
      return;
159
3
    OE = Result.getAs<Expr>();
160
3
  }
161
162
8
  S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
163
8
}
164
165
static void instantiateDependentAlignValueAttr(
166
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
167
3
    const AlignValueAttr *Aligned, Decl *New) {
168
  // The alignment expression is a constant expression.
169
3
  EnterExpressionEvaluationContext Unevaluated(
170
3
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
171
3
  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
172
3
  if (!Result.isInvalid())
173
3
    S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
174
3
}
175
176
static void instantiateDependentAllocAlignAttr(
177
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
178
8
    const AllocAlignAttr *Align, Decl *New) {
179
8
  Expr *Param = IntegerLiteral::Create(
180
8
      S.getASTContext(),
181
8
      llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
182
8
      S.getASTContext().UnsignedLongLongTy, Align->getLocation());
183
8
  S.AddAllocAlignAttr(New, *Align, Param);
184
8
}
185
186
static void instantiateDependentAnnotationAttr(
187
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188
25
    const AnnotateAttr *Attr, Decl *New) {
189
25
  EnterExpressionEvaluationContext Unevaluated(
190
25
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
191
25
  SmallVector<Expr *, 4> Args;
192
25
  Args.reserve(Attr->args_size());
193
36
  for (auto *E : Attr->args()) {
194
36
    ExprResult Result = S.SubstExpr(E, TemplateArgs);
195
36
    if (!Result.isUsable())
196
2
      return;
197
34
    Args.push_back(Result.get());
198
34
  }
199
23
  S.AddAnnotationAttr(New, *Attr, Attr->getAnnotation(), Args);
200
23
}
201
202
static Expr *instantiateDependentFunctionAttrCondition(
203
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
204
1.48k
    const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
205
1.48k
  Expr *Cond = nullptr;
206
1.48k
  {
207
1.48k
    Sema::ContextRAII SwitchContext(S, New);
208
1.48k
    EnterExpressionEvaluationContext Unevaluated(
209
1.48k
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
210
1.48k
    ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
211
1.48k
    if (Result.isInvalid())
212
0
      return nullptr;
213
1.48k
    Cond = Result.getAs<Expr>();
214
1.48k
  }
215
1.48k
  if (!Cond->isTypeDependent()) {
216
1.48k
    ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
217
1.48k
    if (Converted.isInvalid())
218
2
      return nullptr;
219
1.47k
    Cond = Converted.get();
220
1.47k
  }
221
222
1.47k
  SmallVector<PartialDiagnosticAt, 8> Diags;
223
1.47k
  if (OldCond->isValueDependent() && 
!Cond->isValueDependent()100
&&
224
1.47k
      
!Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)100
) {
225
0
    S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
226
0
    for (const auto &P : Diags)
227
0
      S.Diag(P.first, P.second);
228
0
    return nullptr;
229
0
  }
230
1.47k
  return Cond;
231
1.47k
}
232
233
static void instantiateDependentEnableIfAttr(
234
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
235
35
    const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
236
35
  Expr *Cond = instantiateDependentFunctionAttrCondition(
237
35
      S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
238
239
35
  if (Cond)
240
33
    New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
241
33
                                                      Cond, EIA->getMessage()));
242
35
}
243
244
static void instantiateDependentDiagnoseIfAttr(
245
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
246
1.44k
    const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
247
1.44k
  Expr *Cond = instantiateDependentFunctionAttrCondition(
248
1.44k
      S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
249
250
1.44k
  if (Cond)
251
1.44k
    New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
252
1.44k
        S.getASTContext(), *DIA, Cond, DIA->getMessage(),
253
1.44k
        DIA->getDiagnosticType(), DIA->getArgDependent(), New));
254
1.44k
}
255
256
// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
257
// template A as the base and arguments from TemplateArgs.
258
static void instantiateDependentCUDALaunchBoundsAttr(
259
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
260
6
    const CUDALaunchBoundsAttr &Attr, Decl *New) {
261
  // The alignment expression is a constant expression.
262
6
  EnterExpressionEvaluationContext Unevaluated(
263
6
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
264
265
6
  ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
266
6
  if (Result.isInvalid())
267
0
    return;
268
6
  Expr *MaxThreads = Result.getAs<Expr>();
269
270
6
  Expr *MinBlocks = nullptr;
271
6
  if (Attr.getMinBlocks()) {
272
4
    Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
273
4
    if (Result.isInvalid())
274
0
      return;
275
4
    MinBlocks = Result.getAs<Expr>();
276
4
  }
277
278
6
  S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
279
6
}
280
281
static void
282
instantiateDependentModeAttr(Sema &S,
283
                             const MultiLevelTemplateArgumentList &TemplateArgs,
284
84
                             const ModeAttr &Attr, Decl *New) {
285
84
  S.AddModeAttr(New, Attr, Attr.getMode(),
286
84
                /*InInstantiation=*/true);
287
84
}
288
289
/// Instantiation of 'declare simd' attribute and its arguments.
290
static void instantiateOMPDeclareSimdDeclAttr(
291
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
292
58
    const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
293
  // Allow 'this' in clauses with varlists.
294
58
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
295
0
    New = FTD->getTemplatedDecl();
296
58
  auto *FD = cast<FunctionDecl>(New);
297
58
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
298
58
  SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
299
58
  SmallVector<unsigned, 4> LinModifiers;
300
301
110
  auto SubstExpr = [&](Expr *E) -> ExprResult {
302
110
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
303
102
      if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
304
80
        Sema::ContextRAII SavedContext(S, FD);
305
80
        LocalInstantiationScope Local(S);
306
80
        if (FD->getNumParams() > PVD->getFunctionScopeIndex())
307
80
          Local.InstantiatedLocal(
308
80
              PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
309
80
        return S.SubstExpr(E, TemplateArgs);
310
80
      }
311
30
    Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
312
30
                                     FD->isCXXInstanceMember());
313
30
    return S.SubstExpr(E, TemplateArgs);
314
110
  };
315
316
  // Substitute a single OpenMP clause, which is a potentially-evaluated
317
  // full-expression.
318
110
  auto Subst = [&](Expr *E) -> ExprResult {
319
110
    EnterExpressionEvaluationContext Evaluated(
320
110
        S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
321
110
    ExprResult Res = SubstExpr(E);
322
110
    if (Res.isInvalid())
323
0
      return Res;
324
110
    return S.ActOnFinishFullExpr(Res.get(), false);
325
110
  };
326
327
58
  ExprResult Simdlen;
328
58
  if (auto *E = Attr.getSimdlen())
329
18
    Simdlen = Subst(E);
330
331
58
  if (Attr.uniforms_size() > 0) {
332
18
    for(auto *E : Attr.uniforms()) {
333
18
      ExprResult Inst = Subst(E);
334
18
      if (Inst.isInvalid())
335
0
        continue;
336
18
      Uniforms.push_back(Inst.get());
337
18
    }
338
10
  }
339
340
58
  auto AI = Attr.alignments_begin();
341
58
  for (auto *E : Attr.aligneds()) {
342
58
    ExprResult Inst = Subst(E);
343
58
    if (Inst.isInvalid())
344
0
      continue;
345
58
    Aligneds.push_back(Inst.get());
346
58
    Inst = ExprEmpty();
347
58
    if (*AI)
348
16
      Inst = S.SubstExpr(*AI, TemplateArgs);
349
58
    Alignments.push_back(Inst.get());
350
58
    ++AI;
351
58
  }
352
353
58
  auto SI = Attr.steps_begin();
354
58
  for (auto *E : Attr.linears()) {
355
16
    ExprResult Inst = Subst(E);
356
16
    if (Inst.isInvalid())
357
0
      continue;
358
16
    Linears.push_back(Inst.get());
359
16
    Inst = ExprEmpty();
360
16
    if (*SI)
361
16
      Inst = S.SubstExpr(*SI, TemplateArgs);
362
16
    Steps.push_back(Inst.get());
363
16
    ++SI;
364
16
  }
365
58
  LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
366
58
  (void)S.ActOnOpenMPDeclareSimdDirective(
367
58
      S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
368
58
      Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
369
58
      Attr.getRange());
370
58
}
371
372
/// Instantiation of 'declare variant' attribute and its arguments.
373
static void instantiateOMPDeclareVariantAttr(
374
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
375
85
    const OMPDeclareVariantAttr &Attr, Decl *New) {
376
  // Allow 'this' in clauses with varlists.
377
85
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
378
0
    New = FTD->getTemplatedDecl();
379
85
  auto *FD = cast<FunctionDecl>(New);
380
85
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
381
382
117
  auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
383
117
    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
384
81
      if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
385
10
        Sema::ContextRAII SavedContext(S, FD);
386
10
        LocalInstantiationScope Local(S);
387
10
        if (FD->getNumParams() > PVD->getFunctionScopeIndex())
388
10
          Local.InstantiatedLocal(
389
10
              PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
390
10
        return S.SubstExpr(E, TemplateArgs);
391
10
      }
392
107
    Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
393
107
                                     FD->isCXXInstanceMember());
394
107
    return S.SubstExpr(E, TemplateArgs);
395
117
  };
396
397
  // Substitute a single OpenMP clause, which is a potentially-evaluated
398
  // full-expression.
399
117
  auto &&Subst = [&SubstExpr, &S](Expr *E) {
400
117
    EnterExpressionEvaluationContext Evaluated(
401
117
        S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
402
117
    ExprResult Res = SubstExpr(E);
403
117
    if (Res.isInvalid())
404
0
      return Res;
405
117
    return S.ActOnFinishFullExpr(Res.get(), false);
406
117
  };
407
408
85
  ExprResult VariantFuncRef;
409
85
  if (Expr *E = Attr.getVariantFuncRef()) {
410
    // Do not mark function as is used to prevent its emission if this is the
411
    // only place where it is used.
412
85
    EnterExpressionEvaluationContext Unevaluated(
413
85
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
414
85
    VariantFuncRef = Subst(E);
415
85
  }
416
417
  // Copy the template version of the OMPTraitInfo and run substitute on all
418
  // score and condition expressiosn.
419
85
  OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
420
85
  TI = *Attr.getTraitInfos();
421
422
  // Try to substitute template parameters in score and condition expressions.
423
138
  auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
424
138
    if (E) {
425
22
      EnterExpressionEvaluationContext Unevaluated(
426
22
          S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
427
22
      ExprResult ER = Subst(E);
428
22
      if (ER.isUsable())
429
22
        E = ER.get();
430
0
      else
431
0
        return true;
432
22
    }
433
138
    return false;
434
138
  };
435
85
  if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
436
0
    return;
437
438
85
  Expr *E = VariantFuncRef.get();
439
440
  // Check function/variant ref for `omp declare variant` but not for `omp
441
  // begin declare variant` (which use implicit attributes).
442
85
  Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
443
85
      S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New), E, TI,
444
85
                                          Attr.appendArgs_size(),
445
85
                                          Attr.getRange());
446
447
85
  if (!DeclVarData)
448
8
    return;
449
450
77
  E = DeclVarData.getValue().second;
451
77
  FD = DeclVarData.getValue().first;
452
453
77
  if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
454
77
    if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
455
77
      if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
456
40
        if (!VariantFTD->isThisDeclarationADefinition())
457
0
          return;
458
40
        Sema::TentativeAnalysisScope Trap(S);
459
40
        const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
460
40
            S.Context, TemplateArgs.getInnermost());
461
462
40
        auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
463
40
                                                         New->getLocation());
464
40
        if (!SubstFD)
465
2
          return;
466
38
        QualType NewType = S.Context.mergeFunctionTypes(
467
38
            SubstFD->getType(), FD->getType(),
468
38
            /* OfBlockPointer */ false,
469
38
            /* Unqualified */ false, /* AllowCXX */ true);
470
38
        if (NewType.isNull())
471
4
          return;
472
34
        S.InstantiateFunctionDefinition(
473
34
            New->getLocation(), SubstFD, /* Recursive */ true,
474
34
            /* DefinitionRequired */ false, /* AtEndOfTU */ false);
475
34
        SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
476
34
        E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
477
34
                                SourceLocation(), SubstFD,
478
34
                                /* RefersToEnclosingVariableOrCapture */ false,
479
34
                                /* NameLoc */ SubstFD->getLocation(),
480
34
                                SubstFD->getType(), ExprValueKind::VK_PRValue);
481
34
      }
482
77
    }
483
77
  }
484
485
71
  SmallVector<Expr *, 8> NothingExprs;
486
71
  SmallVector<Expr *, 8> NeedDevicePtrExprs;
487
71
  SmallVector<OMPDeclareVariantAttr::InteropType, 8> AppendArgs;
488
489
71
  for (Expr *E : Attr.adjustArgsNothing()) {
490
5
    ExprResult ER = Subst(E);
491
5
    if (ER.isInvalid())
492
0
      continue;
493
5
    NothingExprs.push_back(ER.get());
494
5
  }
495
71
  for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
496
5
    ExprResult ER = Subst(E);
497
5
    if (ER.isInvalid())
498
0
      continue;
499
5
    NeedDevicePtrExprs.push_back(ER.get());
500
5
  }
501
71
  for (auto A : Attr.appendArgs())
502
0
    AppendArgs.push_back(A);
503
504
71
  S.ActOnOpenMPDeclareVariantDirective(
505
71
      FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
506
71
      SourceLocation(), Attr.getRange());
507
71
}
508
509
static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
510
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
511
2
    const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
512
  // Both min and max expression are constant expressions.
513
2
  EnterExpressionEvaluationContext Unevaluated(
514
2
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
515
516
2
  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
517
2
  if (Result.isInvalid())
518
0
    return;
519
2
  Expr *MinExpr = Result.getAs<Expr>();
520
521
2
  Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
522
2
  if (Result.isInvalid())
523
0
    return;
524
2
  Expr *MaxExpr = Result.getAs<Expr>();
525
526
2
  S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
527
2
}
528
529
static ExplicitSpecifier
530
instantiateExplicitSpecifier(Sema &S,
531
                             const MultiLevelTemplateArgumentList &TemplateArgs,
532
1.00M
                             ExplicitSpecifier ES, FunctionDecl *New) {
533
1.00M
  if (!ES.getExpr())
534
1.00M
    return ES;
535
387
  Expr *OldCond = ES.getExpr();
536
387
  Expr *Cond = nullptr;
537
387
  {
538
387
    EnterExpressionEvaluationContext Unevaluated(
539
387
        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
540
387
    ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
541
387
    if (SubstResult.isInvalid()) {
542
142
      return ExplicitSpecifier::Invalid();
543
142
    }
544
245
    Cond = SubstResult.get();
545
245
  }
546
0
  ExplicitSpecifier Result(Cond, ES.getKind());
547
245
  if (!Cond->isTypeDependent())
548
213
    S.tryResolveExplicitSpecifier(Result);
549
245
  return Result;
550
387
}
551
552
static void instantiateDependentAMDGPUWavesPerEUAttr(
553
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
554
3
    const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
555
  // Both min and max expression are constant expressions.
556
3
  EnterExpressionEvaluationContext Unevaluated(
557
3
      S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
558
559
3
  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
560
3
  if (Result.isInvalid())
561
0
    return;
562
3
  Expr *MinExpr = Result.getAs<Expr>();
563
564
3
  Expr *MaxExpr = nullptr;
565
3
  if (auto Max = Attr.getMax()) {
566
2
    Result = S.SubstExpr(Max, TemplateArgs);
567
2
    if (Result.isInvalid())
568
0
      return;
569
2
    MaxExpr = Result.getAs<Expr>();
570
2
  }
571
572
3
  S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
573
3
}
574
575
// This doesn't take any template parameters, but we have a custom action that
576
// needs to happen when the kernel itself is instantiated. We need to run the
577
// ItaniumMangler to mark the names required to name this kernel.
578
static void instantiateDependentSYCLKernelAttr(
579
    Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
580
64
    const SYCLKernelAttr &Attr, Decl *New) {
581
64
  New->addAttr(Attr.clone(S.getASTContext()));
582
64
}
583
584
/// Determine whether the attribute A might be relevant to the declaration D.
585
/// If not, we can skip instantiating it. The attribute may or may not have
586
/// been instantiated yet.
587
3.70M
static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
588
  // 'preferred_name' is only relevant to the matching specialization of the
589
  // template.
590
3.70M
  if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
591
31.4k
    QualType T = PNA->getTypedefType();
592
31.4k
    const auto *RD = cast<CXXRecordDecl>(D);
593
31.4k
    if (!T->isDependentType() && 
!RD->isDependentContext()31.4k
&&
594
31.4k
        
!declaresSameEntity(T->getAsCXXRecordDecl(), RD)31.4k
)
595
19.7k
      return false;
596
11.6k
    for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
597
7.28k
      if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
598
7.28k
                                PNA->getTypedefType()))
599
7.27k
        return false;
600
4.42k
    return true;
601
11.6k
  }
602
603
3.66M
  return true;
604
3.70M
}
605
606
void Sema::InstantiateAttrsForDecl(
607
    const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
608
    Decl *New, LateInstantiatedAttrVec *LateAttrs,
609
1.31M
    LocalInstantiationScope *OuterMostScope) {
610
1.31M
  if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
611
    // FIXME: This function is called multiple times for the same template
612
    // specialization. We should only instantiate attributes that were added
613
    // since the previous instantiation.
614
1.31M
    for (const auto *TmplAttr : Tmpl->attrs()) {
615
563k
      if (!isRelevantAttr(*this, New, TmplAttr))
616
20.4k
        continue;
617
618
      // FIXME: If any of the special case versions from InstantiateAttrs become
619
      // applicable to template declaration, we'll need to add them here.
620
543k
      CXXThisScopeRAII ThisScope(
621
543k
          *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
622
543k
          Qualifiers(), ND->isCXXInstanceMember());
623
624
543k
      Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
625
543k
          TmplAttr, Context, *this, TemplateArgs);
626
543k
      if (NewAttr && 
isRelevantAttr(*this, New, NewAttr)1.66k
)
627
1.66k
        New->addAttr(NewAttr);
628
543k
    }
629
1.31M
  }
630
1.31M
}
631
632
static Sema::RetainOwnershipKind
633
89
attrToRetainOwnershipKind(const Attr *A) {
634
89
  switch (A->getKind()) {
635
0
  case clang::attr::CFConsumed:
636
0
    return Sema::RetainOwnershipKind::CF;
637
0
  case clang::attr::OSConsumed:
638
0
    return Sema::RetainOwnershipKind::OS;
639
89
  case clang::attr::NSConsumed:
640
89
    return Sema::RetainOwnershipKind::NS;
641
0
  default:
642
0
    llvm_unreachable("Wrong argument supplied");
643
89
  }
644
89
}
645
646
void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
647
                            const Decl *Tmpl, Decl *New,
648
                            LateInstantiatedAttrVec *LateAttrs,
649
4.52M
                            LocalInstantiationScope *OuterMostScope) {
650
4.52M
  for (const auto *TmplAttr : Tmpl->attrs()) {
651
2.15M
    if (!isRelevantAttr(*this, New, TmplAttr))
652
6.59k
      continue;
653
654
    // FIXME: This should be generalized to more than just the AlignedAttr.
655
2.15M
    const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
656
2.15M
    if (Aligned && 
Aligned->isAlignmentDependent()1.30k
) {
657
181
      instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
658
181
      continue;
659
181
    }
660
661
2.15M
    if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
662
10
      instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
663
10
      continue;
664
10
    }
665
666
2.15M
    if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
667
3
      instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
668
3
      continue;
669
3
    }
670
671
2.15M
    if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
672
8
      instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
673
8
      continue;
674
8
    }
675
676
2.15M
    if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
677
25
      instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
678
25
      continue;
679
25
    }
680
681
2.15M
    if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
682
35
      instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
683
35
                                       cast<FunctionDecl>(New));
684
35
      continue;
685
35
    }
686
687
2.15M
    if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
688
1.44k
      instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
689
1.44k
                                         cast<FunctionDecl>(New));
690
1.44k
      continue;
691
1.44k
    }
692
693
2.15M
    if (const auto *CUDALaunchBounds =
694
2.15M
            dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
695
6
      instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
696
6
                                               *CUDALaunchBounds, New);
697
6
      continue;
698
6
    }
699
700
2.15M
    if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
701
84
      instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
702
84
      continue;
703
84
    }
704
705
2.15M
    if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
706
58
      instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
707
58
      continue;
708
58
    }
709
710
2.15M
    if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
711
85
      instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
712
85
      continue;
713
85
    }
714
715
2.15M
    if (const auto *AMDGPUFlatWorkGroupSize =
716
2.15M
            dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
717
2
      instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
718
2
          *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
719
2
    }
720
721
2.15M
    if (const auto *AMDGPUFlatWorkGroupSize =
722
2.15M
            dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
723
3
      instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
724
3
                                               *AMDGPUFlatWorkGroupSize, New);
725
3
    }
726
727
    // Existing DLL attribute on the instantiation takes precedence.
728
2.15M
    if (TmplAttr->getKind() == attr::DLLExport ||
729
2.15M
        
TmplAttr->getKind() == attr::DLLImport2.15M
) {
730
1.35k
      if (New->hasAttr<DLLExportAttr>() || 
New->hasAttr<DLLImportAttr>()1.35k
) {
731
24
        continue;
732
24
      }
733
1.35k
    }
734
735
2.15M
    if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
736
6
      AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
737
6
      continue;
738
6
    }
739
740
2.15M
    if (isa<NSConsumedAttr>(TmplAttr) || 
isa<OSConsumedAttr>(TmplAttr)2.15M
||
741
2.15M
        
isa<CFConsumedAttr>(TmplAttr)2.15M
) {
742
89
      AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
743
89
                       /*template instantiation=*/true);
744
89
      continue;
745
89
    }
746
747
2.15M
    if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
748
1.20k
      if (!New->hasAttr<PointerAttr>())
749
1.20k
        New->addAttr(A->clone(Context));
750
1.20k
      continue;
751
1.20k
    }
752
753
2.14M
    if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
754
3.91k
      if (!New->hasAttr<OwnerAttr>())
755
3.88k
        New->addAttr(A->clone(Context));
756
3.91k
      continue;
757
3.91k
    }
758
759
2.14M
    if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
760
64
      instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
761
64
      continue;
762
64
    }
763
764
2.14M
    assert(!TmplAttr->isPackExpansion());
765
2.14M
    if (TmplAttr->isLateParsed() && 
LateAttrs130
) {
766
      // Late parsed attributes must be instantiated and attached after the
767
      // enclosing class has been instantiated.  See Sema::InstantiateClass.
768
82
      LocalInstantiationScope *Saved = nullptr;
769
82
      if (CurrentInstantiationScope)
770
82
        Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
771
82
      LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
772
2.14M
    } else {
773
      // Allow 'this' within late-parsed attributes.
774
2.14M
      auto *ND = cast<NamedDecl>(New);
775
2.14M
      auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
776
2.14M
      CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
777
2.14M
                                 ND->isCXXInstanceMember());
778
779
2.14M
      Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
780
2.14M
                                                         *this, TemplateArgs);
781
2.14M
      if (NewAttr && 
isRelevantAttr(*this, New, TmplAttr)976k
)
782
976k
        New->addAttr(NewAttr);
783
2.14M
    }
784
2.14M
  }
785
4.52M
}
786
787
/// In the MS ABI, we need to instantiate default arguments of dllexported
788
/// default constructors along with the constructor definition. This allows IR
789
/// gen to emit a constructor closure which calls the default constructor with
790
/// its default arguments.
791
223
void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
792
223
  assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
793
223
         Ctor->isDefaultConstructor());
794
0
  unsigned NumParams = Ctor->getNumParams();
795
223
  if (NumParams == 0)
796
184
    return;
797
39
  DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
798
39
  if (!Attr)
799
0
    return;
800
78
  
for (unsigned I = 0; 39
I != NumParams;
++I39
) {
801
39
    (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
802
39
                                   Ctor->getParamDecl(I));
803
39
    DiscardCleanupsInEvaluationContext();
804
39
  }
805
39
}
806
807
/// Get the previous declaration of a declaration for the purposes of template
808
/// instantiation. If this finds a previous declaration, then the previous
809
/// declaration of the instantiation of D should be an instantiation of the
810
/// result of this function.
811
template<typename DeclT>
812
1.47M
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
813
1.47M
  DeclT *Result = D->getPreviousDecl();
814
815
  // If the declaration is within a class, and the previous declaration was
816
  // merged from a different definition of that class, then we don't have a
817
  // previous declaration for the purpose of template instantiation.
818
1.47M
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())522
&&
819
1.47M
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()25
)
820
5
    return nullptr;
821
822
1.47M
  return Result;
823
1.47M
}
SemaTemplateInstantiateDecl.cpp:clang::TypedefNameDecl* getPreviousDeclForInstantiation<clang::TypedefNameDecl>(clang::TypedefNameDecl*)
Line
Count
Source
812
681k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
813
681k
  DeclT *Result = D->getPreviousDecl();
814
815
  // If the declaration is within a class, and the previous declaration was
816
  // merged from a different definition of that class, then we don't have a
817
  // previous declaration for the purpose of template instantiation.
818
681k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())471
&&
819
681k
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
820
0
    return nullptr;
821
822
681k
  return Result;
823
681k
}
SemaTemplateInstantiateDecl.cpp:clang::EnumDecl* getPreviousDeclForInstantiation<clang::EnumDecl>(clang::EnumDecl*)
Line
Count
Source
812
2.91k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
813
2.91k
  DeclT *Result = D->getPreviousDecl();
814
815
  // If the declaration is within a class, and the previous declaration was
816
  // merged from a different definition of that class, then we don't have a
817
  // previous declaration for the purpose of template instantiation.
818
2.91k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())14
&&
819
2.91k
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
820
0
    return nullptr;
821
822
2.91k
  return Result;
823
2.91k
}
SemaTemplateInstantiateDecl.cpp:clang::CXXRecordDecl* getPreviousDeclForInstantiation<clang::CXXRecordDecl>(clang::CXXRecordDecl*)
Line
Count
Source
812
788k
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
813
788k
  DeclT *Result = D->getPreviousDecl();
814
815
  // If the declaration is within a class, and the previous declaration was
816
  // merged from a different definition of that class, then we don't have a
817
  // previous declaration for the purpose of template instantiation.
818
788k
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())37
&&
819
788k
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()25
)
820
5
    return nullptr;
821
822
788k
  return Result;
823
788k
}
SemaTemplateInstantiateDecl.cpp:clang::VarDecl* getPreviousDeclForInstantiation<clang::VarDecl>(clang::VarDecl*)
Line
Count
Source
812
376
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
813
376
  DeclT *Result = D->getPreviousDecl();
814
815
  // If the declaration is within a class, and the previous declaration was
816
  // merged from a different definition of that class, then we don't have a
817
  // previous declaration for the purpose of template instantiation.
818
376
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
819
376
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
820
0
    return nullptr;
821
822
376
  return Result;
823
376
}
SemaTemplateInstantiateDecl.cpp:clang::FunctionTemplateDecl* getPreviousDeclForInstantiation<clang::FunctionTemplateDecl>(clang::FunctionTemplateDecl*)
Line
Count
Source
812
14
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
813
14
  DeclT *Result = D->getPreviousDecl();
814
815
  // If the declaration is within a class, and the previous declaration was
816
  // merged from a different definition of that class, then we don't have a
817
  // previous declaration for the purpose of template instantiation.
818
14
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
819
14
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
820
0
    return nullptr;
821
822
14
  return Result;
823
14
}
SemaTemplateInstantiateDecl.cpp:clang::UsingShadowDecl* getPreviousDeclForInstantiation<clang::UsingShadowDecl>(clang::UsingShadowDecl*)
Line
Count
Source
812
382
static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
813
382
  DeclT *Result = D->getPreviousDecl();
814
815
  // If the declaration is within a class, and the previous declaration was
816
  // merged from a different definition of that class, then we don't have a
817
  // previous declaration for the purpose of template instantiation.
818
382
  if (Result && 
isa<CXXRecordDecl>(D->getDeclContext())0
&&
819
382
      
D->getLexicalDeclContext() != Result->getLexicalDeclContext()0
)
820
0
    return nullptr;
821
822
382
  return Result;
823
382
}
824
825
Decl *
826
0
TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
827
0
  llvm_unreachable("Translation units cannot be instantiated");
828
0
}
829
830
Decl *
831
0
TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
832
0
  llvm_unreachable("pragma comment cannot be instantiated");
833
0
}
834
835
Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
836
0
    PragmaDetectMismatchDecl *D) {
837
0
  llvm_unreachable("pragma comment cannot be instantiated");
838
0
}
839
840
Decl *
841
0
TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
842
0
  llvm_unreachable("extern \"C\" context cannot be instantiated");
843
0
}
844
845
0
Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
846
0
  llvm_unreachable("GUID declaration cannot be instantiated");
847
0
}
848
849
Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
850
0
    TemplateParamObjectDecl *D) {
851
0
  llvm_unreachable("template parameter objects cannot be instantiated");
852
0
}
853
854
Decl *
855
81
TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
856
81
  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
857
81
                                      D->getIdentifier());
858
81
  Owner->addDecl(Inst);
859
81
  return Inst;
860
81
}
861
862
Decl *
863
0
TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
864
0
  llvm_unreachable("Namespaces cannot be instantiated");
865
0
}
866
867
Decl *
868
2
TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
869
2
  NamespaceAliasDecl *Inst
870
2
    = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
871
2
                                 D->getNamespaceLoc(),
872
2
                                 D->getAliasLoc(),
873
2
                                 D->getIdentifier(),
874
2
                                 D->getQualifierLoc(),
875
2
                                 D->getTargetNameLoc(),
876
2
                                 D->getNamespace());
877
2
  Owner->addDecl(Inst);
878
2
  return Inst;
879
2
}
880
881
Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
882
654k
                                                           bool IsTypeAlias) {
883
654k
  bool Invalid = false;
884
654k
  TypeSourceInfo *DI = D->getTypeSourceInfo();
885
654k
  if (DI->getType()->isInstantiationDependentType() ||
886
654k
      
DI->getType()->isVariablyModifiedType()36.7k
) {
887
617k
    DI = SemaRef.SubstType(DI, TemplateArgs,
888
617k
                           D->getLocation(), D->getDeclName());
889
617k
    if (!DI) {
890
215
      Invalid = true;
891
215
      DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
892
215
    }
893
617k
  } else {
894
36.7k
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
895
36.7k
  }
896
897
  // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
898
  // libstdc++ relies upon this bug in its implementation of common_type.  If we
899
  // happen to be processing that implementation, fake up the g++ ?:
900
  // semantics. See LWG issue 2141 for more information on the bug.  The bugs
901
  // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
902
654k
  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
903
654k
  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
904
654k
  if (DT && 
RD2.80k
&&
isa<ConditionalOperator>(DT->getUnderlyingExpr())2.13k
&&
905
654k
      
DT->isReferenceType()1
&&
906
654k
      
RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace()1
&&
907
654k
      
RD->getIdentifier()1
&&
RD->getIdentifier()->isStr("common_type")1
&&
908
654k
      
D->getIdentifier()1
&&
D->getIdentifier()->isStr("type")1
&&
909
654k
      
SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc())1
)
910
    // Fold it to the (non-reference) type which g++ would have produced.
911
1
    DI = SemaRef.Context.getTrivialTypeSourceInfo(
912
1
      DI->getType().getNonReferenceType());
913
914
  // Create the new typedef
915
654k
  TypedefNameDecl *Typedef;
916
654k
  if (IsTypeAlias)
917
87.4k
    Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
918
87.4k
                                    D->getLocation(), D->getIdentifier(), DI);
919
567k
  else
920
567k
    Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
921
567k
                                  D->getLocation(), D->getIdentifier(), DI);
922
654k
  if (Invalid)
923
215
    Typedef->setInvalidDecl();
924
925
  // If the old typedef was the name for linkage purposes of an anonymous
926
  // tag decl, re-establish that relationship for the new typedef.
927
654k
  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
928
8.86k
    TagDecl *oldTag = oldTagType->getDecl();
929
8.86k
    if (oldTag->getTypedefNameForAnonDecl() == D && 
!Invalid20
) {
930
20
      TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
931
20
      assert(!newTag->hasNameForLinkage());
932
0
      newTag->setTypedefNameForAnonDecl(Typedef);
933
20
    }
934
8.86k
  }
935
936
654k
  if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
937
471
    NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
938
471
                                                       TemplateArgs);
939
471
    if (!InstPrev)
940
0
      return nullptr;
941
942
471
    TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
943
944
    // If the typedef types are not identical, reject them.
945
471
    SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
946
947
471
    Typedef->setPreviousDecl(InstPrevTypedef);
948
471
  }
949
950
654k
  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
951
952
654k
  if (D->getUnderlyingType()->getAs<DependentNameType>())
953
239k
    SemaRef.inferGslPointerAttribute(Typedef);
954
955
654k
  Typedef->setAccess(D->getAccess());
956
957
654k
  return Typedef;
958
654k
}
959
960
567k
Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
961
567k
  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
962
567k
  if (Typedef)
963
567k
    Owner->addDecl(Typedef);
964
567k
  return Typedef;
965
567k
}
966
967
60.4k
Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
968
60.4k
  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
969
60.4k
  if (Typedef)
970
60.4k
    Owner->addDecl(Typedef);
971
60.4k
  return Typedef;
972
60.4k
}
973
974
Decl *
975
26.9k
TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
976
  // Create a local instantiation scope for this type alias template, which
977
  // will contain the instantiations of the template parameters.
978
26.9k
  LocalInstantiationScope Scope(SemaRef);
979
980
26.9k
  TemplateParameterList *TempParams = D->getTemplateParameters();
981
26.9k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
982
26.9k
  if (!InstParams)
983
0
    return nullptr;
984
985
26.9k
  TypeAliasDecl *Pattern = D->getTemplatedDecl();
986
987
26.9k
  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
988
26.9k
  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
989
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
990
0
    if (!Found.empty()) {
991
0
      PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
992
0
    }
993
0
  }
994
995
26.9k
  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
996
26.9k
    InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
997
26.9k
  if (!AliasInst)
998
0
    return nullptr;
999
1000
26.9k
  TypeAliasTemplateDecl *Inst
1001
26.9k
    = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1002
26.9k
                                    D->getDeclName(), InstParams, AliasInst);
1003
26.9k
  AliasInst->setDescribedAliasTemplate(Inst);
1004
26.9k
  if (PrevAliasTemplate)
1005
0
    Inst->setPreviousDecl(PrevAliasTemplate);
1006
1007
26.9k
  Inst->setAccess(D->getAccess());
1008
1009
26.9k
  if (!PrevAliasTemplate)
1010
26.9k
    Inst->setInstantiatedFromMemberTemplate(D);
1011
1012
26.9k
  Owner->addDecl(Inst);
1013
1014
26.9k
  return Inst;
1015
26.9k
}
1016
1017
45
Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1018
45
  auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1019
45
                                    D->getIdentifier());
1020
45
  NewBD->setReferenced(D->isReferenced());
1021
45
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1022
45
  return NewBD;
1023
45
}
1024
1025
27
Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1026
  // Transform the bindings first.
1027
27
  SmallVector<BindingDecl*, 16> NewBindings;
1028
27
  for (auto *OldBD : D->bindings())
1029
45
    NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1030
27
  ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1031
1032
27
  auto *NewDD = cast_or_null<DecompositionDecl>(
1033
27
      VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1034
1035
27
  if (!NewDD || NewDD->isInvalidDecl())
1036
8
    for (auto *NewBD : NewBindings)
1037
15
      NewBD->setInvalidDecl();
1038
1039
27
  return NewDD;
1040
27
}
1041
1042
346k
Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1043
346k
  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1044
346k
}
1045
1046
Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1047
                                             bool InstantiatingVarTemplate,
1048
346k
                                             ArrayRef<BindingDecl*> *Bindings) {
1049
1050
  // Do substitution on the type of the declaration
1051
346k
  TypeSourceInfo *DI = SemaRef.SubstType(
1052
346k
      D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1053
346k
      D->getDeclName(), /*AllowDeducedTST*/true);
1054
346k
  if (!DI)
1055
83
    return nullptr;
1056
1057
346k
  if (DI->getType()->isFunctionType()) {
1058
6
    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1059
6
      << D->isStaticDataMember() << DI->getType();
1060
6
    return nullptr;
1061
6
  }
1062
1063
346k
  DeclContext *DC = Owner;
1064
346k
  if (D->isLocalExternDecl())
1065
88
    SemaRef.adjustContextForLocalExternDecl(DC);
1066
1067
  // Build the instantiated declaration.
1068
346k
  VarDecl *Var;
1069
346k
  if (Bindings)
1070
27
    Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1071
27
                                    D->getLocation(), DI->getType(), DI,
1072
27
                                    D->getStorageClass(), *Bindings);
1073
346k
  else
1074
346k
    Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1075
346k
                          D->getLocation(), D->getIdentifier(), DI->getType(),
1076
346k
                          DI, D->getStorageClass());
1077
1078
  // In ARC, infer 'retaining' for variables of retainable type.
1079
346k
  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1080
346k
      
SemaRef.inferObjCARCLifetime(Var)57
)
1081
0
    Var->setInvalidDecl();
1082
1083
346k
  if (SemaRef.getLangOpts().OpenCL)
1084
33
    SemaRef.deduceOpenCLAddressSpace(Var);
1085
1086
  // Substitute the nested name specifier, if any.
1087
346k
  if (SubstQualifier(D, Var))
1088
1
    return nullptr;
1089
1090
346k
  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1091
346k
                                     StartingScope, InstantiatingVarTemplate);
1092
346k
  if (D->isNRVOVariable() && 
!Var->isInvalidDecl()3.86k
) {
1093
3.84k
    QualType RT;
1094
3.84k
    if (auto *F = dyn_cast<FunctionDecl>(DC))
1095
3.84k
      RT = F->getReturnType();
1096
4
    else if (isa<BlockDecl>(DC))
1097
4
      RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1098
4
               ->getReturnType();
1099
0
    else
1100
0
      llvm_unreachable("Unknown context type");
1101
1102
    // This is the last chance we have of checking copy elision eligibility
1103
    // for functions in dependent contexts. The sema actions for building
1104
    // the return statement during template instantiation will have no effect
1105
    // regarding copy elision, since NRVO propagation runs on the scope exit
1106
    // actions, and these are not run on instantiation.
1107
    // This might run through some VarDecls which were returned from non-taken
1108
    // 'if constexpr' branches, and these will end up being constructed on the
1109
    // return slot even if they will never be returned, as a sort of accidental
1110
    // 'optimization'. Notably, functions with 'auto' return types won't have it
1111
    // deduced by this point. Coupled with the limitation described
1112
    // previously, this makes it very hard to support copy elision for these.
1113
3.84k
    Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1114
3.84k
    bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1115
3.84k
    Var->setNRVOVariable(NRVO);
1116
3.84k
  }
1117
1118
346k
  Var->setImplicit(D->isImplicit());
1119
1120
346k
  if (Var->isStaticLocal())
1121
733
    SemaRef.CheckStaticLocalForDllExport(Var);
1122
1123
346k
  return Var;
1124
346k
}
1125
1126
166k
Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1127
166k
  AccessSpecDecl* AD
1128
166k
    = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1129
166k
                             D->getAccessSpecifierLoc(), D->getColonLoc());
1130
166k
  Owner->addHiddenDecl(AD);
1131
166k
  return AD;
1132
166k
}
1133
1134
64.9k
Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1135
64.9k
  bool Invalid = false;
1136
64.9k
  TypeSourceInfo *DI = D->getTypeSourceInfo();
1137
64.9k
  if (DI->getType()->isInstantiationDependentType() ||
1138
64.9k
      
DI->getType()->isVariablyModifiedType()11.3k
) {
1139
53.5k
    DI = SemaRef.SubstType(DI, TemplateArgs,
1140
53.5k
                           D->getLocation(), D->getDeclName());
1141
53.5k
    if (!DI) {
1142
63
      DI = D->getTypeSourceInfo();
1143
63
      Invalid = true;
1144
53.5k
    } else if (DI->getType()->isFunctionType()) {
1145
      // C++ [temp.arg.type]p3:
1146
      //   If a declaration acquires a function type through a type
1147
      //   dependent on a template-parameter and this causes a
1148
      //   declaration that does not use the syntactic form of a
1149
      //   function declarator to have function type, the program is
1150
      //   ill-formed.
1151
15
      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1152
15
        << DI->getType();
1153
15
      Invalid = true;
1154
15
    }
1155
53.5k
  } else {
1156
11.3k
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1157
11.3k
  }
1158
1159
64.9k
  Expr *BitWidth = D->getBitWidth();
1160
64.9k
  if (Invalid)
1161
78
    BitWidth = nullptr;
1162
64.8k
  else if (BitWidth) {
1163
    // The bit-width expression is a constant expression.
1164
111
    EnterExpressionEvaluationContext Unevaluated(
1165
111
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1166
1167
111
    ExprResult InstantiatedBitWidth
1168
111
      = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1169
111
    if (InstantiatedBitWidth.isInvalid()) {
1170
0
      Invalid = true;
1171
0
      BitWidth = nullptr;
1172
0
    } else
1173
111
      BitWidth = InstantiatedBitWidth.getAs<Expr>();
1174
111
  }
1175
1176
64.9k
  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1177
64.9k
                                            DI->getType(), DI,
1178
64.9k
                                            cast<RecordDecl>(Owner),
1179
64.9k
                                            D->getLocation(),
1180
64.9k
                                            D->isMutable(),
1181
64.9k
                                            BitWidth,
1182
64.9k
                                            D->getInClassInitStyle(),
1183
64.9k
                                            D->getInnerLocStart(),
1184
64.9k
                                            D->getAccess(),
1185
64.9k
                                            nullptr);
1186
64.9k
  if (!Field) {
1187
0
    cast<Decl>(Owner)->setInvalidDecl();
1188
0
    return nullptr;
1189
0
  }
1190
1191
64.9k
  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1192
1193
64.9k
  if (Field->hasAttrs())
1194
34
    SemaRef.CheckAlignasUnderalignment(Field);
1195
1196
64.9k
  if (Invalid)
1197
78
    Field->setInvalidDecl();
1198
1199
64.9k
  if (!Field->getDeclName()) {
1200
    // Keep track of where this decl came from.
1201
1.51k
    SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1202
1.51k
  }
1203
64.9k
  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1204
64.9k
    if (Parent->isAnonymousStructOrUnion() &&
1205
64.9k
        
Parent->getRedeclContext()->isFunctionOrMethod()3.71k
)
1206
0
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1207
64.9k
  }
1208
1209
64.9k
  Field->setImplicit(D->isImplicit());
1210
64.9k
  Field->setAccess(D->getAccess());
1211
64.9k
  Owner->addDecl(Field);
1212
1213
64.9k
  return Field;
1214
64.9k
}
1215
1216
29
Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1217
29
  bool Invalid = false;
1218
29
  TypeSourceInfo *DI = D->getTypeSourceInfo();
1219
1220
29
  if (DI->getType()->isVariablyModifiedType()) {
1221
0
    SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1222
0
      << D;
1223
0
    Invalid = true;
1224
29
  } else if (DI->getType()->isInstantiationDependentType())  {
1225
26
    DI = SemaRef.SubstType(DI, TemplateArgs,
1226
26
                           D->getLocation(), D->getDeclName());
1227
26
    if (!DI) {
1228
0
      DI = D->getTypeSourceInfo();
1229
0
      Invalid = true;
1230
26
    } else if (DI->getType()->isFunctionType()) {
1231
      // C++ [temp.arg.type]p3:
1232
      //   If a declaration acquires a function type through a type
1233
      //   dependent on a template-parameter and this causes a
1234
      //   declaration that does not use the syntactic form of a
1235
      //   function declarator to have function type, the program is
1236
      //   ill-formed.
1237
0
      SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1238
0
      << DI->getType();
1239
0
      Invalid = true;
1240
0
    }
1241
26
  } else {
1242
3
    SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1243
3
  }
1244
1245
29
  MSPropertyDecl *Property = MSPropertyDecl::Create(
1246
29
      SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1247
29
      DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1248
1249
29
  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1250
29
                           StartingScope);
1251
1252
29
  if (Invalid)
1253
0
    Property->setInvalidDecl();
1254
1255
29
  Property->setAccess(D->getAccess());
1256
29
  Owner->addDecl(Property);
1257
1258
29
  return Property;
1259
29
}
1260
1261
3.71k
Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1262
3.71k
  NamedDecl **NamedChain =
1263
3.71k
    new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1264
1265
3.71k
  int i = 0;
1266
7.44k
  for (auto *PI : D->chain()) {
1267
7.44k
    NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1268
7.44k
                                              TemplateArgs);
1269
7.44k
    if (!Next)
1270
0
      return nullptr;
1271
1272
7.44k
    NamedChain[i++] = Next;
1273
7.44k
  }
1274
1275
3.71k
  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1276
3.71k
  IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1277
3.71k
      SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1278
3.71k
      {NamedChain, D->getChainingSize()});
1279
1280
3.71k
  for (const auto *Attr : D->attrs())
1281
0
    IndirectField->addAttr(Attr->clone(SemaRef.Context));
1282
1283
3.71k
  IndirectField->setImplicit(D->isImplicit());
1284
3.71k
  IndirectField->setAccess(D->getAccess());
1285
3.71k
  Owner->addDecl(IndirectField);
1286
3.71k
  return IndirectField;
1287
3.71k
}
1288
1289
22.7k
Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1290
  // Handle friend type expressions by simply substituting template
1291
  // parameters into the pattern type and checking the result.
1292
22.7k
  if (TypeSourceInfo *Ty = D->getFriendType()) {
1293
1.77k
    TypeSourceInfo *InstTy;
1294
    // If this is an unsupported friend, don't bother substituting template
1295
    // arguments into it. The actual type referred to won't be used by any
1296
    // parts of Clang, and may not be valid for instantiating. Just use the
1297
    // same info for the instantiated friend.
1298
1.77k
    if (D->isUnsupportedFriend()) {
1299
3
      InstTy = Ty;
1300
1.76k
    } else {
1301
1.76k
      InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1302
1.76k
                                 D->getLocation(), DeclarationName());
1303
1.76k
    }
1304
1.77k
    if (!InstTy)
1305
1
      return nullptr;
1306
1307
1.77k
    FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1308
1.77k
                                                 D->getFriendLoc(), InstTy);
1309
1.77k
    if (!FD)
1310
0
      return nullptr;
1311
1312
1.77k
    FD->setAccess(AS_public);
1313
1.77k
    FD->setUnsupportedFriend(D->isUnsupportedFriend());
1314
1.77k
    Owner->addDecl(FD);
1315
1.77k
    return FD;
1316
1.77k
  }
1317
1318
20.9k
  NamedDecl *ND = D->getFriendDecl();
1319
20.9k
  assert(ND && "friend decl must be a decl or a type!");
1320
1321
  // All of the Visit implementations for the various potential friend
1322
  // declarations have to be carefully written to work for friend
1323
  // objects, with the most important detail being that the target
1324
  // decl should almost certainly not be placed in Owner.
1325
0
  Decl *NewND = Visit(ND);
1326
20.9k
  if (!NewND) 
return nullptr6
;
1327
1328
20.9k
  FriendDecl *FD =
1329
20.9k
    FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1330
20.9k
                       cast<NamedDecl>(NewND), D->getFriendLoc());
1331
20.9k
  FD->setAccess(AS_public);
1332
20.9k
  FD->setUnsupportedFriend(D->isUnsupportedFriend());
1333
20.9k
  Owner->addDecl(FD);
1334
20.9k
  return FD;
1335
20.9k
}
1336
1337
44.8k
Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1338
44.8k
  Expr *AssertExpr = D->getAssertExpr();
1339
1340
  // The expression in a static assertion is a constant expression.
1341
44.8k
  EnterExpressionEvaluationContext Unevaluated(
1342
44.8k
      SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1343
1344
44.8k
  ExprResult InstantiatedAssertExpr
1345
44.8k
    = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1346
44.8k
  if (InstantiatedAssertExpr.isInvalid())
1347
5
    return nullptr;
1348
1349
44.8k
  return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1350
44.8k
                                              InstantiatedAssertExpr.get(),
1351
44.8k
                                              D->getMessage(),
1352
44.8k
                                              D->getRParenLoc(),
1353
44.8k
                                              D->isFailed());
1354
44.8k
}
1355
1356
2.91k
Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1357
2.91k
  EnumDecl *PrevDecl = nullptr;
1358
2.91k
  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1359
14
    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1360
14
                                                   PatternPrev,
1361
14
                                                   TemplateArgs);
1362
14
    if (!Prev) 
return nullptr0
;
1363
14
    PrevDecl = cast<EnumDecl>(Prev);
1364
14
  }
1365
1366
2.91k
  EnumDecl *Enum =
1367
2.91k
      EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1368
2.91k
                       D->getLocation(), D->getIdentifier(), PrevDecl,
1369
2.91k
                       D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1370
2.91k
  if (D->isFixed()) {
1371
165
    if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1372
      // If we have type source information for the underlying type, it means it
1373
      // has been explicitly set by the user. Perform substitution on it before
1374
      // moving on.
1375
90
      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1376
90
      TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1377
90
                                                DeclarationName());
1378
90
      if (!NewTI || 
SemaRef.CheckEnumUnderlyingType(NewTI)88
)
1379
4
        Enum->setIntegerType(SemaRef.Context.IntTy);
1380
86
      else
1381
86
        Enum->setIntegerTypeSourceInfo(NewTI);
1382
90
    } else {
1383
75
      assert(!D->getIntegerType()->isDependentType()
1384
75
             && "Dependent type without type source info");
1385
0
      Enum->setIntegerType(D->getIntegerType());
1386
75
    }
1387
165
  }
1388
1389
0
  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1390
1391
2.91k
  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1392
2.91k
  Enum->setAccess(D->getAccess());
1393
  // Forward the mangling number from the template to the instantiated decl.
1394
2.91k
  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1395
  // See if the old tag was defined along with a declarator.
1396
  // If it did, mark the new tag as being associated with that declarator.
1397
2.91k
  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1398
3
    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1399
  // See if the old tag was defined along with a typedef.
1400
  // If it did, mark the new tag as being associated with that typedef.
1401
2.91k
  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1402
0
    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1403
2.91k
  if (SubstQualifier(D, Enum)) 
return nullptr0
;
1404
2.91k
  Owner->addDecl(Enum);
1405
1406
2.91k
  EnumDecl *Def = D->getDefinition();
1407
2.91k
  if (Def && 
Def != D2.84k
) {
1408
    // If this is an out-of-line definition of an enum member template, check
1409
    // that the underlying types match in the instantiation of both
1410
    // declarations.
1411
36
    if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1412
21
      SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1413
21
      QualType DefnUnderlying =
1414
21
        SemaRef.SubstType(TI->getType(), TemplateArgs,
1415
21
                          UnderlyingLoc, DeclarationName());
1416
21
      SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1417
21
                                     DefnUnderlying, /*IsFixed=*/true, Enum);
1418
21
    }
1419
36
  }
1420
1421
  // C++11 [temp.inst]p1: The implicit instantiation of a class template
1422
  // specialization causes the implicit instantiation of the declarations, but
1423
  // not the definitions of scoped member enumerations.
1424
  //
1425
  // DR1484 clarifies that enumeration definitions inside of a template
1426
  // declaration aren't considered entities that can be separately instantiated
1427
  // from the rest of the entity they are declared inside of.
1428
2.91k
  if (isDeclWithinFunction(D) ? 
D == Def68
:
Def2.84k
&&
!Enum->isScoped()2.78k
) {
1429
2.77k
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1430
2.77k
    InstantiateEnumDefinition(Enum, Def);
1431
2.77k
  }
1432
1433
2.91k
  return Enum;
1434
2.91k
}
1435
1436
void TemplateDeclInstantiator::InstantiateEnumDefinition(
1437
2.81k
    EnumDecl *Enum, EnumDecl *Pattern) {
1438
2.81k
  Enum->startDefinition();
1439
1440
  // Update the location to refer to the definition.
1441
2.81k
  Enum->setLocation(Pattern->getLocation());
1442
1443
2.81k
  SmallVector<Decl*, 4> Enumerators;
1444
1445
2.81k
  EnumConstantDecl *LastEnumConst = nullptr;
1446
2.90k
  for (auto *EC : Pattern->enumerators()) {
1447
    // The specified value for the enumerator.
1448
2.90k
    ExprResult Value((Expr *)nullptr);
1449
2.90k
    if (Expr *UninstValue = EC->getInitExpr()) {
1450
      // The enumerator's value expression is a constant expression.
1451
2.73k
      EnterExpressionEvaluationContext Unevaluated(
1452
2.73k
          SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1453
1454
2.73k
      Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1455
2.73k
    }
1456
1457
    // Drop the initial value and continue.
1458
2.90k
    bool isInvalid = false;
1459
2.90k
    if (Value.isInvalid()) {
1460
19
      Value = nullptr;
1461
19
      isInvalid = true;
1462
19
    }
1463
1464
2.90k
    EnumConstantDecl *EnumConst
1465
2.90k
      = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1466
2.90k
                                  EC->getLocation(), EC->getIdentifier(),
1467
2.90k
                                  Value.get());
1468
1469
2.90k
    if (isInvalid) {
1470
19
      if (EnumConst)
1471
19
        EnumConst->setInvalidDecl();
1472
19
      Enum->setInvalidDecl();
1473
19
    }
1474
1475
2.90k
    if (EnumConst) {
1476
2.90k
      SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1477
1478
2.90k
      EnumConst->setAccess(Enum->getAccess());
1479
2.90k
      Enum->addDecl(EnumConst);
1480
2.90k
      Enumerators.push_back(EnumConst);
1481
2.90k
      LastEnumConst = EnumConst;
1482
1483
2.90k
      if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1484
2.90k
          
!Enum->isScoped()61
) {
1485
        // If the enumeration is within a function or method, record the enum
1486
        // constant as a local.
1487
47
        SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1488
47
      }
1489
2.90k
    }
1490
2.90k
  }
1491
1492
2.81k
  SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1493
2.81k
                        Enumerators, nullptr, ParsedAttributesView());
1494
2.81k
}
1495
1496
0
Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1497
0
  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1498
0
}
1499
1500
Decl *
1501
0
TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1502
0
  llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1503
0
}
1504
1505
17.6k
Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1506
17.6k
  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1507
1508
  // Create a local instantiation scope for this class template, which
1509
  // will contain the instantiations of the template parameters.
1510
17.6k
  LocalInstantiationScope Scope(SemaRef);
1511
17.6k
  TemplateParameterList *TempParams = D->getTemplateParameters();
1512
17.6k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1513
17.6k
  if (!InstParams)
1514
5
    return nullptr;
1515
1516
17.6k
  CXXRecordDecl *Pattern = D->getTemplatedDecl();
1517
1518
  // Instantiate the qualifier.  We have to do this first in case
1519
  // we're a friend declaration, because if we are then we need to put
1520
  // the new declaration in the appropriate context.
1521
17.6k
  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1522
17.6k
  if (QualifierLoc) {
1523
8
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1524
8
                                                       TemplateArgs);
1525
8
    if (!QualifierLoc)
1526
0
      return nullptr;
1527
8
  }
1528
1529
17.6k
  CXXRecordDecl *PrevDecl = nullptr;
1530
17.6k
  ClassTemplateDecl *PrevClassTemplate = nullptr;
1531
1532
17.6k
  if (!isFriend && 
getPreviousDeclForInstantiation(Pattern)12.5k
) {
1533
4
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1534
4
    if (!Found.empty()) {
1535
4
      PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1536
4
      if (PrevClassTemplate)
1537
4
        PrevDecl = PrevClassTemplate->getTemplatedDecl();
1538
4
    }
1539
4
  }
1540
1541
  // If this isn't a friend, then it's a member template, in which
1542
  // case we just want to build the instantiation in the
1543
  // specialization.  If it is a friend, we want to build it in
1544
  // the appropriate context.
1545
17.6k
  DeclContext *DC = Owner;
1546
17.6k
  if (isFriend) {
1547
5.09k
    if (QualifierLoc) {
1548
8
      CXXScopeSpec SS;
1549
8
      SS.Adopt(QualifierLoc);
1550
8
      DC = SemaRef.computeDeclContext(SS);
1551
8
      if (!DC) 
return nullptr0
;
1552
5.08k
    } else {
1553
5.08k
      DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1554
5.08k
                                           Pattern->getDeclContext(),
1555
5.08k
                                           TemplateArgs);
1556
5.08k
    }
1557
1558
    // Look for a previous declaration of the template in the owning
1559
    // context.
1560
5.09k
    LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1561
5.09k
                   Sema::LookupOrdinaryName,
1562
5.09k
                   SemaRef.forRedeclarationInCurContext());
1563
5.09k
    SemaRef.LookupQualifiedName(R, DC);
1564
1565
5.09k
    if (R.isSingleResult()) {
1566
4.89k
      PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1567
4.89k
      if (PrevClassTemplate)
1568
4.89k
        PrevDecl = PrevClassTemplate->getTemplatedDecl();
1569
4.89k
    }
1570
1571
5.09k
    if (!PrevClassTemplate && 
QualifierLoc202
) {
1572
0
      SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1573
0
        << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1574
0
        << QualifierLoc.getSourceRange();
1575
0
      return nullptr;
1576
0
    }
1577
1578
5.09k
    if (PrevClassTemplate) {
1579
4.89k
      TemplateParameterList *PrevParams
1580
4.89k
        = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters();
1581
1582
      // Make sure the parameter lists match.
1583
4.89k
      if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, true,
1584
4.89k
                                                  Sema::TPL_TemplateMatch))
1585
3
        return nullptr;
1586
1587
      // Do some additional validation, then merge default arguments
1588
      // from the existing declarations.
1589
4.88k
      if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1590
4.88k
                                             Sema::TPC_ClassTemplate))
1591
0
        return nullptr;
1592
4.88k
    }
1593
5.09k
  }
1594
1595
17.6k
  CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1596
17.6k
      SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1597
17.6k
      Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1598
17.6k
      /*DelayTypeCreation=*/true);
1599
1600
17.6k
  if (QualifierLoc)
1601
6
    RecordInst->setQualifierInfo(QualifierLoc);
1602
1603
17.6k
  SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1604
17.6k
                                                              StartingScope);
1605
1606
17.6k
  ClassTemplateDecl *Inst
1607
17.6k
    = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1608
17.6k
                                D->getIdentifier(), InstParams, RecordInst);
1609
17.6k
  assert(!(isFriend && Owner->isDependentContext()));
1610
0
  Inst->setPreviousDecl(PrevClassTemplate);
1611
1612
17.6k
  RecordInst->setDescribedClassTemplate(Inst);
1613
1614
17.6k
  if (isFriend) {
1615
5.09k
    if (PrevClassTemplate)
1616
4.88k
      Inst->setAccess(PrevClassTemplate->getAccess());
1617
202
    else
1618
202
      Inst->setAccess(D->getAccess());
1619
1620
5.09k
    Inst->setObjectOfFriendDecl();
1621
    // TODO: do we want to track the instantiation progeny of this
1622
    // friend target decl?
1623
12.5k
  } else {
1624
12.5k
    Inst->setAccess(D->getAccess());
1625
12.5k
    if (!PrevClassTemplate)
1626
12.5k
      Inst->setInstantiatedFromMemberTemplate(D);
1627
12.5k
  }
1628
1629
  // Trigger creation of the type for the instantiation.
1630
17.6k
  SemaRef.Context.getInjectedClassNameType(RecordInst,
1631
17.6k
                                    Inst->getInjectedClassNameSpecialization());
1632
1633
  // Finish handling of friends.
1634
17.6k
  if (isFriend) {
1635
5.09k
    DC->makeDeclVisibleInContext(Inst);
1636
5.09k
    Inst->setLexicalDeclContext(Owner);
1637
5.09k
    RecordInst->setLexicalDeclContext(Owner);
1638
5.09k
    return Inst;
1639
5.09k
  }
1640
1641
12.5k
  if (D->isOutOfLine()) {
1642
0
    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1643
0
    RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1644
0
  }
1645
1646
12.5k
  Owner->addDecl(Inst);
1647
1648
12.5k
  if (!PrevClassTemplate) {
1649
    // Queue up any out-of-line partial specializations of this member
1650
    // class template; the client will force their instantiation once
1651
    // the enclosing class has been instantiated.
1652
12.5k
    SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1653
12.5k
    D->getPartialSpecializations(PartialSpecs);
1654
18.0k
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I5.55k
)
1655
5.55k
      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1656
9
        OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1657
12.5k
  }
1658
1659
12.5k
  return Inst;
1660
17.6k
}
1661
1662
Decl *
1663
TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1664
5.54k
                                   ClassTemplatePartialSpecializationDecl *D) {
1665
5.54k
  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1666
1667
  // Lookup the already-instantiated declaration in the instantiation
1668
  // of the class template and return that.
1669
5.54k
  DeclContext::lookup_result Found
1670
5.54k
    = Owner->lookup(ClassTemplate->getDeclName());
1671
5.54k
  if (Found.empty())
1672
0
    return nullptr;
1673
1674
5.54k
  ClassTemplateDecl *InstClassTemplate
1675
5.54k
    = dyn_cast<ClassTemplateDecl>(Found.front());
1676
5.54k
  if (!InstClassTemplate)
1677
0
    return nullptr;
1678
1679
5.54k
  if (ClassTemplatePartialSpecializationDecl *Result
1680
5.54k
        = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1681
0
    return Result;
1682
1683
5.54k
  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1684
5.54k
}
1685
1686
376
Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1687
376
  assert(D->getTemplatedDecl()->isStaticDataMember() &&
1688
376
         "Only static data member templates are allowed.");
1689
1690
  // Create a local instantiation scope for this variable template, which
1691
  // will contain the instantiations of the template parameters.
1692
0
  LocalInstantiationScope Scope(SemaRef);
1693
376
  TemplateParameterList *TempParams = D->getTemplateParameters();
1694
376
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1695
376
  if (!InstParams)
1696
0
    return nullptr;
1697
1698
376
  VarDecl *Pattern = D->getTemplatedDecl();
1699
376
  VarTemplateDecl *PrevVarTemplate = nullptr;
1700
1701
376
  if (getPreviousDeclForInstantiation(Pattern)) {
1702
0
    DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1703
0
    if (!Found.empty())
1704
0
      PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1705
0
  }
1706
1707
376
  VarDecl *VarInst =
1708
376
      cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1709
376
                                         /*InstantiatingVarTemplate=*/true));
1710
376
  if (!VarInst) 
return nullptr3
;
1711
1712
373
  DeclContext *DC = Owner;
1713
1714
373
  VarTemplateDecl *Inst = VarTemplateDecl::Create(
1715
373
      SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1716
373
      VarInst);
1717
373
  VarInst->setDescribedVarTemplate(Inst);
1718
373
  Inst->setPreviousDecl(PrevVarTemplate);
1719
1720
373
  Inst->setAccess(D->getAccess());
1721
373
  if (!PrevVarTemplate)
1722
373
    Inst->setInstantiatedFromMemberTemplate(D);
1723
1724
373
  if (D->isOutOfLine()) {
1725
0
    Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1726
0
    VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1727
0
  }
1728
1729
373
  Owner->addDecl(Inst);
1730
1731
373
  if (!PrevVarTemplate) {
1732
    // Queue up any out-of-line partial specializations of this member
1733
    // variable template; the client will force their instantiation once
1734
    // the enclosing class has been instantiated.
1735
373
    SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1736
373
    D->getPartialSpecializations(PartialSpecs);
1737
421
    for (unsigned I = 0, N = PartialSpecs.size(); I != N; 
++I48
)
1738
48
      if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1739
7
        OutOfLineVarPartialSpecs.push_back(
1740
7
            std::make_pair(Inst, PartialSpecs[I]));
1741
373
  }
1742
1743
373
  return Inst;
1744
376
}
1745
1746
Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1747
43
    VarTemplatePartialSpecializationDecl *D) {
1748
43
  assert(D->isStaticDataMember() &&
1749
43
         "Only static data member templates are allowed.");
1750
1751
0
  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1752
1753
  // Lookup the already-instantiated declaration and return that.
1754
43
  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1755
43
  assert(!Found.empty() && "Instantiation found nothing?");
1756
1757
0
  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1758
43
  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1759
1760
43
  if (VarTemplatePartialSpecializationDecl *Result =
1761
43
          InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1762
0
    return Result;
1763
1764
43
  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1765
43
}
1766
1767
Decl *
1768
200k
TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1769
  // Create a local instantiation scope for this function template, which
1770
  // will contain the instantiations of the template parameters and then get
1771
  // merged with the local instantiation scope for the function template
1772
  // itself.
1773
200k
  LocalInstantiationScope Scope(SemaRef);
1774
1775
200k
  TemplateParameterList *TempParams = D->getTemplateParameters();
1776
200k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1777
200k
  if (!InstParams)
1778
1
    return nullptr;
1779
1780
200k
  FunctionDecl *Instantiated = nullptr;
1781
200k
  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1782
193k
    Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1783
193k
                                                                 InstParams));
1784
6.95k
  else
1785
6.95k
    Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1786
6.95k
                                                          D->getTemplatedDecl(),
1787
6.95k
                                                                InstParams));
1788
1789
200k
  if (!Instantiated)
1790
4
    return nullptr;
1791
1792
  // Link the instantiated function template declaration to the function
1793
  // template from which it was instantiated.
1794
200k
  FunctionTemplateDecl *InstTemplate
1795
200k
    = Instantiated->getDescribedFunctionTemplate();
1796
200k
  InstTemplate->setAccess(D->getAccess());
1797
200k
  assert(InstTemplate &&
1798
200k
         "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1799
1800
0
  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1801
1802
  // Link the instantiation back to the pattern *unless* this is a
1803
  // non-definition friend declaration.
1804
200k
  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1805
200k
      
!(200k
isFriend200k
&&
!D->getTemplatedDecl()->isThisDeclarationADefinition()6.95k
))
1806
193k
    InstTemplate->setInstantiatedFromMemberTemplate(D);
1807
1808
  // Make declarations visible in the appropriate context.
1809
200k
  if (!isFriend) {
1810
193k
    Owner->addDecl(InstTemplate);
1811
193k
  } else 
if (6.96k
InstTemplate->getDeclContext()->isRecord()6.96k
&&
1812
6.96k
             
!getPreviousDeclForInstantiation(D)14
) {
1813
14
    SemaRef.CheckFriendAccess(InstTemplate);
1814
14
  }
1815
1816
200k
  return InstTemplate;
1817
200k
}
1818
1819
776k
Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1820
776k
  CXXRecordDecl *PrevDecl = nullptr;
1821
776k
  if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1822
28
    NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1823
28
                                                   PatternPrev,
1824
28
                                                   TemplateArgs);
1825
28
    if (!Prev) 
return nullptr0
;
1826
28
    PrevDecl = cast<CXXRecordDecl>(Prev);
1827
28
  }
1828
1829
776k
  CXXRecordDecl *Record = nullptr;
1830
776k
  bool IsInjectedClassName = D->isInjectedClassName();
1831
776k
  if (D->isLambda())
1832
8
    Record = CXXRecordDecl::CreateLambda(
1833
8
        SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1834
8
        D->isDependentLambda(), D->isGenericLambda(),
1835
8
        D->getLambdaCaptureDefault());
1836
776k
  else
1837
776k
    Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1838
776k
                                   D->getBeginLoc(), D->getLocation(),
1839
776k
                                   D->getIdentifier(), PrevDecl,
1840
776k
                                   /*DelayTypeCreation=*/IsInjectedClassName);
1841
  // Link the type of the injected-class-name to that of the outer class.
1842
776k
  if (IsInjectedClassName)
1843
757k
    (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1844
1845
  // Substitute the nested name specifier, if any.
1846
776k
  if (SubstQualifier(D, Record))
1847
0
    return nullptr;
1848
1849
776k
  SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1850
776k
                                                              StartingScope);
1851
1852
776k
  Record->setImplicit(D->isImplicit());
1853
  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1854
  // the tag decls introduced by friend class declarations don't have an access
1855
  // specifier. Remove once this area of the code gets sorted out.
1856
776k
  if (D->getAccess() != AS_none)
1857
774k
    Record->setAccess(D->getAccess());
1858
776k
  if (!IsInjectedClassName)
1859
18.6k
    Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1860
1861
  // If the original function was part of a friend declaration,
1862
  // inherit its namespace state.
1863
776k
  if (D->getFriendObjectKind())
1864
0
    Record->setObjectOfFriendDecl();
1865
1866
  // Make sure that anonymous structs and unions are recorded.
1867
776k
  if (D->isAnonymousStructOrUnion())
1868
1.51k
    Record->setAnonymousStructOrUnion(true);
1869
1870
776k
  if (D->isLocalClass())
1871
2.45k
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1872
1873
  // Forward the mangling number from the template to the instantiated decl.
1874
776k
  SemaRef.Context.setManglingNumber(Record,
1875
776k
                                    SemaRef.Context.getManglingNumber(D));
1876
1877
  // See if the old tag was defined along with a declarator.
1878
  // If it did, mark the new tag as being associated with that declarator.
1879
776k
  if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1880
3
    SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1881
1882
  // See if the old tag was defined along with a typedef.
1883
  // If it did, mark the new tag as being associated with that typedef.
1884
776k
  if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1885
0
    SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1886
1887
776k
  Owner->addDecl(Record);
1888
1889
  // DR1484 clarifies that the members of a local class are instantiated as part
1890
  // of the instantiation of their enclosing entity.
1891
776k
  if (D->isCompleteDefinition() && 
D->isLocalClass()18.2k
) {
1892
2.17k
    Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1893
1894
2.17k
    SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1895
2.17k
                             TSK_ImplicitInstantiation,
1896
2.17k
                             /*Complain=*/true);
1897
1898
    // For nested local classes, we will instantiate the members when we
1899
    // reach the end of the outermost (non-nested) local class.
1900
2.17k
    if (!D->isCXXClassMember())
1901
1.74k
      SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1902
1.74k
                                      TSK_ImplicitInstantiation);
1903
1904
    // This class may have local implicit instantiations that need to be
1905
    // performed within this scope.
1906
2.17k
    LocalInstantiations.perform();
1907
2.17k
  }
1908
1909
776k
  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1910
1911
776k
  if (IsInjectedClassName)
1912
757k
    assert(Record->isInjectedClassName() && "Broken injected-class-name");
1913
1914
0
  return Record;
1915
776k
}
1916
1917
/// Adjust the given function type for an instantiation of the
1918
/// given declaration, to cope with modifications to the function's type that
1919
/// aren't reflected in the type-source information.
1920
///
1921
/// \param D The declaration we're instantiating.
1922
/// \param TInfo The already-instantiated type.
1923
static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1924
                                                   FunctionDecl *D,
1925
1.11M
                                                   TypeSourceInfo *TInfo) {
1926
1.11M
  const FunctionProtoType *OrigFunc
1927
1.11M
    = D->getType()->castAs<FunctionProtoType>();
1928
1.11M
  const FunctionProtoType *NewFunc
1929
1.11M
    = TInfo->getType()->castAs<FunctionProtoType>();
1930
1.11M
  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1931
1.11M
    return TInfo->getType();
1932
1933
248
  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1934
248
  NewEPI.ExtInfo = OrigFunc->getExtInfo();
1935
248
  return Context.getFunctionType(NewFunc->getReturnType(),
1936
248
                                 NewFunc->getParamTypes(), NewEPI);
1937
1.11M
}
1938
1939
/// Normal class members are of more specific types and therefore
1940
/// don't make it here.  This function serves three purposes:
1941
///   1) instantiating function templates
1942
///   2) substituting friend declarations
1943
///   3) substituting deduction guide declarations for nested class templates
1944
Decl *TemplateDeclInstantiator::VisitFunctionDecl(
1945
    FunctionDecl *D, TemplateParameterList *TemplateParams,
1946
276k
    RewriteKind FunctionRewriteKind) {
1947
  // Check whether there is already a function template specialization for
1948
  // this declaration.
1949
276k
  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1950
276k
  if (FunctionTemplate && 
!TemplateParams267k
) {
1951
260k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1952
1953
260k
    void *InsertPos = nullptr;
1954
260k
    FunctionDecl *SpecFunc
1955
260k
      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1956
1957
    // If we already have a function template specialization, return it.
1958
260k
    if (SpecFunc)
1959
111k
      return SpecFunc;
1960
260k
  }
1961
1962
165k
  bool isFriend;
1963
165k
  if (FunctionTemplate)
1964
156k
    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1965
9.00k
  else
1966
9.00k
    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1967
1968
165k
  bool MergeWithParentScope = (TemplateParams != nullptr) ||
1969
165k
    
Owner->isFunctionOrMethod()158k
||
1970
165k
    
!(158k
isa<Decl>(Owner)158k
&&
1971
158k
      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1972
165k
  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1973
1974
165k
  ExplicitSpecifier InstantiatedExplicitSpecifier;
1975
165k
  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
1976
262
    InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
1977
262
        SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
1978
262
    if (InstantiatedExplicitSpecifier.isInvalid())
1979
10
      return nullptr;
1980
262
  }
1981
1982
165k
  SmallVector<ParmVarDecl *, 4> Params;
1983
165k
  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1984
165k
  if (!TInfo)
1985
23.6k
    return nullptr;
1986
141k
  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1987
1988
141k
  if (TemplateParams && 
TemplateParams->size()6.95k
) {
1989
6.95k
    auto *LastParam =
1990
6.95k
        dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
1991
6.95k
    if (LastParam && 
LastParam->isImplicit()3.59k
&&
1992
6.95k
        
LastParam->hasTypeConstraint()0
) {
1993
      // In abbreviated templates, the type-constraints of invented template
1994
      // type parameters are instantiated with the function type, invalidating
1995
      // the TemplateParameterList which relied on the template type parameter
1996
      // not having a type constraint. Recreate the TemplateParameterList with
1997
      // the updated parameter list.
1998
0
      TemplateParams = TemplateParameterList::Create(
1999
0
          SemaRef.Context, TemplateParams->getTemplateLoc(),
2000
0
          TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2001
0
          TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2002
0
    }
2003
6.95k
  }
2004
2005
141k
  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2006
141k
  if (QualifierLoc) {
2007
10
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2008
10
                                                       TemplateArgs);
2009
10
    if (!QualifierLoc)
2010
0
      return nullptr;
2011
10
  }
2012
2013
  // FIXME: Concepts: Do not substitute into constraint expressions
2014
141k
  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2015
141k
  if (TrailingRequiresClause) {
2016
52
    EnterExpressionEvaluationContext ConstantEvaluated(
2017
52
        SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
2018
52
    ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2019
52
                                           TemplateArgs);
2020
52
    if (SubstRC.isInvalid())
2021
0
      return nullptr;
2022
52
    TrailingRequiresClause = SubstRC.get();
2023
52
    if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2024
0
      return nullptr;
2025
52
  }
2026
2027
  // If we're instantiating a local function declaration, put the result
2028
  // in the enclosing namespace; otherwise we need to find the instantiated
2029
  // context.
2030
141k
  DeclContext *DC;
2031
141k
  if (D->isLocalExternDecl()) {
2032
105
    DC = Owner;
2033
105
    SemaRef.adjustContextForLocalExternDecl(DC);
2034
141k
  } else if (isFriend && 
QualifierLoc15.9k
) {
2035
10
    CXXScopeSpec SS;
2036
10
    SS.Adopt(QualifierLoc);
2037
10
    DC = SemaRef.computeDeclContext(SS);
2038
10
    if (!DC) 
return nullptr0
;
2039
141k
  } else {
2040
141k
    DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2041
141k
                                         TemplateArgs);
2042
141k
  }
2043
2044
141k
  DeclarationNameInfo NameInfo
2045
141k
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2046
2047
141k
  if (FunctionRewriteKind != RewriteKind::None)
2048
30
    adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2049
2050
141k
  FunctionDecl *Function;
2051
141k
  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2052
249
    Function = CXXDeductionGuideDecl::Create(
2053
249
        SemaRef.Context, DC, D->getInnerLocStart(),
2054
249
        InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2055
249
        D->getSourceRange().getEnd());
2056
249
    if (DGuide->isCopyDeductionCandidate())
2057
17
      cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
2058
249
    Function->setAccess(D->getAccess());
2059
141k
  } else {
2060
141k
    Function = FunctionDecl::Create(
2061
141k
        SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2062
141k
        D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2063
141k
        D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2064
141k
        TrailingRequiresClause);
2065
141k
    Function->setRangeEnd(D->getSourceRange().getEnd());
2066
141k
  }
2067
2068
141k
  if (D->isInlined())
2069
48.6k
    Function->setImplicitlyInline();
2070
2071
141k
  if (QualifierLoc)
2072
10
    Function->setQualifierInfo(QualifierLoc);
2073
2074
141k
  if (D->isLocalExternDecl())
2075
105
    Function->setLocalExternDecl();
2076
2077
141k
  DeclContext *LexicalDC = Owner;
2078
141k
  if (!isFriend && 
D->isOutOfLine()125k
&&
!D->isLocalExternDecl()0
) {
2079
0
    assert(D->getDeclContext()->isFileContext());
2080
0
    LexicalDC = D->getDeclContext();
2081
0
  }
2082
2083
0
  Function->setLexicalDeclContext(LexicalDC);
2084
2085
  // Attach the parameters
2086
357k
  for (unsigned P = 0; P < Params.size(); 
++P215k
)
2087
215k
    if (Params[P])
2088
215k
      Params[P]->setOwningFunction(Function);
2089
141k
  Function->setParams(Params);
2090
2091
141k
  if (TrailingRequiresClause)
2092
52
    Function->setTrailingRequiresClause(TrailingRequiresClause);
2093
2094
141k
  if (TemplateParams) {
2095
    // Our resulting instantiation is actually a function template, since we
2096
    // are substituting only the outer template parameters. For example, given
2097
    //
2098
    //   template<typename T>
2099
    //   struct X {
2100
    //     template<typename U> friend void f(T, U);
2101
    //   };
2102
    //
2103
    //   X<int> x;
2104
    //
2105
    // We are instantiating the friend function template "f" within X<int>,
2106
    // which means substituting int for T, but leaving "f" as a friend function
2107
    // template.
2108
    // Build the function template itself.
2109
6.95k
    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2110
6.95k
                                                    Function->getLocation(),
2111
6.95k
                                                    Function->getDeclName(),
2112
6.95k
                                                    TemplateParams, Function);
2113
6.95k
    Function->setDescribedFunctionTemplate(FunctionTemplate);
2114
2115
6.95k
    FunctionTemplate->setLexicalDeclContext(LexicalDC);
2116
2117
6.95k
    if (isFriend && 
D->isThisDeclarationADefinition()6.95k
) {
2118
20
      FunctionTemplate->setInstantiatedFromMemberTemplate(
2119
20
                                           D->getDescribedFunctionTemplate());
2120
20
    }
2121
134k
  } else if (FunctionTemplate) {
2122
    // Record this function template specialization.
2123
125k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2124
125k
    Function->setFunctionTemplateSpecialization(FunctionTemplate,
2125
125k
                            TemplateArgumentList::CreateCopy(SemaRef.Context,
2126
125k
                                                             Innermost),
2127
125k
                                                /*InsertPos=*/nullptr);
2128
125k
  } else 
if (9.00k
isFriend9.00k
&&
D->isThisDeclarationADefinition()8.90k
) {
2129
    // Do not connect the friend to the template unless it's actually a
2130
    // definition. We don't want non-template functions to be marked as being
2131
    // template instantiations.
2132
4.99k
    Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2133
4.99k
  }
2134
2135
141k
  if (isFriend) {
2136
15.9k
    Function->setObjectOfFriendDecl();
2137
15.9k
    if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2138
6.95k
      FT->setObjectOfFriendDecl();
2139
15.9k
  }
2140
2141
141k
  if (InitFunctionInstantiation(Function, D))
2142
0
    Function->setInvalidDecl();
2143
2144
141k
  bool IsExplicitSpecialization = false;
2145
2146
141k
  LookupResult Previous(
2147
141k
      SemaRef, Function->getDeclName(), SourceLocation(),
2148
141k
      D->isLocalExternDecl() ? 
Sema::LookupRedeclarationWithLinkage105
2149
141k
                             : 
Sema::LookupOrdinaryName141k
,
2150
141k
      D->isLocalExternDecl() ? 
Sema::ForExternalRedeclaration105
2151
141k
                             : 
SemaRef.forRedeclarationInCurContext()141k
);
2152
2153
141k
  if (DependentFunctionTemplateSpecializationInfo *Info
2154
141k
        = D->getDependentSpecializationInfo()) {
2155
3.62k
    assert(isFriend && "non-friend has dependent specialization info?");
2156
2157
    // Instantiate the explicit template arguments.
2158
0
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2159
3.62k
                                          Info->getRAngleLoc());
2160
3.62k
    if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2161
3.62k
                                       ExplicitArgs))
2162
0
      return nullptr;
2163
2164
    // Map the candidate templates to their instantiations.
2165
32.4k
    
for (unsigned I = 0, E = Info->getNumTemplates(); 3.62k
I != E;
++I28.8k
) {
2166
28.8k
      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2167
28.8k
                                                Info->getTemplate(I),
2168
28.8k
                                                TemplateArgs);
2169
28.8k
      if (!Temp) 
return nullptr0
;
2170
2171
28.8k
      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2172
28.8k
    }
2173
2174
3.62k
    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2175
3.62k
                                                    &ExplicitArgs,
2176
3.62k
                                                    Previous))
2177
0
      Function->setInvalidDecl();
2178
2179
3.62k
    IsExplicitSpecialization = true;
2180
137k
  } else if (const ASTTemplateArgumentListInfo *Info =
2181
137k
                 D->getTemplateSpecializationArgsAsWritten()) {
2182
    // The name of this function was written as a template-id.
2183
1
    SemaRef.LookupQualifiedName(Previous, DC);
2184
2185
    // Instantiate the explicit template arguments.
2186
1
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2187
1
                                          Info->getRAngleLoc());
2188
1
    if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2189
1
                                       ExplicitArgs))
2190
0
      return nullptr;
2191
2192
1
    if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2193
1
                                                    &ExplicitArgs,
2194
1
                                                    Previous))
2195
0
      Function->setInvalidDecl();
2196
2197
1
    IsExplicitSpecialization = true;
2198
137k
  } else if (TemplateParams || 
!FunctionTemplate130k
) {
2199
    // Look only into the namespace where the friend would be declared to
2200
    // find a previous declaration. This is the innermost enclosing namespace,
2201
    // as described in ActOnFriendFunctionDecl.
2202
12.3k
    SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2203
2204
    // In C++, the previous declaration we find might be a tag type
2205
    // (class or enum). In this case, the new declaration will hide the
2206
    // tag type. Note that this does does not apply if we're declaring a
2207
    // typedef (C++ [dcl.typedef]p4).
2208
12.3k
    if (Previous.isSingleTagDecl())
2209
0
      Previous.clear();
2210
2211
    // Filter out previous declarations that don't match the scope. The only
2212
    // effect this has is to remove declarations found in inline namespaces
2213
    // for friend declarations with unqualified names.
2214
12.3k
    SemaRef.FilterLookupForScope(Previous, DC, /*Scope*/ nullptr,
2215
12.3k
                                 /*ConsiderLinkage*/ true,
2216
12.3k
                                 QualifierLoc.hasQualifier());
2217
12.3k
  }
2218
2219
141k
  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2220
141k
                                   IsExplicitSpecialization);
2221
2222
  // Check the template parameter list against the previous declaration. The
2223
  // goal here is to pick up default arguments added since the friend was
2224
  // declared; we know the template parameter lists match, since otherwise
2225
  // we would not have picked this template as the previous declaration.
2226
141k
  if (isFriend && 
TemplateParams15.9k
&&
FunctionTemplate->getPreviousDecl()6.95k
) {
2227
6.93k
    SemaRef.CheckTemplateParameterList(
2228
6.93k
        TemplateParams,
2229
6.93k
        FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2230
6.93k
        Function->isThisDeclarationADefinition()
2231
6.93k
            ? 
Sema::TPC_FriendFunctionTemplateDefinition0
2232
6.93k
            : Sema::TPC_FriendFunctionTemplate);
2233
6.93k
  }
2234
2235
  // If we're introducing a friend definition after the first use, trigger
2236
  // instantiation.
2237
  // FIXME: If this is a friend function template definition, we should check
2238
  // to see if any specializations have been used.
2239
141k
  if (isFriend && 
D->isThisDeclarationADefinition()15.9k
&&
Function->isUsed(false)5.02k
) {
2240
7
    if (MemberSpecializationInfo *MSInfo =
2241
7
            Function->getMemberSpecializationInfo()) {
2242
7
      if (MSInfo->getPointOfInstantiation().isInvalid()) {
2243
7
        SourceLocation Loc = D->getLocation(); // FIXME
2244
7
        MSInfo->setPointOfInstantiation(Loc);
2245
7
        SemaRef.PendingLocalImplicitInstantiations.push_back(
2246
7
            std::make_pair(Function, Loc));
2247
7
      }
2248
7
    }
2249
7
  }
2250
2251
141k
  if (D->isExplicitlyDefaulted()) {
2252
84
    if (SubstDefaultedFunction(Function, D))
2253
0
      return nullptr;
2254
84
  }
2255
141k
  if (D->isDeleted())
2256
1.52k
    SemaRef.SetDeclDeleted(Function, D->getLocation());
2257
2258
141k
  NamedDecl *PrincipalDecl =
2259
141k
      (TemplateParams ? 
cast<NamedDecl>(FunctionTemplate)6.95k
:
Function134k
);
2260
2261
  // If this declaration lives in a different context from its lexical context,
2262
  // add it to the corresponding lookup table.
2263
141k
  if (isFriend ||
2264
141k
      
(125k
Function->isLocalExternDecl()125k
&&
!Function->getPreviousDecl()105
))
2265
15.9k
    DC->makeDeclVisibleInContext(PrincipalDecl);
2266
2267
141k
  if (Function->isOverloadedOperator() && 
!DC->isRecord()19.2k
&&
2268
141k
      
PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)19.2k
)
2269
14.3k
    PrincipalDecl->setNonMemberOperator();
2270
2271
141k
  return Function;
2272
141k
}
2273
2274
Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2275
    CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2276
    Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs,
2277
1.06M
    RewriteKind FunctionRewriteKind) {
2278
1.06M
  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2279
1.06M
  if (FunctionTemplate && 
!TemplateParams385k
) {
2280
    // We are creating a function template specialization from a function
2281
    // template. Check whether there is already a function template
2282
    // specialization for this particular set of template arguments.
2283
191k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2284
2285
191k
    void *InsertPos = nullptr;
2286
191k
    FunctionDecl *SpecFunc
2287
191k
      = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2288
2289
    // If we already have a function template specialization, return it.
2290
191k
    if (SpecFunc)
2291
67.0k
      return SpecFunc;
2292
191k
  }
2293
2294
1.00M
  bool isFriend;
2295
1.00M
  if (FunctionTemplate)
2296
318k
    isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2297
684k
  else
2298
684k
    isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2299
2300
1.00M
  bool MergeWithParentScope = (TemplateParams != nullptr) ||
2301
1.00M
    
!(808k
isa<Decl>(Owner)808k
&&
2302
808k
      cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2303
1.00M
  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2304
2305
  // Instantiate enclosing template arguments for friends.
2306
1.00M
  SmallVector<TemplateParameterList *, 4> TempParamLists;
2307
1.00M
  unsigned NumTempParamLists = 0;
2308
1.00M
  if (isFriend && 
(NumTempParamLists = D->getNumTemplateParameterLists())60
) {
2309
3
    TempParamLists.resize(NumTempParamLists);
2310
10
    for (unsigned I = 0; I != NumTempParamLists; 
++I7
) {
2311
7
      TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2312
7
      TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2313
7
      if (!InstParams)
2314
0
        return nullptr;
2315
7
      TempParamLists[I] = InstParams;
2316
7
    }
2317
3
  }
2318
2319
1.00M
  ExplicitSpecifier InstantiatedExplicitSpecifier =
2320
1.00M
      instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2321
1.00M
                                   ExplicitSpecifier::getFromDecl(D), D);
2322
1.00M
  if (InstantiatedExplicitSpecifier.isInvalid())
2323
134
    return nullptr;
2324
2325
  // Implicit destructors/constructors created for local classes in
2326
  // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2327
  // Unfortunately there isn't enough context in those functions to
2328
  // conditionally populate the TSI without breaking non-template related use
2329
  // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2330
  // a proper transformation.
2331
1.00M
  if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2332
1.00M
      
!D->getTypeSourceInfo()3.91k
&&
2333
1.00M
      
isa<CXXConstructorDecl, CXXDestructorDecl>(D)12
) {
2334
12
    TypeSourceInfo *TSI =
2335
12
        SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2336
12
    D->setTypeSourceInfo(TSI);
2337
12
  }
2338
2339
1.00M
  SmallVector<ParmVarDecl *, 4> Params;
2340
1.00M
  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2341
1.00M
  if (!TInfo)
2342
25.3k
    return nullptr;
2343
977k
  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2344
2345
977k
  if (TemplateParams && 
TemplateParams->size()193k
) {
2346
193k
    auto *LastParam =
2347
193k
        dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2348
193k
    if (LastParam && 
LastParam->isImplicit()162k
&&
2349
193k
        
LastParam->hasTypeConstraint()17
) {
2350
      // In abbreviated templates, the type-constraints of invented template
2351
      // type parameters are instantiated with the function type, invalidating
2352
      // the TemplateParameterList which relied on the template type parameter
2353
      // not having a type constraint. Recreate the TemplateParameterList with
2354
      // the updated parameter list.
2355
5
      TemplateParams = TemplateParameterList::Create(
2356
5
          SemaRef.Context, TemplateParams->getTemplateLoc(),
2357
5
          TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2358
5
          TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2359
5
    }
2360
193k
  }
2361
2362
977k
  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2363
977k
  if (QualifierLoc) {
2364
344
    QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2365
344
                                                 TemplateArgs);
2366
344
    if (!QualifierLoc)
2367
1
      return nullptr;
2368
344
  }
2369
2370
  // FIXME: Concepts: Do not substitute into constraint expressions
2371
977k
  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2372
977k
  if (TrailingRequiresClause) {
2373
34
    EnterExpressionEvaluationContext ConstantEvaluated(
2374
34
        SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
2375
34
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
2376
34
    Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext,
2377
34
                                     D->getMethodQualifiers(), ThisContext);
2378
34
    ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause,
2379
34
                                           TemplateArgs);
2380
34
    if (SubstRC.isInvalid())
2381
0
      return nullptr;
2382
34
    TrailingRequiresClause = SubstRC.get();
2383
34
    if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause))
2384
0
      return nullptr;
2385
34
  }
2386
2387
977k
  DeclContext *DC = Owner;
2388
977k
  if (isFriend) {
2389
59
    if (QualifierLoc) {
2390
59
      CXXScopeSpec SS;
2391
59
      SS.Adopt(QualifierLoc);
2392
59
      DC = SemaRef.computeDeclContext(SS);
2393
2394
59
      if (DC && 
SemaRef.RequireCompleteDeclContext(SS, DC)57
)
2395
0
        return nullptr;
2396
59
    } else {
2397
0
      DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2398
0
                                           D->getDeclContext(),
2399
0
                                           TemplateArgs);
2400
0
    }
2401
59
    if (!DC) 
return nullptr2
;
2402
59
  }
2403
2404
977k
  DeclarationNameInfo NameInfo
2405
977k
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2406
2407
977k
  if (FunctionRewriteKind != RewriteKind::None)
2408
87
    adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2409
2410
  // Build the instantiated method declaration.
2411
977k
  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2412
977k
  CXXMethodDecl *Method = nullptr;
2413
2414
977k
  SourceLocation StartLoc = D->getInnerLocStart();
2415
977k
  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2416
223k
    Method = CXXConstructorDecl::Create(
2417
223k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2418
223k
        InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2419
223k
        Constructor->isInlineSpecified(), false,
2420
223k
        Constructor->getConstexprKind(), InheritedConstructor(),
2421
223k
        TrailingRequiresClause);
2422
223k
    Method->setRangeEnd(Constructor->getEndLoc());
2423
754k
  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2424
12.9k
    Method = CXXDestructorDecl::Create(
2425
12.9k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2426
12.9k
        Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2427
12.9k
        Destructor->getConstexprKind(), TrailingRequiresClause);
2428
12.9k
    Method->setRangeEnd(Destructor->getEndLoc());
2429
12.9k
    Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2430
12.9k
        SemaRef.Context.getCanonicalType(
2431
12.9k
            SemaRef.Context.getTypeDeclType(Record))));
2432
741k
  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2433
12.5k
    Method = CXXConversionDecl::Create(
2434
12.5k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2435
12.5k
        Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2436
12.5k
        InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2437
12.5k
        Conversion->getEndLoc(), TrailingRequiresClause);
2438
728k
  } else {
2439
728k
    StorageClass SC = D->isStatic() ? 
SC_Static181k
:
SC_None546k
;
2440
728k
    Method = CXXMethodDecl::Create(
2441
728k
        SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2442
728k
        D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2443
728k
        D->getEndLoc(), TrailingRequiresClause);
2444
728k
  }
2445
2446
977k
  if (D->isInlined())
2447
708k
    Method->setImplicitlyInline();
2448
2449
977k
  if (QualifierLoc)
2450
341
    Method->setQualifierInfo(QualifierLoc);
2451
2452
977k
  if (TemplateParams) {
2453
    // Our resulting instantiation is actually a function template, since we
2454
    // are substituting only the outer template parameters. For example, given
2455
    //
2456
    //   template<typename T>
2457
    //   struct X {
2458
    //     template<typename U> void f(T, U);
2459
    //   };
2460
    //
2461
    //   X<int> x;
2462
    //
2463
    // We are instantiating the member template "f" within X<int>, which means
2464
    // substituting int for T, but leaving "f" as a member function template.
2465
    // Build the function template itself.
2466
193k
    FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2467
193k
                                                    Method->getLocation(),
2468
193k
                                                    Method->getDeclName(),
2469
193k
                                                    TemplateParams, Method);
2470
193k
    if (isFriend) {
2471
14
      FunctionTemplate->setLexicalDeclContext(Owner);
2472
14
      FunctionTemplate->setObjectOfFriendDecl();
2473
193k
    } else if (D->isOutOfLine())
2474
0
      FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2475
193k
    Method->setDescribedFunctionTemplate(FunctionTemplate);
2476
783k
  } else if (FunctionTemplate) {
2477
    // Record this function template specialization.
2478
99.3k
    ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2479
99.3k
    Method->setFunctionTemplateSpecialization(FunctionTemplate,
2480
99.3k
                         TemplateArgumentList::CreateCopy(SemaRef.Context,
2481
99.3k
                                                          Innermost),
2482
99.3k
                                              /*InsertPos=*/nullptr);
2483
683k
  } else if (!isFriend) {
2484
    // Record that this is an instantiation of a member function.
2485
683k
    Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2486
683k
  }
2487
2488
  // If we are instantiating a member function defined
2489
  // out-of-line, the instantiation will have the same lexical
2490
  // context (which will be a namespace scope) as the template.
2491
977k
  if (isFriend) {
2492
57
    if (NumTempParamLists)
2493
0
      Method->setTemplateParameterListsInfo(
2494
0
          SemaRef.Context,
2495
0
          llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2496
2497
57
    Method->setLexicalDeclContext(Owner);
2498
57
    Method->setObjectOfFriendDecl();
2499
977k
  } else if (D->isOutOfLine())
2500
284
    Method->setLexicalDeclContext(D->getLexicalDeclContext());
2501
2502
  // Attach the parameters
2503
2.07M
  for (unsigned P = 0; P < Params.size(); 
++P1.09M
)
2504
1.09M
    Params[P]->setOwningFunction(Method);
2505
977k
  Method->setParams(Params);
2506
2507
977k
  if (InitMethodInstantiation(Method, D))
2508
0
    Method->setInvalidDecl();
2509
2510
977k
  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2511
977k
                        Sema::ForExternalRedeclaration);
2512
2513
977k
  bool IsExplicitSpecialization = false;
2514
2515
  // If the name of this function was written as a template-id, instantiate
2516
  // the explicit template arguments.
2517
977k
  if (DependentFunctionTemplateSpecializationInfo *Info
2518
977k
        = D->getDependentSpecializationInfo()) {
2519
8
    assert(isFriend && "non-friend has dependent specialization info?");
2520
2521
    // Instantiate the explicit template arguments.
2522
0
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2523
8
                                          Info->getRAngleLoc());
2524
8
    if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2525
8
                                       ExplicitArgs))
2526
0
      return nullptr;
2527
2528
    // Map the candidate templates to their instantiations.
2529
16
    
for (unsigned I = 0, E = Info->getNumTemplates(); 8
I != E;
++I8
) {
2530
8
      Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2531
8
                                                Info->getTemplate(I),
2532
8
                                                TemplateArgs);
2533
8
      if (!Temp) 
return nullptr0
;
2534
2535
8
      Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2536
8
    }
2537
2538
8
    if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2539
8
                                                    &ExplicitArgs,
2540
8
                                                    Previous))
2541
0
      Method->setInvalidDecl();
2542
2543
8
    IsExplicitSpecialization = true;
2544
977k
  } else if (const ASTTemplateArgumentListInfo *Info =
2545
977k
                 ClassScopeSpecializationArgs.getValueOr(
2546
977k
                     D->getTemplateSpecializationArgsAsWritten())) {
2547
80
    SemaRef.LookupQualifiedName(Previous, DC);
2548
2549
80
    TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2550
80
                                          Info->getRAngleLoc());
2551
80
    if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2552
80
                                       ExplicitArgs))
2553
0
      return nullptr;
2554
2555
80
    if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2556
80
                                                    &ExplicitArgs,
2557
80
                                                    Previous))
2558
0
      Method->setInvalidDecl();
2559
2560
80
    IsExplicitSpecialization = true;
2561
977k
  } else if (ClassScopeSpecializationArgs) {
2562
    // Class-scope explicit specialization written without explicit template
2563
    // arguments.
2564
11
    SemaRef.LookupQualifiedName(Previous, DC);
2565
11
    if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2566
0
      Method->setInvalidDecl();
2567
2568
11
    IsExplicitSpecialization = true;
2569
977k
  } else if (!FunctionTemplate || 
TemplateParams293k
||
isFriend99.3k
) {
2570
877k
    SemaRef.LookupQualifiedName(Previous, Record);
2571
2572
    // In C++, the previous declaration we find might be a tag type
2573
    // (class or enum). In this case, the new declaration will hide the
2574
    // tag type. Note that this does does not apply if we're declaring a
2575
    // typedef (C++ [dcl.typedef]p4).
2576
877k
    if (Previous.isSingleTagDecl())
2577
0
      Previous.clear();
2578
877k
  }
2579
2580
977k
  SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2581
977k
                                   IsExplicitSpecialization);
2582
2583
977k
  if (D->isPure())
2584
233
    SemaRef.CheckPureMethod(Method, SourceRange());
2585
2586
  // Propagate access.  For a non-friend declaration, the access is
2587
  // whatever we're propagating from.  For a friend, it should be the
2588
  // previous declaration we just found.
2589
977k
  if (isFriend && 
Method->getPreviousDecl()57
)
2590
55
    Method->setAccess(Method->getPreviousDecl()->getAccess());
2591
977k
  else
2592
977k
    Method->setAccess(D->getAccess());
2593
977k
  if (FunctionTemplate)
2594
293k
    FunctionTemplate->setAccess(Method->getAccess());
2595
2596
977k
  SemaRef.CheckOverrideControl(Method);
2597
2598
  // If a function is defined as defaulted or deleted, mark it as such now.
2599
977k
  if (D->isExplicitlyDefaulted()) {
2600
16.6k
    if (SubstDefaultedFunction(Method, D))
2601
0
      return nullptr;
2602
16.6k
  }
2603
977k
  if (D->isDeletedAsWritten())
2604
6.08k
    SemaRef.SetDeclDeleted(Method, Method->getLocation());
2605
2606
  // If this is an explicit specialization, mark the implicitly-instantiated
2607
  // template specialization as being an explicit specialization too.
2608
  // FIXME: Is this necessary?
2609
977k
  if (IsExplicitSpecialization && 
!isFriend99
)
2610
90
    SemaRef.CompleteMemberSpecialization(Method, Previous);
2611
2612
  // If there's a function template, let our caller handle it.
2613
977k
  if (FunctionTemplate) {
2614
    // do nothing
2615
2616
  // Don't hide a (potentially) valid declaration with an invalid one.
2617
683k
  } else if (Method->isInvalidDecl() && 
!Previous.empty()5
) {
2618
    // do nothing
2619
2620
  // Otherwise, check access to friends and make them visible.
2621
683k
  } else if (isFriend) {
2622
    // We only need to re-check access for methods which we didn't
2623
    // manage to match during parsing.
2624
42
    if (!D->getPreviousDecl())
2625
37
      SemaRef.CheckFriendAccess(Method);
2626
2627
42
    Record->makeDeclVisibleInContext(Method);
2628
2629
  // Otherwise, add the declaration.  We don't need to do this for
2630
  // class-scope specializations because we'll have matched them with
2631
  // the appropriate template.
2632
683k
  } else {
2633
683k
    Owner->addDecl(Method);
2634
683k
  }
2635
2636
  // PR17480: Honor the used attribute to instantiate member function
2637
  // definitions
2638
977k
  if (Method->hasAttr<UsedAttr>()) {
2639
5
    if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2640
5
      SourceLocation Loc;
2641
5
      if (const MemberSpecializationInfo *MSInfo =
2642
5
              A->getMemberSpecializationInfo())
2643
0
        Loc = MSInfo->getPointOfInstantiation();
2644
5
      else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2645
5
        Loc = Spec->getPointOfInstantiation();
2646
5
      SemaRef.MarkFunctionReferenced(Loc, Method);
2647
5
    }
2648
5
  }
2649
2650
977k
  return Method;
2651
977k
}
2652
2653
197k
Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2654
197k
  return VisitCXXMethodDecl(D);
2655
197k
}
2656
2657
12.9k
Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2658
12.9k
  return VisitCXXMethodDecl(D);
2659
12.9k
}
2660
2661
14.5k
Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2662
14.5k
  return VisitCXXMethodDecl(D);
2663
14.5k
}
2664
2665
0
Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2666
0
  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2667
0
                                  /*ExpectParameterPack=*/ false);
2668
0
}
2669
2670
Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2671
418k
                                                    TemplateTypeParmDecl *D) {
2672
418k
  assert(D->getTypeForDecl()->isTemplateTypeParmType());
2673
2674
0
  Optional<unsigned> NumExpanded;
2675
2676
418k
  if (const TypeConstraint *TC = D->getTypeConstraint()) {
2677
46
    if (D->isPackExpansion() && 
!D->isExpandedParameterPack()3
) {
2678
3
      assert(TC->getTemplateArgsAsWritten() &&
2679
3
             "type parameter can only be an expansion when explicit arguments "
2680
3
             "are specified");
2681
      // The template type parameter pack's type is a pack expansion of types.
2682
      // Determine whether we need to expand this parameter pack into separate
2683
      // types.
2684
0
      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2685
3
      for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2686
5
        SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2687
2688
      // Determine whether the set of unexpanded parameter packs can and should
2689
      // be expanded.
2690
3
      bool Expand = true;
2691
3
      bool RetainExpansion = false;
2692
3
      if (SemaRef.CheckParameterPacksForExpansion(
2693
3
              cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2694
3
                  ->getEllipsisLoc(),
2695
3
              SourceRange(TC->getConceptNameLoc(),
2696
3
                          TC->hasExplicitTemplateArgs() ?
2697
3
                          TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2698
3
                          
TC->getConceptNameInfo().getEndLoc()0
),
2699
3
              Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2700
0
        return nullptr;
2701
3
    }
2702
46
  }
2703
2704
418k
  TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2705
418k
      SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2706
418k
      D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2707
418k
      D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2708
418k
      D->hasTypeConstraint(), NumExpanded);
2709
2710
418k
  Inst->setAccess(AS_public);
2711
418k
  Inst->setImplicit(D->isImplicit());
2712
418k
  if (auto *TC = D->getTypeConstraint()) {
2713
46
    if (!D->isImplicit()) {
2714
      // Invented template parameter type constraints will be instantiated with
2715
      // the corresponding auto-typed parameter as it might reference other
2716
      // parameters.
2717
2718
      // TODO: Concepts: do not instantiate the constraint (delayed constraint
2719
      // substitution)
2720
34
      if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs))
2721
4
        return nullptr;
2722
34
    }
2723
46
  }
2724
418k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()112k
) {
2725
112k
    TypeSourceInfo *InstantiatedDefaultArg =
2726
112k
        SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2727
112k
                          D->getDefaultArgumentLoc(), D->getDeclName());
2728
112k
    if (InstantiatedDefaultArg)
2729
112k
      Inst->setDefaultArgument(InstantiatedDefaultArg);
2730
112k
  }
2731
2732
  // Introduce this template parameter's instantiation into the instantiation
2733
  // scope.
2734
418k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2735
2736
418k
  return Inst;
2737
418k
}
2738
2739
Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2740
111k
                                                 NonTypeTemplateParmDecl *D) {
2741
  // Substitute into the type of the non-type template parameter.
2742
111k
  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2743
111k
  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2744
111k
  SmallVector<QualType, 4> ExpandedParameterPackTypes;
2745
111k
  bool IsExpandedParameterPack = false;
2746
111k
  TypeSourceInfo *DI;
2747
111k
  QualType T;
2748
111k
  bool Invalid = false;
2749
2750
111k
  if (D->isExpandedParameterPack()) {
2751
    // The non-type template parameter pack is an already-expanded pack
2752
    // expansion of types. Substitute into each of the expanded types.
2753
3
    ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2754
3
    ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2755
12
    for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; 
++I9
) {
2756
9
      TypeSourceInfo *NewDI =
2757
9
          SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2758
9
                            D->getLocation(), D->getDeclName());
2759
9
      if (!NewDI)
2760
0
        return nullptr;
2761
2762
9
      QualType NewT =
2763
9
          SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2764
9
      if (NewT.isNull())
2765
0
        return nullptr;
2766
2767
9
      ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2768
9
      ExpandedParameterPackTypes.push_back(NewT);
2769
9
    }
2770
2771
3
    IsExpandedParameterPack = true;
2772
3
    DI = D->getTypeSourceInfo();
2773
3
    T = DI->getType();
2774
111k
  } else if (D->isPackExpansion()) {
2775
    // The non-type template parameter pack's type is a pack expansion of types.
2776
    // Determine whether we need to expand this parameter pack into separate
2777
    // types.
2778
53
    PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2779
53
    TypeLoc Pattern = Expansion.getPatternLoc();
2780
53
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2781
53
    SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2782
2783
    // Determine whether the set of unexpanded parameter packs can and should
2784
    // be expanded.
2785
53
    bool Expand = true;
2786
53
    bool RetainExpansion = false;
2787
53
    Optional<unsigned> OrigNumExpansions
2788
53
      = Expansion.getTypePtr()->getNumExpansions();
2789
53
    Optional<unsigned> NumExpansions = OrigNumExpansions;
2790
53
    if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2791
53
                                                Pattern.getSourceRange(),
2792
53
                                                Unexpanded,
2793
53
                                                TemplateArgs,
2794
53
                                                Expand, RetainExpansion,
2795
53
                                                NumExpansions))
2796
0
      return nullptr;
2797
2798
53
    if (Expand) {
2799
128
      for (unsigned I = 0; I != *NumExpansions; 
++I81
) {
2800
82
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2801
82
        TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2802
82
                                                  D->getLocation(),
2803
82
                                                  D->getDeclName());
2804
82
        if (!NewDI)
2805
0
          return nullptr;
2806
2807
82
        QualType NewT =
2808
82
            SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2809
82
        if (NewT.isNull())
2810
1
          return nullptr;
2811
2812
81
        ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2813
81
        ExpandedParameterPackTypes.push_back(NewT);
2814
81
      }
2815
2816
      // Note that we have an expanded parameter pack. The "type" of this
2817
      // expanded parameter pack is the original expansion type, but callers
2818
      // will end up using the expanded parameter pack types for type-checking.
2819
46
      IsExpandedParameterPack = true;
2820
46
      DI = D->getTypeSourceInfo();
2821
46
      T = DI->getType();
2822
46
    } else {
2823
      // We cannot fully expand the pack expansion now, so substitute into the
2824
      // pattern and create a new pack expansion type.
2825
6
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2826
6
      TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2827
6
                                                     D->getLocation(),
2828
6
                                                     D->getDeclName());
2829
6
      if (!NewPattern)
2830
0
        return nullptr;
2831
2832
6
      SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2833
6
      DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2834
6
                                      NumExpansions);
2835
6
      if (!DI)
2836
0
        return nullptr;
2837
2838
6
      T = DI->getType();
2839
6
    }
2840
111k
  } else {
2841
    // Simple case: substitution into a parameter that is not a parameter pack.
2842
111k
    DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2843
111k
                           D->getLocation(), D->getDeclName());
2844
111k
    if (!DI)
2845
6
      return nullptr;
2846
2847
    // Check that this type is acceptable for a non-type template parameter.
2848
111k
    T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2849
111k
    if (T.isNull()) {
2850
4
      T = SemaRef.Context.IntTy;
2851
4
      Invalid = true;
2852
4
    }
2853
111k
  }
2854
2855
111k
  NonTypeTemplateParmDecl *Param;
2856
111k
  if (IsExpandedParameterPack)
2857
49
    Param = NonTypeTemplateParmDecl::Create(
2858
49
        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2859
49
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2860
49
        D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2861
49
        ExpandedParameterPackTypesAsWritten);
2862
111k
  else
2863
111k
    Param = NonTypeTemplateParmDecl::Create(
2864
111k
        SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2865
111k
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2866
111k
        D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2867
2868
111k
  if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
2869
20
    if (AutoLoc.isConstrained())
2870
0
      if (SemaRef.AttachTypeConstraint(
2871
0
              AutoLoc, Param,
2872
0
              IsExpandedParameterPack
2873
0
                ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
2874
0
                    .getEllipsisLoc()
2875
0
                : SourceLocation()))
2876
0
        Invalid = true;
2877
2878
111k
  Param->setAccess(AS_public);
2879
111k
  Param->setImplicit(D->isImplicit());
2880
111k
  if (Invalid)
2881
4
    Param->setInvalidDecl();
2882
2883
111k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()39.6k
) {
2884
39.6k
    EnterExpressionEvaluationContext ConstantEvaluated(
2885
39.6k
        SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2886
39.6k
    ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2887
39.6k
    if (!Value.isInvalid())
2888
39.6k
      Param->setDefaultArgument(Value.get());
2889
39.6k
  }
2890
2891
  // Introduce this template parameter's instantiation into the instantiation
2892
  // scope.
2893
111k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2894
111k
  return Param;
2895
111k
}
2896
2897
static void collectUnexpandedParameterPacks(
2898
    Sema &S,
2899
    TemplateParameterList *Params,
2900
17
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2901
18
  for (const auto &P : *Params) {
2902
18
    if (P->isTemplateParameterPack())
2903
0
      continue;
2904
18
    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2905
17
      S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2906
17
                                        Unexpanded);
2907
18
    if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2908
0
      collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2909
0
                                      Unexpanded);
2910
18
  }
2911
17
}
2912
2913
Decl *
2914
TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2915
9.08k
                                                  TemplateTemplateParmDecl *D) {
2916
  // Instantiate the template parameter list of the template template parameter.
2917
9.08k
  TemplateParameterList *TempParams = D->getTemplateParameters();
2918
9.08k
  TemplateParameterList *InstParams;
2919
9.08k
  SmallVector<TemplateParameterList*, 8> ExpandedParams;
2920
2921
9.08k
  bool IsExpandedParameterPack = false;
2922
2923
9.08k
  if (D->isExpandedParameterPack()) {
2924
    // The template template parameter pack is an already-expanded pack
2925
    // expansion of template parameters. Substitute into each of the expanded
2926
    // parameters.
2927
1
    ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2928
1
    for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2929
1
         I != N; 
++I0
) {
2930
0
      LocalInstantiationScope Scope(SemaRef);
2931
0
      TemplateParameterList *Expansion =
2932
0
        SubstTemplateParams(D->getExpansionTemplateParameters(I));
2933
0
      if (!Expansion)
2934
0
        return nullptr;
2935
0
      ExpandedParams.push_back(Expansion);
2936
0
    }
2937
2938
1
    IsExpandedParameterPack = true;
2939
1
    InstParams = TempParams;
2940
9.08k
  } else if (D->isPackExpansion()) {
2941
    // The template template parameter pack expands to a pack of template
2942
    // template parameters. Determine whether we need to expand this parameter
2943
    // pack into separate parameters.
2944
17
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2945
17
    collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2946
17
                                    Unexpanded);
2947
2948
    // Determine whether the set of unexpanded parameter packs can and should
2949
    // be expanded.
2950
17
    bool Expand = true;
2951
17
    bool RetainExpansion = false;
2952
17
    Optional<unsigned> NumExpansions;
2953
17
    if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2954
17
                                                TempParams->getSourceRange(),
2955
17
                                                Unexpanded,
2956
17
                                                TemplateArgs,
2957
17
                                                Expand, RetainExpansion,
2958
17
                                                NumExpansions))
2959
0
      return nullptr;
2960
2961
17
    if (Expand) {
2962
8.24k
      for (unsigned I = 0; I != *NumExpansions; 
++I8.22k
) {
2963
8.22k
        Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2964
8.22k
        LocalInstantiationScope Scope(SemaRef);
2965
8.22k
        TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2966
8.22k
        if (!Expansion)
2967
0
          return nullptr;
2968
8.22k
        ExpandedParams.push_back(Expansion);
2969
8.22k
      }
2970
2971
      // Note that we have an expanded parameter pack. The "type" of this
2972
      // expanded parameter pack is the original expansion type, but callers
2973
      // will end up using the expanded parameter pack types for type-checking.
2974
17
      IsExpandedParameterPack = true;
2975
17
      InstParams = TempParams;
2976
17
    } else {
2977
      // We cannot fully expand the pack expansion now, so just substitute
2978
      // into the pattern.
2979
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2980
2981
0
      LocalInstantiationScope Scope(SemaRef);
2982
0
      InstParams = SubstTemplateParams(TempParams);
2983
0
      if (!InstParams)
2984
0
        return nullptr;
2985
0
    }
2986
9.06k
  } else {
2987
    // Perform the actual substitution of template parameters within a new,
2988
    // local instantiation scope.
2989
9.06k
    LocalInstantiationScope Scope(SemaRef);
2990
9.06k
    InstParams = SubstTemplateParams(TempParams);
2991
9.06k
    if (!InstParams)
2992
5
      return nullptr;
2993
9.06k
  }
2994
2995
  // Build the template template parameter.
2996
9.07k
  TemplateTemplateParmDecl *Param;
2997
9.07k
  if (IsExpandedParameterPack)
2998
18
    Param = TemplateTemplateParmDecl::Create(
2999
18
        SemaRef.Context, Owner, D->getLocation(),
3000
18
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3001
18
        D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
3002
9.05k
  else
3003
9.05k
    Param = TemplateTemplateParmDecl::Create(
3004
9.05k
        SemaRef.Context, Owner, D->getLocation(),
3005
9.05k
        D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3006
9.05k
        D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
3007
9.07k
  if (D->hasDefaultArgument() && 
!D->defaultArgumentWasInherited()7.46k
) {
3008
7.46k
    NestedNameSpecifierLoc QualifierLoc =
3009
7.46k
        D->getDefaultArgument().getTemplateQualifierLoc();
3010
7.46k
    QualifierLoc =
3011
7.46k
        SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3012
7.46k
    TemplateName TName = SemaRef.SubstTemplateName(
3013
7.46k
        QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3014
7.46k
        D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3015
7.46k
    if (!TName.isNull())
3016
7.46k
      Param->setDefaultArgument(
3017
7.46k
          SemaRef.Context,
3018
7.46k
          TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3019
7.46k
                              D->getDefaultArgument().getTemplateQualifierLoc(),
3020
7.46k
                              D->getDefaultArgument().getTemplateNameLoc()));
3021
7.46k
  }
3022
9.07k
  Param->setAccess(AS_public);
3023
9.07k
  Param->setImplicit(D->isImplicit());
3024
3025
  // Introduce this template parameter's instantiation into the instantiation
3026
  // scope.
3027
9.07k
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3028
3029
9.07k
  return Param;
3030
9.08k
}
3031
3032
14
Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3033
  // Using directives are never dependent (and never contain any types or
3034
  // expressions), so they require no explicit instantiation work.
3035
3036
14
  UsingDirectiveDecl *Inst
3037
14
    = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3038
14
                                 D->getNamespaceKeyLocation(),
3039
14
                                 D->getQualifierLoc(),
3040
14
                                 D->getIdentLocation(),
3041
14
                                 D->getNominatedNamespace(),
3042
14
                                 D->getCommonAncestor());
3043
3044
  // Add the using directive to its declaration context
3045
  // only if this is not a function or method.
3046
14
  if (!Owner->isFunctionOrMethod())
3047
0
    Owner->addDecl(Inst);
3048
3049
14
  return Inst;
3050
14
}
3051
3052
Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3053
                                                    BaseUsingDecl *Inst,
3054
269
                                                    LookupResult *Lookup) {
3055
3056
269
  bool isFunctionScope = Owner->isFunctionOrMethod();
3057
3058
385
  for (auto *Shadow : D->shadows()) {
3059
    // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3060
    // reconstruct it in the case where it matters. Hm, can we extract it from
3061
    // the DeclSpec when parsing and save it in the UsingDecl itself?
3062
385
    NamedDecl *OldTarget = Shadow->getTargetDecl();
3063
385
    if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3064
48
      if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3065
4
        OldTarget = BaseShadow;
3066
3067
385
    NamedDecl *InstTarget = nullptr;
3068
385
    if (auto *EmptyD =
3069
385
            dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3070
0
      InstTarget = UnresolvedUsingIfExistsDecl::Create(
3071
0
          SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3072
385
    } else {
3073
385
      InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3074
385
          Shadow->getLocation(), OldTarget, TemplateArgs));
3075
385
    }
3076
385
    if (!InstTarget)
3077
0
      return nullptr;
3078
3079
385
    UsingShadowDecl *PrevDecl = nullptr;
3080
385
    if (Lookup &&
3081
385
        
SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl)353
)
3082
3
      continue;
3083
3084
382
    if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3085
0
      PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3086
0
          Shadow->getLocation(), OldPrev, TemplateArgs));
3087
3088
382
    UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3089
382
        /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3090
382
    SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3091
3092
382
    if (isFunctionScope)
3093
18
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3094
382
  }
3095
3096
269
  return Inst;
3097
269
}
3098
3099
264
Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3100
3101
  // The nested name specifier may be dependent, for example
3102
  //     template <typename T> struct t {
3103
  //       struct s1 { T f1(); };
3104
  //       struct s2 : s1 { using s1::f1; };
3105
  //     };
3106
  //     template struct t<int>;
3107
  // Here, in using s1::f1, s1 refers to t<T>::s1;
3108
  // we need to substitute for t<int>::s1.
3109
264
  NestedNameSpecifierLoc QualifierLoc
3110
264
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3111
264
                                          TemplateArgs);
3112
264
  if (!QualifierLoc)
3113
0
    return nullptr;
3114
3115
  // For an inheriting constructor declaration, the name of the using
3116
  // declaration is the name of a constructor in this class, not in the
3117
  // base class.
3118
264
  DeclarationNameInfo NameInfo = D->getNameInfo();
3119
264
  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3120
17
    if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3121
17
      NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3122
17
          SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3123
3124
  // We only need to do redeclaration lookups if we're in a class scope (in
3125
  // fact, it's not really even possible in non-class scopes).
3126
264
  bool CheckRedeclaration = Owner->isRecord();
3127
264
  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3128
264
                    Sema::ForVisibleRedeclaration);
3129
3130
264
  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3131
264
                                       D->getUsingLoc(),
3132
264
                                       QualifierLoc,
3133
264
                                       NameInfo,
3134
264
                                       D->hasTypename());
3135
3136
264
  CXXScopeSpec SS;
3137
264
  SS.Adopt(QualifierLoc);
3138
264
  if (CheckRedeclaration) {
3139
249
    Prev.setHideTags(false);
3140
249
    SemaRef.LookupQualifiedName(Prev, Owner);
3141
3142
    // Check for invalid redeclarations.
3143
249
    if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3144
249
                                            D->hasTypename(), SS,
3145
249
                                            D->getLocation(), Prev))
3146
0
      NewUD->setInvalidDecl();
3147
249
  }
3148
3149
264
  if (!NewUD->isInvalidDecl() &&
3150
264
      SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3151
264
                                      NameInfo, D->getLocation(), nullptr, D))
3152
2
    NewUD->setInvalidDecl();
3153
3154
264
  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3155
264
  NewUD->setAccess(D->getAccess());
3156
264
  Owner->addDecl(NewUD);
3157
3158
  // Don't process the shadow decls for an invalid decl.
3159
264
  if (NewUD->isInvalidDecl())
3160
2
    return NewUD;
3161
3162
  // If the using scope was dependent, or we had dependent bases, we need to
3163
  // recheck the inheritance
3164
262
  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3165
16
    SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3166
3167
262
  return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? 
&Prev247
:
nullptr15
);
3168
264
}
3169
3170
7
Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3171
  // Cannot be a dependent type, but still could be an instantiation
3172
7
  EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3173
7
      D->getLocation(), D->getEnumDecl(), TemplateArgs));
3174
3175
7
  if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3176
0
    return nullptr;
3177
3178
7
  UsingEnumDecl *NewUD =
3179
7
      UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3180
7
                            D->getEnumLoc(), D->getLocation(), EnumD);
3181
3182
7
  SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3183
7
  NewUD->setAccess(D->getAccess());
3184
7
  Owner->addDecl(NewUD);
3185
3186
  // Don't process the shadow decls for an invalid decl.
3187
7
  if (NewUD->isInvalidDecl())
3188
0
    return NewUD;
3189
3190
  // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3191
  // cannot be dependent, and will therefore have been checked during template
3192
  // definition.
3193
3194
7
  return VisitBaseUsingDecls(D, NewUD, nullptr);
3195
7
}
3196
3197
320
Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3198
  // Ignore these;  we handle them in bulk when processing the UsingDecl.
3199
320
  return nullptr;
3200
320
}
3201
3202
Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3203
51
    ConstructorUsingShadowDecl *D) {
3204
  // Ignore these;  we handle them in bulk when processing the UsingDecl.
3205
51
  return nullptr;
3206
51
}
3207
3208
template <typename T>
3209
Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3210
1.28k
    T *D, bool InstantiatingPackElement) {
3211
  // If this is a pack expansion, expand it now.
3212
1.28k
  if (D->isPackExpansion() && 
!InstantiatingPackElement165
) {
3213
62
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3214
62
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3215
62
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3216
3217
    // Determine whether the set of unexpanded parameter packs can and should
3218
    // be expanded.
3219
62
    bool Expand = true;
3220
62
    bool RetainExpansion = false;
3221
62
    Optional<unsigned> NumExpansions;
3222
62
    if (SemaRef.CheckParameterPacksForExpansion(
3223
62
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3224
62
            Expand, RetainExpansion, NumExpansions))
3225
0
      return nullptr;
3226
3227
    // This declaration cannot appear within a function template signature,
3228
    // so we can't have a partial argument list for a parameter pack.
3229
62
    assert(!RetainExpansion &&
3230
62
           "should never need to retain an expansion for UsingPackDecl");
3231
3232
62
    if (!Expand) {
3233
      // We cannot fully expand the pack expansion now, so substitute into the
3234
      // pattern and create a new pack expansion.
3235
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3236
0
      return instantiateUnresolvedUsingDecl(D, true);
3237
0
    }
3238
3239
    // Within a function, we don't have any normal way to check for conflicts
3240
    // between shadow declarations from different using declarations in the
3241
    // same pack expansion, but this is always ill-formed because all expansions
3242
    // must produce (conflicting) enumerators.
3243
    //
3244
    // Sadly we can't just reject this in the template definition because it
3245
    // could be valid if the pack is empty or has exactly one expansion.
3246
62
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 16
) {
3247
2
      SemaRef.Diag(D->getEllipsisLoc(),
3248
2
                   diag::err_using_decl_redeclaration_expansion);
3249
2
      return nullptr;
3250
2
    }
3251
3252
    // Instantiate the slices of this pack and build a UsingPackDecl.
3253
60
    SmallVector<NamedDecl*, 8> Expansions;
3254
161
    for (unsigned I = 0; I != *NumExpansions; 
++I101
) {
3255
103
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3256
103
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3257
103
      if (!Slice)
3258
2
        return nullptr;
3259
      // Note that we can still get unresolved using declarations here, if we
3260
      // had arguments for all packs but the pattern also contained other
3261
      // template arguments (this only happens during partial substitution, eg
3262
      // into the body of a generic lambda in a function template).
3263
101
      Expansions.push_back(cast<NamedDecl>(Slice));
3264
101
    }
3265
3266
58
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3267
58
    if (isDeclWithinFunction(D))
3268
16
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3269
58
    return NewD;
3270
60
  }
3271
3272
1.22k
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3273
1.22k
  SourceLocation TypenameLoc = TD ? 
TD->getTypenameLoc()727
:
SourceLocation()500
;
3274
3275
1.22k
  NestedNameSpecifierLoc QualifierLoc
3276
1.22k
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3277
1.22k
                                          TemplateArgs);
3278
1.22k
  if (!QualifierLoc)
3279
7
    return nullptr;
3280
3281
1.22k
  CXXScopeSpec SS;
3282
1.22k
  SS.Adopt(QualifierLoc);
3283
3284
1.22k
  DeclarationNameInfo NameInfo
3285
1.22k
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3286
3287
  // Produce a pack expansion only if we're not instantiating a particular
3288
  // slice of a pack expansion.
3289
1.22k
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3290
1.22k
                            
SemaRef.ArgumentPackSubstitutionIndex != -1103
;
3291
1.22k
  SourceLocation EllipsisLoc =
3292
1.22k
      InstantiatingSlice ? 
SourceLocation()103
:
D->getEllipsisLoc()1.11k
;
3293
3294
1.22k
  bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3295
1.22k
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3296
1.22k
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3297
1.22k
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3298
1.22k
      ParsedAttributesView(),
3299
1.22k
      /*IsInstantiation*/ true, IsUsingIfExists);
3300
1.22k
  if (UD) {
3301
1.19k
    SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3302
1.19k
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3303
1.19k
  }
3304
3305
1.22k
  return UD;
3306
1.22k
}
clang::Decl* clang::TemplateDeclInstantiator::instantiateUnresolvedUsingDecl<clang::UnresolvedUsingTypenameDecl>(clang::UnresolvedUsingTypenameDecl*, bool)
Line
Count
Source
3210
746
    T *D, bool InstantiatingPackElement) {
3211
  // If this is a pack expansion, expand it now.
3212
746
  if (D->isPackExpansion() && 
!InstantiatingPackElement50
) {
3213
19
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3214
19
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3215
19
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3216
3217
    // Determine whether the set of unexpanded parameter packs can and should
3218
    // be expanded.
3219
19
    bool Expand = true;
3220
19
    bool RetainExpansion = false;
3221
19
    Optional<unsigned> NumExpansions;
3222
19
    if (SemaRef.CheckParameterPacksForExpansion(
3223
19
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3224
19
            Expand, RetainExpansion, NumExpansions))
3225
0
      return nullptr;
3226
3227
    // This declaration cannot appear within a function template signature,
3228
    // so we can't have a partial argument list for a parameter pack.
3229
19
    assert(!RetainExpansion &&
3230
19
           "should never need to retain an expansion for UsingPackDecl");
3231
3232
19
    if (!Expand) {
3233
      // We cannot fully expand the pack expansion now, so substitute into the
3234
      // pattern and create a new pack expansion.
3235
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3236
0
      return instantiateUnresolvedUsingDecl(D, true);
3237
0
    }
3238
3239
    // Within a function, we don't have any normal way to check for conflicts
3240
    // between shadow declarations from different using declarations in the
3241
    // same pack expansion, but this is always ill-formed because all expansions
3242
    // must produce (conflicting) enumerators.
3243
    //
3244
    // Sadly we can't just reject this in the template definition because it
3245
    // could be valid if the pack is empty or has exactly one expansion.
3246
19
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 10
) {
3247
0
      SemaRef.Diag(D->getEllipsisLoc(),
3248
0
                   diag::err_using_decl_redeclaration_expansion);
3249
0
      return nullptr;
3250
0
    }
3251
3252
    // Instantiate the slices of this pack and build a UsingPackDecl.
3253
19
    SmallVector<NamedDecl*, 8> Expansions;
3254
50
    for (unsigned I = 0; I != *NumExpansions; 
++I31
) {
3255
31
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3256
31
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3257
31
      if (!Slice)
3258
0
        return nullptr;
3259
      // Note that we can still get unresolved using declarations here, if we
3260
      // had arguments for all packs but the pattern also contained other
3261
      // template arguments (this only happens during partial substitution, eg
3262
      // into the body of a generic lambda in a function template).
3263
31
      Expansions.push_back(cast<NamedDecl>(Slice));
3264
31
    }
3265
3266
19
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3267
19
    if (isDeclWithinFunction(D))
3268
7
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3269
19
    return NewD;
3270
19
  }
3271
3272
727
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3273
727
  SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : 
SourceLocation()0
;
3274
3275
727
  NestedNameSpecifierLoc QualifierLoc
3276
727
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3277
727
                                          TemplateArgs);
3278
727
  if (!QualifierLoc)
3279
0
    return nullptr;
3280
3281
727
  CXXScopeSpec SS;
3282
727
  SS.Adopt(QualifierLoc);
3283
3284
727
  DeclarationNameInfo NameInfo
3285
727
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3286
3287
  // Produce a pack expansion only if we're not instantiating a particular
3288
  // slice of a pack expansion.
3289
727
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3290
727
                            
SemaRef.ArgumentPackSubstitutionIndex != -131
;
3291
727
  SourceLocation EllipsisLoc =
3292
727
      InstantiatingSlice ? 
SourceLocation()31
:
D->getEllipsisLoc()696
;
3293
3294
727
  bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3295
727
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3296
727
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3297
727
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3298
727
      ParsedAttributesView(),
3299
727
      /*IsInstantiation*/ true, IsUsingIfExists);
3300
727
  if (UD) {
3301
727
    SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3302
727
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3303
727
  }
3304
3305
727
  return UD;
3306
727
}
clang::Decl* clang::TemplateDeclInstantiator::instantiateUnresolvedUsingDecl<clang::UnresolvedUsingValueDecl>(clang::UnresolvedUsingValueDecl*, bool)
Line
Count
Source
3210
543
    T *D, bool InstantiatingPackElement) {
3211
  // If this is a pack expansion, expand it now.
3212
543
  if (D->isPackExpansion() && 
!InstantiatingPackElement115
) {
3213
43
    SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3214
43
    SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3215
43
    SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3216
3217
    // Determine whether the set of unexpanded parameter packs can and should
3218
    // be expanded.
3219
43
    bool Expand = true;
3220
43
    bool RetainExpansion = false;
3221
43
    Optional<unsigned> NumExpansions;
3222
43
    if (SemaRef.CheckParameterPacksForExpansion(
3223
43
          D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3224
43
            Expand, RetainExpansion, NumExpansions))
3225
0
      return nullptr;
3226
3227
    // This declaration cannot appear within a function template signature,
3228
    // so we can't have a partial argument list for a parameter pack.
3229
43
    assert(!RetainExpansion &&
3230
43
           "should never need to retain an expansion for UsingPackDecl");
3231
3232
43
    if (!Expand) {
3233
      // We cannot fully expand the pack expansion now, so substitute into the
3234
      // pattern and create a new pack expansion.
3235
0
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3236
0
      return instantiateUnresolvedUsingDecl(D, true);
3237
0
    }
3238
3239
    // Within a function, we don't have any normal way to check for conflicts
3240
    // between shadow declarations from different using declarations in the
3241
    // same pack expansion, but this is always ill-formed because all expansions
3242
    // must produce (conflicting) enumerators.
3243
    //
3244
    // Sadly we can't just reject this in the template definition because it
3245
    // could be valid if the pack is empty or has exactly one expansion.
3246
43
    if (D->getDeclContext()->isFunctionOrMethod() && 
*NumExpansions > 16
) {
3247
2
      SemaRef.Diag(D->getEllipsisLoc(),
3248
2
                   diag::err_using_decl_redeclaration_expansion);
3249
2
      return nullptr;
3250
2
    }
3251
3252
    // Instantiate the slices of this pack and build a UsingPackDecl.
3253
41
    SmallVector<NamedDecl*, 8> Expansions;
3254
111
    for (unsigned I = 0; I != *NumExpansions; 
++I70
) {
3255
72
      Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3256
72
      Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3257
72
      if (!Slice)
3258
2
        return nullptr;
3259
      // Note that we can still get unresolved using declarations here, if we
3260
      // had arguments for all packs but the pattern also contained other
3261
      // template arguments (this only happens during partial substitution, eg
3262
      // into the body of a generic lambda in a function template).
3263
70
      Expansions.push_back(cast<NamedDecl>(Slice));
3264
70
    }
3265
3266
39
    auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3267
39
    if (isDeclWithinFunction(D))
3268
9
      SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3269
39
    return NewD;
3270
41
  }
3271
3272
500
  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3273
500
  SourceLocation TypenameLoc = TD ? 
TD->getTypenameLoc()0
: SourceLocation();
3274
3275
500
  NestedNameSpecifierLoc QualifierLoc
3276
500
    = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3277
500
                                          TemplateArgs);
3278
500
  if (!QualifierLoc)
3279
7
    return nullptr;
3280
3281
493
  CXXScopeSpec SS;
3282
493
  SS.Adopt(QualifierLoc);
3283
3284
493
  DeclarationNameInfo NameInfo
3285
493
    = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3286
3287
  // Produce a pack expansion only if we're not instantiating a particular
3288
  // slice of a pack expansion.
3289
493
  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3290
493
                            
SemaRef.ArgumentPackSubstitutionIndex != -172
;
3291
493
  SourceLocation EllipsisLoc =
3292
493
      InstantiatingSlice ? 
SourceLocation()72
:
D->getEllipsisLoc()421
;
3293
3294
493
  bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3295
493
  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3296
493
      /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3297
493
      /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3298
493
      ParsedAttributesView(),
3299
493
      /*IsInstantiation*/ true, IsUsingIfExists);
3300
493
  if (UD) {
3301
466
    SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3302
466
    SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3303
466
  }
3304
3305
493
  return UD;
3306
500
}
3307
3308
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3309
715
    UnresolvedUsingTypenameDecl *D) {
3310
715
  return instantiateUnresolvedUsingDecl(D);
3311
715
}
3312
3313
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3314
471
    UnresolvedUsingValueDecl *D) {
3315
471
  return instantiateUnresolvedUsingDecl(D);
3316
471
}
3317
3318
Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3319
0
    UnresolvedUsingIfExistsDecl *D) {
3320
0
  llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3321
0
}
3322
3323
8
Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3324
8
  SmallVector<NamedDecl*, 8> Expansions;
3325
10
  for (auto *UD : D->expansions()) {
3326
10
    if (NamedDecl *NewUD =
3327
10
            SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3328
10
      Expansions.push_back(NewUD);
3329
0
    else
3330
0
      return nullptr;
3331
10
  }
3332
3333
8
  auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3334
8
  if (isDeclWithinFunction(D))
3335
8
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3336
8
  return NewD;
3337
8
}
3338
3339
Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
3340
92
    ClassScopeFunctionSpecializationDecl *Decl) {
3341
92
  CXXMethodDecl *OldFD = Decl->getSpecialization();
3342
92
  return cast_or_null<CXXMethodDecl>(
3343
92
      VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
3344
92
}
3345
3346
Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3347
234
                                     OMPThreadPrivateDecl *D) {
3348
234
  SmallVector<Expr *, 5> Vars;
3349
258
  for (auto *I : D->varlists()) {
3350
258
    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3351
258
    assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3352
0
    Vars.push_back(Var);
3353
258
  }
3354
3355
234
  OMPThreadPrivateDecl *TD =
3356
234
    SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3357
3358
234
  TD->setAccess(AS_public);
3359
234
  Owner->addDecl(TD);
3360
3361
234
  return TD;
3362
234
}
3363
3364
82
Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3365
82
  SmallVector<Expr *, 5> Vars;
3366
82
  for (auto *I : D->varlists()) {
3367
82
    Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3368
82
    assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3369
0
    Vars.push_back(Var);
3370
82
  }
3371
82
  SmallVector<OMPClause *, 4> Clauses;
3372
  // Copy map clauses from the original mapper.
3373
82
  for (OMPClause *C : D->clauselists()) {
3374
69
    OMPClause *IC = nullptr;
3375
69
    if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3376
61
      ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3377
61
      if (!NewE.isUsable())
3378
0
        continue;
3379
61
      IC = SemaRef.ActOnOpenMPAllocatorClause(
3380
61
          NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3381
61
    } else 
if (auto *8
AC8
= dyn_cast<OMPAlignClause>(C)) {
3382
8
      ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3383
8
      if (!NewE.isUsable())
3384
0
        continue;
3385
8
      IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(),
3386
8
                                          AC->getLParenLoc(), AC->getEndLoc());
3387
      // If align clause value ends up being invalid, this can end up null.
3388
8
      if (!IC)
3389
1
        continue;
3390
8
    }
3391
68
    Clauses.push_back(IC);
3392
68
  }
3393
3394
82
  Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3395
82
      D->getLocation(), Vars, Clauses, Owner);
3396
82
  if (Res.get().isNull())
3397
0
    return nullptr;
3398
82
  return Res.get().getSingleDecl();
3399
82
}
3400
3401
0
Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3402
0
  llvm_unreachable(
3403
0
      "Requires directive cannot be instantiated within a dependent context");
3404
0
}
3405
3406
Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3407
156
    OMPDeclareReductionDecl *D) {
3408
  // Instantiate type and check if it is allowed.
3409
156
  const bool RequiresInstantiation =
3410
156
      D->getType()->isDependentType() ||
3411
156
      
D->getType()->isInstantiationDependentType()26
||
3412
156
      
D->getType()->containsUnexpandedParameterPack()26
;
3413
156
  QualType SubstReductionType;
3414
156
  if (RequiresInstantiation) {
3415
130
    SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3416
130
        D->getLocation(),
3417
130
        ParsedType::make(SemaRef.SubstType(
3418
130
            D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3419
130
  } else {
3420
26
    SubstReductionType = D->getType();
3421
26
  }
3422
156
  if (SubstReductionType.isNull())
3423
12
    return nullptr;
3424
144
  Expr *Combiner = D->getCombiner();
3425
144
  Expr *Init = D->getInitializer();
3426
144
  bool IsCorrect = true;
3427
  // Create instantiated copy.
3428
144
  std::pair<QualType, SourceLocation> ReductionTypes[] = {
3429
144
      std::make_pair(SubstReductionType, D->getLocation())};
3430
144
  auto *PrevDeclInScope = D->getPrevDeclInScope();
3431
144
  if (PrevDeclInScope && 
!PrevDeclInScope->isInvalidDecl()20
) {
3432
20
    PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3433
20
        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3434
20
            ->get<Decl *>());
3435
20
  }
3436
144
  auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3437
144
      /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3438
144
      PrevDeclInScope);
3439
144
  auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3440
144
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3441
144
  Expr *SubstCombiner = nullptr;
3442
144
  Expr *SubstInitializer = nullptr;
3443
  // Combiners instantiation sequence.
3444
144
  if (Combiner) {
3445
144
    SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3446
144
        /*S=*/nullptr, NewDRD);
3447
144
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3448
144
        cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3449
144
        cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3450
144
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3451
144
        cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3452
144
        cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3453
144
    auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3454
144
    Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3455
144
                                     ThisContext);
3456
144
    SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3457
144
    SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3458
144
  }
3459
  // Initializers instantiation sequence.
3460
144
  if (Init) {
3461
52
    VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3462
52
        /*S=*/nullptr, NewDRD);
3463
52
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3464
52
        cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3465
52
        cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3466
52
    SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3467
52
        cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3468
52
        cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3469
52
    if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3470
4
      SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3471
48
    } else {
3472
48
      auto *OldPrivParm =
3473
48
          cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3474
48
      IsCorrect = IsCorrect && OldPrivParm->hasInit();
3475
48
      if (IsCorrect)
3476
48
        SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3477
48
                                               TemplateArgs);
3478
48
    }
3479
52
    SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3480
52
                                                      OmpPrivParm);
3481
52
  }
3482
144
  IsCorrect = IsCorrect && SubstCombiner &&
3483
144
              
(142
!Init142
||
3484
142
               
(52
D->getInitializerKind() == OMPDeclareReductionDecl::CallInit52
&&
3485
52
                
SubstInitializer4
) ||
3486
142
               
(48
D->getInitializerKind() != OMPDeclareReductionDecl::CallInit48
&&
3487
48
                !SubstInitializer));
3488
3489
144
  (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3490
144
      /*S=*/nullptr, DRD, IsCorrect && 
!D->isInvalidDecl()142
);
3491
3492
144
  return NewDRD;
3493
156
}
3494
3495
Decl *
3496
30
TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3497
  // Instantiate type and check if it is allowed.
3498
30
  const bool RequiresInstantiation =
3499
30
      D->getType()->isDependentType() ||
3500
30
      
D->getType()->isInstantiationDependentType()18
||
3501
30
      
D->getType()->containsUnexpandedParameterPack()18
;
3502
30
  QualType SubstMapperTy;
3503
30
  DeclarationName VN = D->getVarName();
3504
30
  if (RequiresInstantiation) {
3505
12
    SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3506
12
        D->getLocation(),
3507
12
        ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3508
12
                                           D->getLocation(), VN)));
3509
18
  } else {
3510
18
    SubstMapperTy = D->getType();
3511
18
  }
3512
30
  if (SubstMapperTy.isNull())
3513
0
    return nullptr;
3514
  // Create an instantiated copy of mapper.
3515
30
  auto *PrevDeclInScope = D->getPrevDeclInScope();
3516
30
  if (PrevDeclInScope && 
!PrevDeclInScope->isInvalidDecl()4
) {
3517
4
    PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3518
4
        SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3519
4
            ->get<Decl *>());
3520
4
  }
3521
30
  bool IsCorrect = true;
3522
30
  SmallVector<OMPClause *, 6> Clauses;
3523
  // Instantiate the mapper variable.
3524
30
  DeclarationNameInfo DirName;
3525
30
  SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3526
30
                              /*S=*/nullptr,
3527
30
                              (*D->clauselist_begin())->getBeginLoc());
3528
30
  ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3529
30
      /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3530
30
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3531
30
      cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3532
30
      cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3533
30
  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3534
30
  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3535
30
                                   ThisContext);
3536
  // Instantiate map clauses.
3537
30
  for (OMPClause *C : D->clauselists()) {
3538
30
    auto *OldC = cast<OMPMapClause>(C);
3539
30
    SmallVector<Expr *, 4> NewVars;
3540
30
    for (Expr *OE : OldC->varlists()) {
3541
30
      Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3542
30
      if (!NE) {
3543
0
        IsCorrect = false;
3544
0
        break;
3545
0
      }
3546
30
      NewVars.push_back(NE);
3547
30
    }
3548
30
    if (!IsCorrect)
3549
0
      break;
3550
30
    NestedNameSpecifierLoc NewQualifierLoc =
3551
30
        SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3552
30
                                            TemplateArgs);
3553
30
    CXXScopeSpec SS;
3554
30
    SS.Adopt(NewQualifierLoc);
3555
30
    DeclarationNameInfo NewNameInfo =
3556
30
        SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3557
30
    OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3558
30
                         OldC->getEndLoc());
3559
30
    OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3560
30
        OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3561
30
        NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3562
30
        OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3563
30
    Clauses.push_back(NewC);
3564
30
  }
3565
30
  SemaRef.EndOpenMPDSABlock(nullptr);
3566
30
  if (!IsCorrect)
3567
0
    return nullptr;
3568
30
  Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3569
30
      /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3570
30
      VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3571
30
  Decl *NewDMD = DG.get().getSingleDecl();
3572
30
  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3573
30
  return NewDMD;
3574
30
}
3575
3576
Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3577
0
    OMPCapturedExprDecl * /*D*/) {
3578
0
  llvm_unreachable("Should not be met in templates");
3579
0
}
3580
3581
269k
Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3582
269k
  return VisitFunctionDecl(D, nullptr);
3583
269k
}
3584
3585
Decl *
3586
486
TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3587
486
  Decl *Inst = VisitFunctionDecl(D, nullptr);
3588
486
  if (Inst && 
!D->getDescribedFunctionTemplate()473
)
3589
1
    Owner->addDecl(Inst);
3590
486
  return Inst;
3591
486
}
3592
3593
875k
Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3594
875k
  return VisitCXXMethodDecl(D, nullptr);
3595
875k
}
3596
3597
0
Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3598
0
  llvm_unreachable("There are only CXXRecordDecls in C++");
3599
0
}
3600
3601
Decl *
3602
TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3603
39
    ClassTemplateSpecializationDecl *D) {
3604
  // As a MS extension, we permit class-scope explicit specialization
3605
  // of member class templates.
3606
39
  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3607
39
  assert(ClassTemplate->getDeclContext()->isRecord() &&
3608
39
         D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3609
39
         "can only instantiate an explicit specialization "
3610
39
         "for a member class template");
3611
3612
  // Lookup the already-instantiated declaration in the instantiation
3613
  // of the class template.
3614
0
  ClassTemplateDecl *InstClassTemplate =
3615
39
      cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3616
39
          D->getLocation(), ClassTemplate, TemplateArgs));
3617
39
  if (!InstClassTemplate)
3618
0
    return nullptr;
3619
3620
  // Substitute into the template arguments of the class template explicit
3621
  // specialization.
3622
39
  TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3623
39
                                        castAs<TemplateSpecializationTypeLoc>();
3624
39
  TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3625
39
                                            Loc.getRAngleLoc());
3626
39
  SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3627
77
  for (unsigned I = 0; I != Loc.getNumArgs(); 
++I38
)
3628
38
    ArgLocs.push_back(Loc.getArgLoc(I));
3629
39
  if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs))
3630
0
    return nullptr;
3631
3632
  // Check that the template argument list is well-formed for this
3633
  // class template.
3634
39
  SmallVector<TemplateArgument, 4> Converted;
3635
39
  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
3636
39
                                        D->getLocation(),
3637
39
                                        InstTemplateArgs,
3638
39
                                        false,
3639
39
                                        Converted,
3640
39
                                        /*UpdateArgsWithConversions=*/true))
3641
0
    return nullptr;
3642
3643
  // Figure out where to insert this class template explicit specialization
3644
  // in the member template's set of class template explicit specializations.
3645
39
  void *InsertPos = nullptr;
3646
39
  ClassTemplateSpecializationDecl *PrevDecl =
3647
39
      InstClassTemplate->findSpecialization(Converted, InsertPos);
3648
3649
  // Check whether we've already seen a conflicting instantiation of this
3650
  // declaration (for instance, if there was a prior implicit instantiation).
3651
39
  bool Ignored;
3652
39
  if (PrevDecl &&
3653
39
      SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3654
14
                                                     D->getSpecializationKind(),
3655
14
                                                     PrevDecl,
3656
14
                                                     PrevDecl->getSpecializationKind(),
3657
14
                                                     PrevDecl->getPointOfInstantiation(),
3658
14
                                                     Ignored))
3659
2
    return nullptr;
3660
3661
  // If PrevDecl was a definition and D is also a definition, diagnose.
3662
  // This happens in cases like:
3663
  //
3664
  //   template<typename T, typename U>
3665
  //   struct Outer {
3666
  //     template<typename X> struct Inner;
3667
  //     template<> struct Inner<T> {};
3668
  //     template<> struct Inner<U> {};
3669
  //   };
3670
  //
3671
  //   Outer<int, int> outer; // error: the explicit specializations of Inner
3672
  //                          // have the same signature.
3673
37
  if (PrevDecl && 
PrevDecl->getDefinition()12
&&
3674
37
      
D->isThisDeclarationADefinition()7
) {
3675
7
    SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3676
7
    SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3677
7
                 diag::note_previous_definition);
3678
7
    return nullptr;
3679
7
  }
3680
3681
  // Create the class template partial specialization declaration.
3682
30
  ClassTemplateSpecializationDecl *InstD =
3683
30
      ClassTemplateSpecializationDecl::Create(
3684
30
          SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3685
30
          D->getLocation(), InstClassTemplate, Converted, PrevDecl);
3686
3687
  // Add this partial specialization to the set of class template partial
3688
  // specializations.
3689
30
  if (!PrevDecl)
3690
25
    InstClassTemplate->AddSpecialization(InstD, InsertPos);
3691
3692
  // Substitute the nested name specifier, if any.
3693
30
  if (SubstQualifier(D, InstD))
3694
0
    return nullptr;
3695
3696
  // Build the canonical type that describes the converted template
3697
  // arguments of the class template explicit specialization.
3698
30
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3699
30
      TemplateName(InstClassTemplate), Converted,
3700
30
      SemaRef.Context.getRecordType(InstD));
3701
3702
  // Build the fully-sugared type for this class template
3703
  // specialization as the user wrote in the specialization
3704
  // itself. This means that we'll pretty-print the type retrieved
3705
  // from the specialization's declaration the way that the user
3706
  // actually wrote the specialization, rather than formatting the
3707
  // name based on the "canonical" representation used to store the
3708
  // template arguments in the specialization.
3709
30
  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3710
30
      TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3711
30
      CanonType);
3712
3713
30
  InstD->setAccess(D->getAccess());
3714
30
  InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3715
30
  InstD->setSpecializationKind(D->getSpecializationKind());
3716
30
  InstD->setTypeAsWritten(WrittenTy);
3717
30
  InstD->setExternLoc(D->getExternLoc());
3718
30
  InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3719
3720
30
  Owner->addDecl(InstD);
3721
3722
  // Instantiate the members of the class-scope explicit specialization eagerly.
3723
  // We don't have support for lazy instantiation of an explicit specialization
3724
  // yet, and MSVC eagerly instantiates in this case.
3725
  // FIXME: This is wrong in standard C++.
3726
30
  if (D->isThisDeclarationADefinition() &&
3727
30
      SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3728
18
                               TSK_ImplicitInstantiation,
3729
18
                               /*Complain=*/true))
3730
0
    return nullptr;
3731
3732
30
  return InstD;
3733
30
}
3734
3735
Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3736
57
    VarTemplateSpecializationDecl *D) {
3737
3738
57
  TemplateArgumentListInfo VarTemplateArgsInfo;
3739
57
  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3740
57
  assert(VarTemplate &&
3741
57
         "A template specialization without specialized template?");
3742
3743
0
  VarTemplateDecl *InstVarTemplate =
3744
57
      cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3745
57
          D->getLocation(), VarTemplate, TemplateArgs));
3746
57
  if (!InstVarTemplate)
3747
0
    return nullptr;
3748
3749
  // Substitute the current template arguments.
3750
57
  const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
3751
57
  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
3752
57
  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
3753
3754
57
  if (SemaRef.SubstTemplateArguments(TemplateArgsInfo.arguments(), TemplateArgs,
3755
57
                                     VarTemplateArgsInfo))
3756
0
    return nullptr;
3757
3758
  // Check that the template argument list is well-formed for this template.
3759
57
  SmallVector<TemplateArgument, 4> Converted;
3760
57
  if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3761
57
                                        VarTemplateArgsInfo, false, Converted,
3762
57
                                        /*UpdateArgsWithConversions=*/true))
3763
0
    return nullptr;
3764
3765
  // Check whether we've already seen a declaration of this specialization.
3766
57
  void *InsertPos = nullptr;
3767
57
  VarTemplateSpecializationDecl *PrevDecl =
3768
57
      InstVarTemplate->findSpecialization(Converted, InsertPos);
3769
3770
  // Check whether we've already seen a conflicting instantiation of this
3771
  // declaration (for instance, if there was a prior implicit instantiation).
3772
57
  bool Ignored;
3773
57
  if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3774
10
                      D->getLocation(), D->getSpecializationKind(), PrevDecl,
3775
10
                      PrevDecl->getSpecializationKind(),
3776
10
                      PrevDecl->getPointOfInstantiation(), Ignored))
3777
0
    return nullptr;
3778
3779
57
  return VisitVarTemplateSpecializationDecl(
3780
57
      InstVarTemplate, D, VarTemplateArgsInfo, Converted, PrevDecl);
3781
57
}
3782
3783
Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3784
    VarTemplateDecl *VarTemplate, VarDecl *D,
3785
    const TemplateArgumentListInfo &TemplateArgsInfo,
3786
    ArrayRef<TemplateArgument> Converted,
3787
2.51k
    VarTemplateSpecializationDecl *PrevDecl) {
3788
3789
  // Do substitution on the type of the declaration
3790
2.51k
  TypeSourceInfo *DI =
3791
2.51k
      SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3792
2.51k
                        D->getTypeSpecStartLoc(), D->getDeclName());
3793
2.51k
  if (!DI)
3794
0
    return nullptr;
3795
3796
2.51k
  if (DI->getType()->isFunctionType()) {
3797
0
    SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3798
0
        << D->isStaticDataMember() << DI->getType();
3799
0
    return nullptr;
3800
0
  }
3801
3802
  // Build the instantiated declaration
3803
2.51k
  VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3804
2.51k
      SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3805
2.51k
      VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3806
2.51k
  Var->setTemplateArgsInfo(TemplateArgsInfo);
3807
2.51k
  if (!PrevDecl) {
3808
2.36k
    void *InsertPos = nullptr;
3809
2.36k
    VarTemplate->findSpecialization(Converted, InsertPos);
3810
2.36k
    VarTemplate->AddSpecialization(Var, InsertPos);
3811
2.36k
  }
3812
3813
2.51k
  if (SemaRef.getLangOpts().OpenCL)
3814
2
    SemaRef.deduceOpenCLAddressSpace(Var);
3815
3816
  // Substitute the nested name specifier, if any.
3817
2.51k
  if (SubstQualifier(D, Var))
3818
0
    return nullptr;
3819
3820
2.51k
  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3821
2.51k
                                     StartingScope, false, PrevDecl);
3822
3823
2.51k
  return Var;
3824
2.51k
}
3825
3826
0
Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3827
0
  llvm_unreachable("@defs is not supported in Objective-C++");
3828
0
}
3829
3830
0
Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3831
  // FIXME: We need to be able to instantiate FriendTemplateDecls.
3832
0
  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3833
0
                                               DiagnosticsEngine::Error,
3834
0
                                               "cannot instantiate %0 yet");
3835
0
  SemaRef.Diag(D->getLocation(), DiagID)
3836
0
    << D->getDeclKindName();
3837
3838
0
  return nullptr;
3839
0
}
3840
3841
0
Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3842
0
  llvm_unreachable("Concept definitions cannot reside inside a template");
3843
0
}
3844
3845
Decl *
3846
0
TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
3847
0
  return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
3848
0
                                      D->getBeginLoc());
3849
0
}
3850
3851
0
Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3852
0
  llvm_unreachable("Unexpected decl");
3853
0
}
3854
3855
Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3856
608k
                      const MultiLevelTemplateArgumentList &TemplateArgs) {
3857
608k
  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3858
608k
  if (D->isInvalidDecl())
3859
21
    return nullptr;
3860
3861
608k
  Decl *SubstD;
3862
608k
  runWithSufficientStackSpace(D->getLocation(), [&] {
3863
608k
    SubstD = Instantiator.Visit(D);
3864
608k
  });
3865
608k
  return SubstD;
3866
608k
}
3867
3868
void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
3869
                                                FunctionDecl *Orig, QualType &T,
3870
                                                TypeSourceInfo *&TInfo,
3871
117
                                                DeclarationNameInfo &NameInfo) {
3872
117
  assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual);
3873
3874
  // C++2a [class.compare.default]p3:
3875
  //   the return type is replaced with bool
3876
0
  auto *FPT = T->castAs<FunctionProtoType>();
3877
117
  T = SemaRef.Context.getFunctionType(
3878
117
      SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
3879
3880
  // Update the return type in the source info too. The most straightforward
3881
  // way is to create new TypeSourceInfo for the new type. Use the location of
3882
  // the '= default' as the location of the new type.
3883
  //
3884
  // FIXME: Set the correct return type when we initially transform the type,
3885
  // rather than delaying it to now.
3886
117
  TypeSourceInfo *NewTInfo =
3887
117
      SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
3888
117
  auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
3889
117
  assert(OldLoc && "type of function is not a function type?");
3890
0
  auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
3891
264
  for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; 
++I147
)
3892
147
    NewLoc.setParam(I, OldLoc.getParam(I));
3893
117
  TInfo = NewTInfo;
3894
3895
  //   and the declarator-id is replaced with operator==
3896
117
  NameInfo.setName(
3897
117
      SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
3898
117
}
3899
3900
FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
3901
117
                                               FunctionDecl *Spaceship) {
3902
117
  if (Spaceship->isInvalidDecl())
3903
0
    return nullptr;
3904
3905
  // C++2a [class.compare.default]p3:
3906
  //   an == operator function is declared implicitly [...] with the same
3907
  //   access and function-definition and in the same class scope as the
3908
  //   three-way comparison operator function
3909
117
  MultiLevelTemplateArgumentList NoTemplateArgs;
3910
117
  NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
3911
117
  NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
3912
117
  TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
3913
117
  Decl *R;
3914
117
  if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
3915
87
    R = Instantiator.VisitCXXMethodDecl(
3916
87
        MD, nullptr, None,
3917
87
        TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3918
87
  } else {
3919
30
    assert(Spaceship->getFriendObjectKind() &&
3920
30
           "defaulted spaceship is neither a member nor a friend");
3921
3922
0
    R = Instantiator.VisitFunctionDecl(
3923
30
        Spaceship, nullptr,
3924
30
        TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
3925
30
    if (!R)
3926
0
      return nullptr;
3927
3928
30
    FriendDecl *FD =
3929
30
        FriendDecl::Create(Context, RD, Spaceship->getLocation(),
3930
30
                           cast<NamedDecl>(R), Spaceship->getBeginLoc());
3931
30
    FD->setAccess(AS_public);
3932
30
    RD->addDecl(FD);
3933
30
  }
3934
117
  return cast_or_null<FunctionDecl>(R);
3935
117
}
3936
3937
/// Instantiates a nested template parameter list in the current
3938
/// instantiation context.
3939
///
3940
/// \param L The parameter list to instantiate
3941
///
3942
/// \returns NULL if there was an error
3943
TemplateParameterList *
3944
313k
TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3945
  // Get errors for all the parameters before bailing out.
3946
313k
  bool Invalid = false;
3947
3948
313k
  unsigned N = L->size();
3949
313k
  typedef SmallVector<NamedDecl *, 8> ParamVector;
3950
313k
  ParamVector Params;
3951
313k
  Params.reserve(N);
3952
539k
  for (auto &P : *L) {
3953
539k
    NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3954
539k
    Params.push_back(D);
3955
539k
    Invalid = Invalid || !D || 
D->isInvalidDecl()539k
;
3956
539k
  }
3957
3958
  // Clean up if we had an error.
3959
313k
  if (Invalid)
3960
16
    return nullptr;
3961
3962
  // FIXME: Concepts: Substitution into requires clause should only happen when
3963
  // checking satisfaction.
3964
313k
  Expr *InstRequiresClause = nullptr;
3965
313k
  if (Expr *E = L->getRequiresClause()) {
3966
12
    EnterExpressionEvaluationContext ConstantEvaluated(
3967
12
        SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
3968
12
    ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs);
3969
12
    if (Res.isInvalid() || !Res.isUsable()) {
3970
0
      return nullptr;
3971
0
    }
3972
12
    InstRequiresClause = Res.get();
3973
12
  }
3974
3975
313k
  TemplateParameterList *InstL
3976
313k
    = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3977
313k
                                    L->getLAngleLoc(), Params,
3978
313k
                                    L->getRAngleLoc(), InstRequiresClause);
3979
313k
  return InstL;
3980
313k
}
3981
3982
TemplateParameterList *
3983
Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
3984
43.5k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
3985
43.5k
  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3986
43.5k
  return Instantiator.SubstTemplateParams(Params);
3987
43.5k
}
3988
3989
/// Instantiate the declaration of a class template partial
3990
/// specialization.
3991
///
3992
/// \param ClassTemplate the (instantiated) class template that is partially
3993
// specialized by the instantiation of \p PartialSpec.
3994
///
3995
/// \param PartialSpec the (uninstantiated) class template partial
3996
/// specialization that we are instantiating.
3997
///
3998
/// \returns The instantiated partial specialization, if successful; otherwise,
3999
/// NULL to indicate an error.
4000
ClassTemplatePartialSpecializationDecl *
4001
TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4002
                                            ClassTemplateDecl *ClassTemplate,
4003
5.55k
                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
4004
  // Create a local instantiation scope for this class template partial
4005
  // specialization, which will contain the instantiations of the template
4006
  // parameters.
4007
5.55k
  LocalInstantiationScope Scope(SemaRef);
4008
4009
  // Substitute into the template parameters of the class template partial
4010
  // specialization.
4011
5.55k
  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4012
5.55k
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4013
5.55k
  if (!InstParams)
4014
0
    return nullptr;
4015
4016
  // Substitute into the template arguments of the class template partial
4017
  // specialization.
4018
5.55k
  const ASTTemplateArgumentListInfo *TemplArgInfo
4019
5.55k
    = PartialSpec->getTemplateArgsAsWritten();
4020
5.55k
  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4021
5.55k
                                            TemplArgInfo->RAngleLoc);
4022
5.55k
  if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4023
5.55k
                                     InstTemplateArgs))
4024
0
    return nullptr;
4025
4026
  // Check that the template argument list is well-formed for this
4027
  // class template.
4028
5.55k
  SmallVector<TemplateArgument, 4> Converted;
4029
5.55k
  if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
4030
5.55k
                                        PartialSpec->getLocation(),
4031
5.55k
                                        InstTemplateArgs,
4032
5.55k
                                        false,
4033
5.55k
                                        Converted))
4034
0
    return nullptr;
4035
4036
  // Check these arguments are valid for a template partial specialization.
4037
5.55k
  if (SemaRef.CheckTemplatePartialSpecializationArgs(
4038
5.55k
          PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4039
5.55k
          Converted))
4040
5
    return nullptr;
4041
4042
  // Figure out where to insert this class template partial specialization
4043
  // in the member template's set of class template partial specializations.
4044
5.55k
  void *InsertPos = nullptr;
4045
5.55k
  ClassTemplateSpecializationDecl *PrevDecl
4046
5.55k
    = ClassTemplate->findPartialSpecialization(Converted, InstParams,
4047
5.55k
                                               InsertPos);
4048
4049
  // Build the canonical type that describes the converted template
4050
  // arguments of the class template partial specialization.
4051
5.55k
  QualType CanonType
4052
5.55k
    = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
4053
5.55k
                                                    Converted);
4054
4055
  // Build the fully-sugared type for this class template
4056
  // specialization as the user wrote in the specialization
4057
  // itself. This means that we'll pretty-print the type retrieved
4058
  // from the specialization's declaration the way that the user
4059
  // actually wrote the specialization, rather than formatting the
4060
  // name based on the "canonical" representation used to store the
4061
  // template arguments in the specialization.
4062
5.55k
  TypeSourceInfo *WrittenTy
4063
5.55k
    = SemaRef.Context.getTemplateSpecializationTypeInfo(
4064
5.55k
                                                    TemplateName(ClassTemplate),
4065
5.55k
                                                    PartialSpec->getLocation(),
4066
5.55k
                                                    InstTemplateArgs,
4067
5.55k
                                                    CanonType);
4068
4069
5.55k
  if (PrevDecl) {
4070
    // We've already seen a partial specialization with the same template
4071
    // parameters and template arguments. This can happen, for example, when
4072
    // substituting the outer template arguments ends up causing two
4073
    // class template partial specializations of a member class template
4074
    // to have identical forms, e.g.,
4075
    //
4076
    //   template<typename T, typename U>
4077
    //   struct Outer {
4078
    //     template<typename X, typename Y> struct Inner;
4079
    //     template<typename Y> struct Inner<T, Y>;
4080
    //     template<typename Y> struct Inner<U, Y>;
4081
    //   };
4082
    //
4083
    //   Outer<int, int> outer; // error: the partial specializations of Inner
4084
    //                          // have the same signature.
4085
1
    SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
4086
1
      << WrittenTy->getType();
4087
1
    SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4088
1
      << SemaRef.Context.getTypeDeclType(PrevDecl);
4089
1
    return nullptr;
4090
1
  }
4091
4092
4093
  // Create the class template partial specialization declaration.
4094
5.55k
  ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4095
5.55k
      ClassTemplatePartialSpecializationDecl::Create(
4096
5.55k
          SemaRef.Context, PartialSpec->getTagKind(), Owner,
4097
5.55k
          PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4098
5.55k
          ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr);
4099
  // Substitute the nested name specifier, if any.
4100
5.55k
  if (SubstQualifier(PartialSpec, InstPartialSpec))
4101
0
    return nullptr;
4102
4103
5.55k
  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4104
5.55k
  InstPartialSpec->setTypeAsWritten(WrittenTy);
4105
4106
  // Check the completed partial specialization.
4107
5.55k
  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4108
4109
  // Add this partial specialization to the set of class template partial
4110
  // specializations.
4111
5.55k
  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4112
5.55k
                                          /*InsertPos=*/nullptr);
4113
5.55k
  return InstPartialSpec;
4114
5.55k
}
4115
4116
/// Instantiate the declaration of a variable template partial
4117
/// specialization.
4118
///
4119
/// \param VarTemplate the (instantiated) variable template that is partially
4120
/// specialized by the instantiation of \p PartialSpec.
4121
///
4122
/// \param PartialSpec the (uninstantiated) variable template partial
4123
/// specialization that we are instantiating.
4124
///
4125
/// \returns The instantiated partial specialization, if successful; otherwise,
4126
/// NULL to indicate an error.
4127
VarTemplatePartialSpecializationDecl *
4128
TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4129
    VarTemplateDecl *VarTemplate,
4130
50
    VarTemplatePartialSpecializationDecl *PartialSpec) {
4131
  // Create a local instantiation scope for this variable template partial
4132
  // specialization, which will contain the instantiations of the template
4133
  // parameters.
4134
50
  LocalInstantiationScope Scope(SemaRef);
4135
4136
  // Substitute into the template parameters of the variable template partial
4137
  // specialization.
4138
50
  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4139
50
  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4140
50
  if (!InstParams)
4141
0
    return nullptr;
4142
4143
  // Substitute into the template arguments of the variable template partial
4144
  // specialization.
4145
50
  const ASTTemplateArgumentListInfo *TemplArgInfo
4146
50
    = PartialSpec->getTemplateArgsAsWritten();
4147
50
  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4148
50
                                            TemplArgInfo->RAngleLoc);
4149
50
  if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4150
50
                                     InstTemplateArgs))
4151
0
    return nullptr;
4152
4153
  // Check that the template argument list is well-formed for this
4154
  // class template.
4155
50
  SmallVector<TemplateArgument, 4> Converted;
4156
50
  if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
4157
50
                                        InstTemplateArgs, false, Converted))
4158
1
    return nullptr;
4159
4160
  // Check these arguments are valid for a template partial specialization.
4161
49
  if (SemaRef.CheckTemplatePartialSpecializationArgs(
4162
49
          PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4163
49
          Converted))
4164
0
    return nullptr;
4165
4166
  // Figure out where to insert this variable template partial specialization
4167
  // in the member template's set of variable template partial specializations.
4168
49
  void *InsertPos = nullptr;
4169
49
  VarTemplateSpecializationDecl *PrevDecl =
4170
49
      VarTemplate->findPartialSpecialization(Converted, InstParams, InsertPos);
4171
4172
  // Build the canonical type that describes the converted template
4173
  // arguments of the variable template partial specialization.
4174
49
  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4175
49
      TemplateName(VarTemplate), Converted);
4176
4177
  // Build the fully-sugared type for this variable template
4178
  // specialization as the user wrote in the specialization
4179
  // itself. This means that we'll pretty-print the type retrieved
4180
  // from the specialization's declaration the way that the user
4181
  // actually wrote the specialization, rather than formatting the
4182
  // name based on the "canonical" representation used to store the
4183
  // template arguments in the specialization.
4184
49
  TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
4185
49
      TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4186
49
      CanonType);
4187
4188
49
  if (PrevDecl) {
4189
    // We've already seen a partial specialization with the same template
4190
    // parameters and template arguments. This can happen, for example, when
4191
    // substituting the outer template arguments ends up causing two
4192
    // variable template partial specializations of a member variable template
4193
    // to have identical forms, e.g.,
4194
    //
4195
    //   template<typename T, typename U>
4196
    //   struct Outer {
4197
    //     template<typename X, typename Y> pair<X,Y> p;
4198
    //     template<typename Y> pair<T, Y> p;
4199
    //     template<typename Y> pair<U, Y> p;
4200
    //   };
4201
    //
4202
    //   Outer<int, int> outer; // error: the partial specializations of Inner
4203
    //                          // have the same signature.
4204
0
    SemaRef.Diag(PartialSpec->getLocation(),
4205
0
                 diag::err_var_partial_spec_redeclared)
4206
0
        << WrittenTy->getType();
4207
0
    SemaRef.Diag(PrevDecl->getLocation(),
4208
0
                 diag::note_var_prev_partial_spec_here);
4209
0
    return nullptr;
4210
0
  }
4211
4212
  // Do substitution on the type of the declaration
4213
49
  TypeSourceInfo *DI = SemaRef.SubstType(
4214
49
      PartialSpec->getTypeSourceInfo(), TemplateArgs,
4215
49
      PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4216
49
  if (!DI)
4217
0
    return nullptr;
4218
4219
49
  if (DI->getType()->isFunctionType()) {
4220
0
    SemaRef.Diag(PartialSpec->getLocation(),
4221
0
                 diag::err_variable_instantiates_to_function)
4222
0
        << PartialSpec->isStaticDataMember() << DI->getType();
4223
0
    return nullptr;
4224
0
  }
4225
4226
  // Create the variable template partial specialization declaration.
4227
49
  VarTemplatePartialSpecializationDecl *InstPartialSpec =
4228
49
      VarTemplatePartialSpecializationDecl::Create(
4229
49
          SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4230
49
          PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4231
49
          DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
4232
4233
  // Substitute the nested name specifier, if any.
4234
49
  if (SubstQualifier(PartialSpec, InstPartialSpec))
4235
0
    return nullptr;
4236
4237
49
  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4238
49
  InstPartialSpec->setTypeAsWritten(WrittenTy);
4239
4240
  // Check the completed partial specialization.
4241
49
  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4242
4243
  // Add this partial specialization to the set of variable template partial
4244
  // specializations. The instantiation of the initializer is not necessary.
4245
49
  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4246
4247
49
  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4248
49
                                     LateAttrs, Owner, StartingScope);
4249
4250
49
  return InstPartialSpec;
4251
49
}
4252
4253
TypeSourceInfo*
4254
TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4255
1.16M
                              SmallVectorImpl<ParmVarDecl *> &Params) {
4256
1.16M
  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4257
1.16M
  assert(OldTInfo && "substituting function without type source info");
4258
0
  assert(Params.empty() && "parameter vector is non-empty at start");
4259
4260
0
  CXXRecordDecl *ThisContext = nullptr;
4261
1.16M
  Qualifiers ThisTypeQuals;
4262
1.16M
  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4263
1.00M
    ThisContext = cast<CXXRecordDecl>(Owner);
4264
1.00M
    ThisTypeQuals = Method->getMethodQualifiers();
4265
1.00M
  }
4266
4267
1.16M
  TypeSourceInfo *NewTInfo
4268
1.16M
    = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
4269
1.16M
                                    D->getTypeSpecStartLoc(),
4270
1.16M
                                    D->getDeclName(),
4271
1.16M
                                    ThisContext, ThisTypeQuals);
4272
1.16M
  if (!NewTInfo)
4273
49.0k
    return nullptr;
4274
4275
1.11M
  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4276
1.11M
  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4277
1.11M
    if (NewTInfo != OldTInfo) {
4278
      // Get parameters from the new type info.
4279
975k
      TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4280
975k
      FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4281
975k
      unsigned NewIdx = 0;
4282
975k
      for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4283
2.28M
           OldIdx != NumOldParams; 
++OldIdx1.31M
) {
4284
1.31M
        ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4285
1.31M
        if (!OldParam)
4286
1
          return nullptr;
4287
4288
1.31M
        LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4289
4290
1.31M
        Optional<unsigned> NumArgumentsInExpansion;
4291
1.31M
        if (OldParam->isParameterPack())
4292
23.6k
          NumArgumentsInExpansion =
4293
23.6k
              SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4294
23.6k
                                                 TemplateArgs);
4295
1.31M
        if (!NumArgumentsInExpansion) {
4296
          // Simple case: normal parameter, or a parameter pack that's
4297
          // instantiated to a (still-dependent) parameter pack.
4298
1.30M
          ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4299
1.30M
          Params.push_back(NewParam);
4300
1.30M
          Scope->InstantiatedLocal(OldParam, NewParam);
4301
1.30M
        } else {
4302
          // Parameter pack expansion: make the instantiation an argument pack.
4303
9.19k
          Scope->MakeInstantiatedLocalArgPack(OldParam);
4304
22.5k
          for (unsigned I = 0; I != *NumArgumentsInExpansion; 
++I13.3k
) {
4305
13.3k
            ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4306
13.3k
            Params.push_back(NewParam);
4307
13.3k
            Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4308
13.3k
          }
4309
9.19k
        }
4310
1.31M
      }
4311
975k
    } else {
4312
      // The function type itself was not dependent and therefore no
4313
      // substitution occurred. However, we still need to instantiate
4314
      // the function parameters themselves.
4315
142k
      const FunctionProtoType *OldProto =
4316
142k
          cast<FunctionProtoType>(OldProtoLoc.getType());
4317
142k
      for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4318
142k
           
++i19
) {
4319
19
        ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4320
19
        if (!OldParam) {
4321
19
          Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4322
19
              D, D->getLocation(), OldProto->getParamType(i)));
4323
19
          continue;
4324
19
        }
4325
4326
0
        ParmVarDecl *Parm =
4327
0
            cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4328
0
        if (!Parm)
4329
0
          return nullptr;
4330
0
        Params.push_back(Parm);
4331
0
      }
4332
142k
    }
4333
1.11M
  } else {
4334
    // If the type of this function, after ignoring parentheses, is not
4335
    // *directly* a function type, then we're instantiating a function that
4336
    // was declared via a typedef or with attributes, e.g.,
4337
    //
4338
    //   typedef int functype(int, int);
4339
    //   functype func;
4340
    //   int __cdecl meth(int, int);
4341
    //
4342
    // In this case, we'll just go instantiate the ParmVarDecls that we
4343
    // synthesized in the method declaration.
4344
88
    SmallVector<QualType, 4> ParamTypes;
4345
88
    Sema::ExtParameterInfoBuilder ExtParamInfos;
4346
88
    if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4347
88
                               TemplateArgs, ParamTypes, &Params,
4348
88
                               ExtParamInfos))
4349
0
      return nullptr;
4350
88
  }
4351
4352
1.11M
  return NewTInfo;
4353
1.11M
}
4354
4355
/// Introduce the instantiated function parameters into the local
4356
/// instantiation scope, and set the parameter names to those used
4357
/// in the template.
4358
static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
4359
                                             const FunctionDecl *PatternDecl,
4360
                                             LocalInstantiationScope &Scope,
4361
199k
                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4362
199k
  unsigned FParamIdx = 0;
4363
413k
  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; 
++I214k
) {
4364
214k
    const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4365
214k
    if (!PatternParam->isParameterPack()) {
4366
      // Simple case: not a parameter pack.
4367
206k
      assert(FParamIdx < Function->getNumParams());
4368
0
      ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4369
206k
      FunctionParam->setDeclName(PatternParam->getDeclName());
4370
      // If the parameter's type is not dependent, update it to match the type
4371
      // in the pattern. They can differ in top-level cv-qualifiers, and we want
4372
      // the pattern's type here. If the type is dependent, they can't differ,
4373
      // per core issue 1668. Substitute into the type from the pattern, in case
4374
      // it's instantiation-dependent.
4375
      // FIXME: Updating the type to work around this is at best fragile.
4376
206k
      if (!PatternDecl->getType()->isDependentType()) {
4377
6.18k
        QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
4378
6.18k
                                 FunctionParam->getLocation(),
4379
6.18k
                                 FunctionParam->getDeclName());
4380
6.18k
        if (T.isNull())
4381
0
          return true;
4382
6.18k
        FunctionParam->setType(T);
4383
6.18k
      }
4384
4385
206k
      Scope.InstantiatedLocal(PatternParam, FunctionParam);
4386
206k
      ++FParamIdx;
4387
206k
      continue;
4388
206k
    }
4389
4390
    // Expand the parameter pack.
4391
7.20k
    Scope.MakeInstantiatedLocalArgPack(PatternParam);
4392
7.20k
    Optional<unsigned> NumArgumentsInExpansion
4393
7.20k
      = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4394
7.20k
    if (NumArgumentsInExpansion) {
4395
7.20k
      QualType PatternType =
4396
7.20k
          PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4397
17.5k
      for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; 
++Arg10.3k
) {
4398
10.3k
        ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4399
10.3k
        FunctionParam->setDeclName(PatternParam->getDeclName());
4400
10.3k
        if (!PatternDecl->getType()->isDependentType()) {
4401
0
          Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
4402
0
          QualType T = S.SubstType(PatternType, TemplateArgs,
4403
0
                                   FunctionParam->getLocation(),
4404
0
                                   FunctionParam->getDeclName());
4405
0
          if (T.isNull())
4406
0
            return true;
4407
0
          FunctionParam->setType(T);
4408
0
        }
4409
4410
10.3k
        Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4411
10.3k
        ++FParamIdx;
4412
10.3k
      }
4413
7.20k
    }
4414
7.20k
  }
4415
4416
199k
  return false;
4417
199k
}
4418
4419
bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4420
8.18k
                                      ParmVarDecl *Param) {
4421
8.18k
  assert(Param->hasUninstantiatedDefaultArg());
4422
0
  Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4423
4424
8.18k
  EnterExpressionEvaluationContext EvalContext(
4425
8.18k
      *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4426
4427
  // Instantiate the expression.
4428
  //
4429
  // FIXME: Pass in a correct Pattern argument, otherwise
4430
  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4431
  //
4432
  // template<typename T>
4433
  // struct A {
4434
  //   static int FooImpl();
4435
  //
4436
  //   template<typename Tp>
4437
  //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4438
  //   // template argument list [[T], [Tp]], should be [[Tp]].
4439
  //   friend A<Tp> Foo(int a);
4440
  // };
4441
  //
4442
  // template<typename T>
4443
  // A<T> Foo(int a = A<T>::FooImpl());
4444
8.18k
  MultiLevelTemplateArgumentList TemplateArgs
4445
8.18k
    = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4446
4447
8.18k
  InstantiatingTemplate Inst(*this, CallLoc, Param,
4448
8.18k
                             TemplateArgs.getInnermost());
4449
8.18k
  if (Inst.isInvalid())
4450
1
    return true;
4451
8.18k
  if (Inst.isAlreadyInstantiating()) {
4452
1
    Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4453
1
    Param->setInvalidDecl();
4454
1
    return true;
4455
1
  }
4456
4457
8.18k
  ExprResult Result;
4458
8.18k
  {
4459
    // C++ [dcl.fct.default]p5:
4460
    //   The names in the [default argument] expression are bound, and
4461
    //   the semantic constraints are checked, at the point where the
4462
    //   default argument expression appears.
4463
8.18k
    ContextRAII SavedContext(*this, FD);
4464
8.18k
    LocalInstantiationScope Local(*this);
4465
4466
8.18k
    FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(
4467
8.18k
        /*ForDefinition*/ false);
4468
8.18k
    if (addInstantiatedParametersToScope(*this, FD, Pattern, Local,
4469
8.18k
                                         TemplateArgs))
4470
0
      return true;
4471
4472
8.18k
    runWithSufficientStackSpace(CallLoc, [&] {
4473
8.18k
      Result = SubstInitializer(UninstExpr, TemplateArgs,
4474
8.18k
                                /*DirectInit*/false);
4475
8.18k
    });
4476
8.18k
  }
4477
8.18k
  if (Result.isInvalid())
4478
156
    return true;
4479
4480
  // Check the expression as an initializer for the parameter.
4481
8.02k
  InitializedEntity Entity
4482
8.02k
    = InitializedEntity::InitializeParameter(Context, Param);
4483
8.02k
  InitializationKind Kind = InitializationKind::CreateCopy(
4484
8.02k
      Param->getLocation(),
4485
8.02k
      /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4486
8.02k
  Expr *ResultE = Result.getAs<Expr>();
4487
4488
8.02k
  InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4489
8.02k
  Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4490
8.02k
  if (Result.isInvalid())
4491
25
    return true;
4492
4493
8.00k
  Result =
4494
8.00k
      ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4495
8.00k
                          /*DiscardedValue*/ false);
4496
8.00k
  if (Result.isInvalid())
4497
0
    return true;
4498
4499
  // Remember the instantiated default argument.
4500
8.00k
  Param->setDefaultArg(Result.getAs<Expr>());
4501
8.00k
  if (ASTMutationListener *L = getASTMutationListener())
4502
429
    L->DefaultArgumentInstantiated(Param);
4503
4504
8.00k
  return false;
4505
8.00k
}
4506
4507
void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4508
6.09k
                                    FunctionDecl *Decl) {
4509
6.09k
  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4510
6.09k
  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4511
0
    return;
4512
4513
6.09k
  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4514
6.09k
                             InstantiatingTemplate::ExceptionSpecification());
4515
6.09k
  if (Inst.isInvalid()) {
4516
    // We hit the instantiation depth limit. Clear the exception specification
4517
    // so that our callers don't have to cope with EST_Uninstantiated.
4518
0
    UpdateExceptionSpec(Decl, EST_None);
4519
0
    return;
4520
0
  }
4521
6.09k
  if (Inst.isAlreadyInstantiating()) {
4522
    // This exception specification indirectly depends on itself. Reject.
4523
    // FIXME: Corresponding rule in the standard?
4524
10
    Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4525
10
    UpdateExceptionSpec(Decl, EST_None);
4526
10
    return;
4527
10
  }
4528
4529
  // Enter the scope of this instantiation. We don't use
4530
  // PushDeclContext because we don't have a scope.
4531
6.08k
  Sema::ContextRAII savedContext(*this, Decl);
4532
6.08k
  LocalInstantiationScope Scope(*this);
4533
4534
6.08k
  MultiLevelTemplateArgumentList TemplateArgs =
4535
6.08k
    getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
4536
4537
  // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4538
  // here, because for a non-defining friend declaration in a class template,
4539
  // we don't store enough information to map back to the friend declaration in
4540
  // the template.
4541
6.08k
  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4542
6.08k
  if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
4543
6.08k
                                       TemplateArgs)) {
4544
0
    UpdateExceptionSpec(Decl, EST_None);
4545
0
    return;
4546
0
  }
4547
4548
6.08k
  SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4549
6.08k
                     TemplateArgs);
4550
6.08k
}
4551
4552
bool Sema::CheckInstantiatedFunctionTemplateConstraints(
4553
    SourceLocation PointOfInstantiation, FunctionDecl *Decl,
4554
    ArrayRef<TemplateArgument> TemplateArgs,
4555
401k
    ConstraintSatisfaction &Satisfaction) {
4556
  // In most cases we're not going to have constraints, so check for that first.
4557
401k
  FunctionTemplateDecl *Template = Decl->getPrimaryTemplate();
4558
  // Note - code synthesis context for the constraints check is created
4559
  // inside CheckConstraintsSatisfaction.
4560
401k
  SmallVector<const Expr *, 3> TemplateAC;
4561
401k
  Template->getAssociatedConstraints(TemplateAC);
4562
401k
  if (TemplateAC.empty()) {
4563
401k
    Satisfaction.IsSatisfied = true;
4564
401k
    return false;
4565
401k
  }
4566
4567
  // Enter the scope of this instantiation. We don't use
4568
  // PushDeclContext because we don't have a scope.
4569
240
  Sema::ContextRAII savedContext(*this, Decl);
4570
240
  LocalInstantiationScope Scope(*this);
4571
4572
  // If this is not an explicit specialization - we need to get the instantiated
4573
  // version of the template arguments and add them to scope for the
4574
  // substitution.
4575
240
  if (Decl->isTemplateInstantiation()) {
4576
240
    InstantiatingTemplate Inst(*this, Decl->getPointOfInstantiation(),
4577
240
        InstantiatingTemplate::ConstraintsCheck{}, Decl->getPrimaryTemplate(),
4578
240
        TemplateArgs, SourceRange());
4579
240
    if (Inst.isInvalid())
4580
0
      return true;
4581
240
    MultiLevelTemplateArgumentList MLTAL(
4582
240
        *Decl->getTemplateSpecializationArgs());
4583
240
    if (addInstantiatedParametersToScope(
4584
240
            *this, Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(),
4585
240
            Scope, MLTAL))
4586
0
      return true;
4587
240
  }
4588
240
  Qualifiers ThisQuals;
4589
240
  CXXRecordDecl *Record = nullptr;
4590
240
  if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) {
4591
59
    ThisQuals = Method->getMethodQualifiers();
4592
59
    Record = Method->getParent();
4593
59
  }
4594
240
  CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr);
4595
240
  return CheckConstraintSatisfaction(Template, TemplateAC, TemplateArgs,
4596
240
                                     PointOfInstantiation, Satisfaction);
4597
240
}
4598
4599
/// Initializes the common fields of an instantiation function
4600
/// declaration (New) from the corresponding fields of its template (Tmpl).
4601
///
4602
/// \returns true if there was an error
4603
bool
4604
TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4605
1.11M
                                                    FunctionDecl *Tmpl) {
4606
1.11M
  New->setImplicit(Tmpl->isImplicit());
4607
4608
  // Forward the mangling number from the template to the instantiated decl.
4609
1.11M
  SemaRef.Context.setManglingNumber(New,
4610
1.11M
                                    SemaRef.Context.getManglingNumber(Tmpl));
4611
4612
  // If we are performing substituting explicitly-specified template arguments
4613
  // or deduced template arguments into a function template and we reach this
4614
  // point, we are now past the point where SFINAE applies and have committed
4615
  // to keeping the new function template specialization. We therefore
4616
  // convert the active template instantiation for the function template
4617
  // into a template instantiation for this specific function template
4618
  // specialization, which is not a SFINAE context, so that we diagnose any
4619
  // further errors in the declaration itself.
4620
  //
4621
  // FIXME: This is a hack.
4622
1.11M
  typedef Sema::CodeSynthesisContext ActiveInstType;
4623
1.11M
  ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4624
1.11M
  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4625
1.11M
      
ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution1.11M
) {
4626
224k
    if (FunctionTemplateDecl *FunTmpl
4627
224k
          = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
4628
224k
      assert(FunTmpl->getTemplatedDecl() == Tmpl &&
4629
224k
             "Deduction from the wrong function template?");
4630
0
      (void) FunTmpl;
4631
224k
      SemaRef.InstantiatingSpecializations.erase(
4632
224k
          {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4633
224k
      atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4634
224k
      ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4635
224k
      ActiveInst.Entity = New;
4636
224k
      atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4637
224k
    }
4638
224k
  }
4639
4640
0
  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4641
1.11M
  assert(Proto && "Function template without prototype?");
4642
4643
1.11M
  if (Proto->hasExceptionSpec() || 
Proto->getNoReturnAttr()666k
) {
4644
452k
    FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4645
4646
    // DR1330: In C++11, defer instantiation of a non-trivial
4647
    // exception specification.
4648
    // DR1484: Local classes and their members are instantiated along with the
4649
    // containing function.
4650
452k
    if (SemaRef.getLangOpts().CPlusPlus11 &&
4651
452k
        
EPI.ExceptionSpec.Type != EST_None452k
&&
4652
452k
        
EPI.ExceptionSpec.Type != EST_DynamicNone452k
&&
4653
452k
        
EPI.ExceptionSpec.Type != EST_BasicNoexcept452k
&&
4654
452k
        
!Tmpl->isInLocalScopeForInstantiation()48.5k
) {
4655
48.5k
      FunctionDecl *ExceptionSpecTemplate = Tmpl;
4656
48.5k
      if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4657
3.80k
        ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4658
48.5k
      ExceptionSpecificationType NewEST = EST_Uninstantiated;
4659
48.5k
      if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4660
10
        NewEST = EST_Unevaluated;
4661
4662
      // Mark the function has having an uninstantiated exception specification.
4663
48.5k
      const FunctionProtoType *NewProto
4664
48.5k
        = New->getType()->getAs<FunctionProtoType>();
4665
48.5k
      assert(NewProto && "Template instantiation without function prototype?");
4666
0
      EPI = NewProto->getExtProtoInfo();
4667
48.5k
      EPI.ExceptionSpec.Type = NewEST;
4668
48.5k
      EPI.ExceptionSpec.SourceDecl = New;
4669
48.5k
      EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4670
48.5k
      New->setType(SemaRef.Context.getFunctionType(
4671
48.5k
          NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4672
403k
    } else {
4673
403k
      Sema::ContextRAII SwitchContext(SemaRef, New);
4674
403k
      SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4675
403k
    }
4676
452k
  }
4677
4678
  // Get the definition. Leaves the variable unchanged if undefined.
4679
0
  const FunctionDecl *Definition = Tmpl;
4680
1.11M
  Tmpl->isDefined(Definition);
4681
4682
1.11M
  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4683
1.11M
                           LateAttrs, StartingScope);
4684
4685
1.11M
  return false;
4686
1.11M
}
4687
4688
/// Initializes common fields of an instantiated method
4689
/// declaration (New) from the corresponding fields of its template
4690
/// (Tmpl).
4691
///
4692
/// \returns true if there was an error
4693
bool
4694
TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4695
977k
                                                  CXXMethodDecl *Tmpl) {
4696
977k
  if (InitFunctionInstantiation(New, Tmpl))
4697
0
    return true;
4698
4699
977k
  if (isa<CXXDestructorDecl>(New) && 
SemaRef.getLangOpts().CPlusPlus1112.9k
)
4700
12.8k
    SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4701
4702
977k
  New->setAccess(Tmpl->getAccess());
4703
977k
  if (Tmpl->isVirtualAsWritten())
4704
18.5k
    New->setVirtualAsWritten(true);
4705
4706
  // FIXME: New needs a pointer to Tmpl
4707
977k
  return false;
4708
977k
}
4709
4710
bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4711
16.7k
                                                      FunctionDecl *Tmpl) {
4712
  // Transfer across any unqualified lookups.
4713
16.7k
  if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4714
131
    SmallVector<DeclAccessPair, 32> Lookups;
4715
131
    Lookups.reserve(DFI->getUnqualifiedLookups().size());
4716
131
    bool AnyChanged = false;
4717
131
    for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4718
18
      NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4719
18
                                                  DA.getDecl(), TemplateArgs);
4720
18
      if (!D)
4721
0
        return true;
4722
18
      AnyChanged |= (D != DA.getDecl());
4723
18
      Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4724
18
    }
4725
4726
    // It's unlikely that substitution will change any declarations. Don't
4727
    // store an unnecessary copy in that case.
4728
131
    New->setDefaultedFunctionInfo(
4729
131
        AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4730
8
                         SemaRef.Context, Lookups)
4731
131
                   : 
DFI123
);
4732
131
  }
4733
4734
16.7k
  SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4735
16.7k
  return false;
4736
16.7k
}
4737
4738
/// Instantiate (or find existing instantiation of) a function template with a
4739
/// given set of template arguments.
4740
///
4741
/// Usually this should not be used, and template argument deduction should be
4742
/// used in its place.
4743
FunctionDecl *
4744
Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4745
                                     const TemplateArgumentList *Args,
4746
1.45k
                                     SourceLocation Loc) {
4747
1.45k
  FunctionDecl *FD = FTD->getTemplatedDecl();
4748