Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaCXXScopeSpec.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaCXXScopeSpec.cpp - Semantic Analysis for C++ scope specifiers-===//
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
//
9
// This file implements C++ semantic analysis for scope specifiers.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "TypeLocBuilder.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/DeclTemplate.h"
16
#include "clang/AST/ExprCXX.h"
17
#include "clang/AST/NestedNameSpecifier.h"
18
#include "clang/Basic/PartialDiagnostic.h"
19
#include "clang/Sema/DeclSpec.h"
20
#include "clang/Sema/Lookup.h"
21
#include "clang/Sema/SemaInternal.h"
22
#include "clang/Sema/Template.h"
23
#include "llvm/ADT/STLExtras.h"
24
using namespace clang;
25
26
/// Find the current instantiation that associated with the given type.
27
static CXXRecordDecl *getCurrentInstantiationOf(QualType T,
28
6.93M
                                                DeclContext *CurContext) {
29
6.93M
  if (T.isNull())
30
0
    return nullptr;
31
6.93M
32
6.93M
  const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
33
6.93M
  if (const RecordType *RecordTy = dyn_cast<RecordType>(Ty)) {
34
50.4k
    CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordTy->getDecl());
35
50.4k
    if (!Record->isDependentContext() ||
36
50.4k
        Record->isCurrentInstantiation(CurContext))
37
30.1k
      return Record;
38
20.2k
39
20.2k
    return nullptr;
40
6.88M
  } else if (isa<InjectedClassNameType>(Ty))
41
2.16M
    return cast<InjectedClassNameType>(Ty)->getDecl();
42
4.72M
  else
43
4.72M
    return nullptr;
44
6.93M
}
45
46
/// Compute the DeclContext that is associated with the given type.
47
///
48
/// \param T the type for which we are attempting to find a DeclContext.
49
///
50
/// \returns the declaration context represented by the type T,
51
/// or NULL if the declaration context cannot be computed (e.g., because it is
52
/// dependent and not the current instantiation).
53
2.15M
DeclContext *Sema::computeDeclContext(QualType T) {
54
2.15M
  if (!T->isDependentType())
55
803k
    if (const TagType *Tag = T->getAs<TagType>())
56
803k
      return Tag->getDecl();
57
1.35M
58
1.35M
  return ::getCurrentInstantiationOf(T, CurContext);
59
1.35M
}
60
61
/// Compute the DeclContext that is associated with the given
62
/// scope specifier.
63
///
64
/// \param SS the C++ scope specifier as it appears in the source
65
///
66
/// \param EnteringContext when true, we will be entering the context of
67
/// this scope specifier, so we can retrieve the declaration context of a
68
/// class template or class template partial specialization even if it is
69
/// not the current instantiation.
70
///
71
/// \returns the declaration context represented by the scope specifier @p SS,
72
/// or NULL if the declaration context cannot be computed (e.g., because it is
73
/// dependent and not the current instantiation).
74
DeclContext *Sema::computeDeclContext(const CXXScopeSpec &SS,
75
12.7M
                                      bool EnteringContext) {
76
12.7M
  if (!SS.isSet() || 
SS.isInvalid()12.7M
)
77
601
    return nullptr;
78
12.7M
79
12.7M
  NestedNameSpecifier *NNS = SS.getScopeRep();
80
12.7M
  if (NNS->isDependent()) {
81
5.62M
    // If this nested-name-specifier refers to the current
82
5.62M
    // instantiation, return its DeclContext.
83
5.62M
    if (CXXRecordDecl *Record = getCurrentInstantiationOf(NNS))
84
848k
      return Record;
85
4.77M
86
4.77M
    if (EnteringContext) {
87
337k
      const Type *NNSType = NNS->getAsType();
88
337k
      if (!NNSType) {
89
48
        return nullptr;
90
48
      }
91
337k
92
337k
      // Look through type alias templates, per C++0x [temp.dep.type]p1.
93
337k
      NNSType = Context.getCanonicalType(NNSType);
94
337k
      if (const TemplateSpecializationType *SpecType
95
330k
            = NNSType->getAs<TemplateSpecializationType>()) {
96
330k
        // We are entering the context of the nested name specifier, so try to
97
330k
        // match the nested name specifier to either a primary class template
98
330k
        // or a class template partial specialization.
99
330k
        if (ClassTemplateDecl *ClassTemplate
100
330k
              = dyn_cast_or_null<ClassTemplateDecl>(
101
330k
                            SpecType->getTemplateName().getAsTemplateDecl())) {
102
330k
          QualType ContextType
103
330k
            = Context.getCanonicalType(QualType(SpecType, 0));
104
330k
105
330k
          // If the type of the nested name specifier is the same as the
106
330k
          // injected class name of the named class template, we're entering
107
330k
          // into that class template definition.
108
330k
          QualType Injected
109
330k
            = ClassTemplate->getInjectedClassNameSpecialization();
110
330k
          if (Context.hasSameType(Injected, ContextType))
111
244k
            return ClassTemplate->getTemplatedDecl();
112
85.8k
113
85.8k
          // If the type of the nested name specifier is the same as the
114
85.8k
          // type of one of the class template's class template partial
115
85.8k
          // specializations, we're entering into the definition of that
116
85.8k
          // class template partial specialization.
117
85.8k
          if (ClassTemplatePartialSpecializationDecl *PartialSpec
118
84.3k
                = ClassTemplate->findPartialSpecialization(ContextType)) {
119
84.3k
            // A declaration of the partial specialization must be visible.
120
84.3k
            // We can always recover here, because this only happens when we're
121
84.3k
            // entering the context, and that can't happen in a SFINAE context.
122
84.3k
            assert(!isSFINAEContext() &&
123
84.3k
                   "partial specialization scope specifier in SFINAE context?");
124
84.3k
            if (!hasVisibleDeclaration(PartialSpec))
125
30
              diagnoseMissingImport(SS.getLastQualifierNameLoc(), PartialSpec,
126
30
                                    MissingImportKind::PartialSpecialization,
127
30
                                    /*Recover*/true);
128
84.3k
            return PartialSpec;
129
84.3k
          }
130
7.21k
        }
131
7.21k
      } else if (const RecordType *RecordT = NNSType->getAs<RecordType>()) {
132
6.87k
        // The nested name specifier refers to a member of a class template.
133
6.87k
        return RecordT->getDecl();
134
6.87k
      }
135
4.44M
    }
136
4.44M
137
4.44M
    return nullptr;
138
4.44M
  }
139
7.13M
140
7.13M
  switch (NNS->getKind()) {
141
7.13M
  case NestedNameSpecifier::Identifier:
142
0
    llvm_unreachable("Dependent nested-name-specifier has no DeclContext");
143
7.13M
144
7.13M
  case NestedNameSpecifier::Namespace:
145
2.97M
    return NNS->getAsNamespace();
146
7.13M
147
7.13M
  case NestedNameSpecifier::NamespaceAlias:
148
513
    return NNS->getAsNamespaceAlias()->getNamespace();
149
7.13M
150
7.13M
  case NestedNameSpecifier::TypeSpec:
151
3.28M
  case NestedNameSpecifier::TypeSpecWithTemplate: {
152
3.28M
    const TagType *Tag = NNS->getAsType()->getAs<TagType>();
153
3.28M
    assert(Tag && "Non-tag type in nested-name-specifier");
154
3.28M
    return Tag->getDecl();
155
3.28M
  }
156
3.28M
157
3.28M
  case NestedNameSpecifier::Global:
158
873k
    return Context.getTranslationUnitDecl();
159
3.28M
160
3.28M
  case NestedNameSpecifier::Super:
161
70
    return NNS->getAsRecordDecl();
162
0
  }
163
0
164
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
165
0
}
166
167
3.20M
bool Sema::isDependentScopeSpecifier(const CXXScopeSpec &SS) {
168
3.20M
  if (!SS.isSet() || 
SS.isInvalid()2.35M
)
169
849k
    return false;
170
2.35M
171
2.35M
  return SS.getScopeRep()->isDependent();
172
2.35M
}
173
174
/// If the given nested name specifier refers to the current
175
/// instantiation, return the declaration that corresponds to that
176
/// current instantiation (C++0x [temp.dep.type]p1).
177
///
178
/// \param NNS a dependent nested name specifier.
179
5.62M
CXXRecordDecl *Sema::getCurrentInstantiationOf(NestedNameSpecifier *NNS) {
180
5.62M
  assert(getLangOpts().CPlusPlus && "Only callable in C++");
181
5.62M
  assert(NNS->isDependent() && "Only dependent nested-name-specifier allowed");
182
5.62M
183
5.62M
  if (!NNS->getAsType())
184
42.8k
    return nullptr;
185
5.58M
186
5.58M
  QualType T = QualType(NNS->getAsType(), 0);
187
5.58M
  return ::getCurrentInstantiationOf(T, CurContext);
188
5.58M
}
189
190
/// Require that the context specified by SS be complete.
191
///
192
/// If SS refers to a type, this routine checks whether the type is
193
/// complete enough (or can be made complete enough) for name lookup
194
/// into the DeclContext. A type that is not yet completed can be
195
/// considered "complete enough" if it is a class/struct/union/enum
196
/// that is currently being defined. Or, if we have a type that names
197
/// a class template specialization that is not a complete type, we
198
/// will attempt to instantiate that class template.
199
bool Sema::RequireCompleteDeclContext(CXXScopeSpec &SS,
200
6.58M
                                      DeclContext *DC) {
201
6.58M
  assert(DC && "given null context");
202
6.58M
203
6.58M
  TagDecl *tag = dyn_cast<TagDecl>(DC);
204
6.58M
205
6.58M
  // If this is a dependent type, then we consider it complete.
206
6.58M
  // FIXME: This is wrong; we should require a (visible) definition to
207
6.58M
  // exist in this case too.
208
6.58M
  if (!tag || 
tag->isDependentContext()3.18M
)
209
3.48M
    return false;
210
3.09M
211
3.09M
  // Grab the tag definition, if there is one.
212
3.09M
  QualType type = Context.getTypeDeclType(tag);
213
3.09M
  tag = type->getAsTagDecl();
214
3.09M
215
3.09M
  // If we're currently defining this type, then lookup into the
216
3.09M
  // type is okay: don't complain that it isn't complete yet.
217
3.09M
  if (tag->isBeingDefined())
218
2.03k
    return false;
219
3.09M
220
3.09M
  SourceLocation loc = SS.getLastQualifierNameLoc();
221
3.09M
  if (loc.isInvalid()) 
loc = SS.getRange().getBegin()799
;
222
3.09M
223
3.09M
  // The type must be complete.
224
3.09M
  if (RequireCompleteType(loc, type, diag::err_incomplete_nested_name_spec,
225
3.09M
                          SS.getRange())) {
226
662
    SS.SetInvalid(SS.getRange());
227
662
    return true;
228
662
  }
229
3.09M
230
3.09M
  // Fixed enum types are complete, but they aren't valid as scopes
231
3.09M
  // until we see a definition, so awkwardly pull out this special
232
3.09M
  // case.
233
3.09M
  auto *EnumD = dyn_cast<EnumDecl>(tag);
234
3.09M
  if (!EnumD)
235
3.06M
    return false;
236
28.2k
  if (EnumD->isCompleteDefinition()) {
237
28.2k
    // If we know about the definition but it is not visible, complain.
238
28.2k
    NamedDecl *SuggestedDef = nullptr;
239
28.2k
    if (!hasVisibleDefinition(EnumD, &SuggestedDef,
240
28.2k
                              /*OnlyNeedComplete*/false)) {
241
25
      // If the user is going to see an error here, recover by making the
242
25
      // definition visible.
243
25
      bool TreatAsComplete = !isSFINAEContext();
244
25
      diagnoseMissingImport(loc, SuggestedDef, MissingImportKind::Definition,
245
25
                            /*Recover*/TreatAsComplete);
246
25
      return !TreatAsComplete;
247
25
    }
248
28.2k
    return false;
249
28.2k
  }
250
22
251
22
  // Try to instantiate the definition, if this is a specialization of an
252
22
  // enumeration temploid.
253
22
  if (EnumDecl *Pattern = EnumD->getInstantiatedFromMemberEnum()) {
254
17
    MemberSpecializationInfo *MSI = EnumD->getMemberSpecializationInfo();
255
17
    if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
256
16
      if (InstantiateEnum(loc, EnumD, Pattern,
257
16
                          getTemplateInstantiationArgs(EnumD),
258
16
                          TSK_ImplicitInstantiation)) {
259
3
        SS.SetInvalid(SS.getRange());
260
3
        return true;
261
3
      }
262
13
      return false;
263
13
    }
264
17
  }
265
6
266
6
  Diag(loc, diag::err_incomplete_nested_name_spec)
267
6
    << type << SS.getRange();
268
6
  SS.SetInvalid(SS.getRange());
269
6
  return true;
270
6
}
271
272
bool Sema::ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc,
273
246k
                                        CXXScopeSpec &SS) {
274
246k
  SS.MakeGlobal(Context, CCLoc);
275
246k
  return false;
276
246k
}
277
278
bool Sema::ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
279
                                    SourceLocation ColonColonLoc,
280
42
                                    CXXScopeSpec &SS) {
281
42
  CXXRecordDecl *RD = nullptr;
282
45
  for (Scope *S = getCurScope(); S; 
S = S->getParent()3
) {
283
45
    if (S->isFunctionScope()) {
284
27
      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(S->getEntity()))
285
27
        RD = MD->getParent();
286
27
      break;
287
27
    }
288
18
    if (S->isClassScope()) {
289
15
      RD = cast<CXXRecordDecl>(S->getEntity());
290
15
      break;
291
15
    }
292
18
  }
293
42
294
42
  if (!RD) {
295
0
    Diag(SuperLoc, diag::err_invalid_super_scope);
296
0
    return true;
297
42
  } else if (RD->isLambda()) {
298
1
    Diag(SuperLoc, diag::err_super_in_lambda_unsupported);
299
1
    return true;
300
41
  } else if (RD->getNumBases() == 0) {
301
1
    Diag(SuperLoc, diag::err_no_base_classes) << RD->getName();
302
1
    return true;
303
1
  }
304
40
305
40
  SS.MakeSuper(Context, RD, SuperLoc, ColonColonLoc);
306
40
  return false;
307
40
}
308
309
/// Determines whether the given declaration is an valid acceptable
310
/// result for name lookup of a nested-name-specifier.
311
/// \param SD Declaration checked for nested-name-specifier.
312
/// \param IsExtension If not null and the declaration is accepted as an
313
/// extension, the pointed variable is assigned true.
314
bool Sema::isAcceptableNestedNameSpecifier(const NamedDecl *SD,
315
2.38M
                                           bool *IsExtension) {
316
2.38M
  if (!SD)
317
555
    return false;
318
2.37M
319
2.37M
  SD = SD->getUnderlyingDecl();
320
2.37M
321
2.37M
  // Namespace and namespace aliases are fine.
322
2.37M
  if (isa<NamespaceDecl>(SD))
323
1.61M
    return true;
324
768k
325
768k
  if (!isa<TypeDecl>(SD))
326
9
    return false;
327
768k
328
768k
  // Determine whether we have a class (or, in C++11, an enum) or
329
768k
  // a typedef thereof. If so, build the nested-name-specifier.
330
768k
  QualType T = Context.getTypeDeclType(cast<TypeDecl>(SD));
331
768k
  if (T->isDependentType())
332
501k
    return true;
333
267k
  if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
334
13.7k
    if (TD->getUnderlyingType()->isRecordType())
335
13.7k
      return true;
336
57
    if (TD->getUnderlyingType()->isEnumeralType()) {
337
1
      if (Context.getLangOpts().CPlusPlus11)
338
1
        return true;
339
0
      if (IsExtension)
340
0
        *IsExtension = true;
341
0
    }
342
253k
  } else if (isa<RecordDecl>(SD)) {
343
246k
    return true;
344
246k
  } else 
if (7.12k
isa<EnumDecl>(SD)7.12k
) {
345
7.12k
    if (Context.getLangOpts().CPlusPlus11)
346
7.09k
      return true;
347
22
    if (IsExtension)
348
13
      *IsExtension = true;
349
22
  }
350
267k
351
267k
  
return false78
;
352
267k
}
353
354
/// If the given nested-name-specifier begins with a bare identifier
355
/// (e.g., Base::), perform name lookup for that identifier as a
356
/// nested-name-specifier within the given scope, and return the result of that
357
/// name lookup.
358
549
NamedDecl *Sema::FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS) {
359
549
  if (!S || !NNS)
360
0
    return nullptr;
361
549
362
704
  
while (549
NNS->getPrefix())
363
155
    NNS = NNS->getPrefix();
364
549
365
549
  if (NNS->getKind() != NestedNameSpecifier::Identifier)
366
480
    return nullptr;
367
69
368
69
  LookupResult Found(*this, NNS->getAsIdentifier(), SourceLocation(),
369
69
                     LookupNestedNameSpecifierName);
370
69
  LookupName(Found, S);
371
69
  assert(!Found.isAmbiguous() && "Cannot handle ambiguities here yet");
372
69
373
69
  if (!Found.isSingleResult())
374
15
    return nullptr;
375
54
376
54
  NamedDecl *Result = Found.getFoundDecl();
377
54
  if (isAcceptableNestedNameSpecifier(Result))
378
53
    return Result;
379
1
380
1
  return nullptr;
381
1
}
382
383
bool Sema::isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
384
87
                                        NestedNameSpecInfo &IdInfo) {
385
87
  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
386
87
  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
387
87
                     LookupNestedNameSpecifierName);
388
87
389
87
  // Determine where to perform name lookup
390
87
  DeclContext *LookupCtx = nullptr;
391
87
  bool isDependent = false;
392
87
  if (!ObjectType.isNull()) {
393
18
    // This nested-name-specifier occurs in a member access expression, e.g.,
394
18
    // x->B::f, and we are looking into the type of the object.
395
18
    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
396
18
    LookupCtx = computeDeclContext(ObjectType);
397
18
    isDependent = ObjectType->isDependentType();
398
69
  } else if (SS.isSet()) {
399
5
    // This nested-name-specifier occurs after another nested-name-specifier,
400
5
    // so long into the context associated with the prior nested-name-specifier.
401
5
    LookupCtx = computeDeclContext(SS, false);
402
5
    isDependent = isDependentScopeSpecifier(SS);
403
5
    Found.setContextRange(SS.getRange());
404
5
  }
405
87
406
87
  if (LookupCtx) {
407
4
    // Perform "qualified" name lookup into the declaration context we
408
4
    // computed, which is either the type of the base of a member access
409
4
    // expression or the declaration context associated with a prior
410
4
    // nested-name-specifier.
411
4
412
4
    // The declaration context must be complete.
413
4
    if (!LookupCtx->isDependentContext() &&
414
4
        RequireCompleteDeclContext(SS, LookupCtx))
415
0
      return false;
416
4
417
4
    LookupQualifiedName(Found, LookupCtx);
418
83
  } else if (isDependent) {
419
19
    return false;
420
64
  } else {
421
64
    LookupName(Found, S);
422
64
  }
423
87
  Found.suppressDiagnostics();
424
68
425
68
  return Found.getAsSingle<NamespaceDecl>();
426
87
}
427
428
namespace {
429
430
// Callback to only accept typo corrections that can be a valid C++ member
431
// intializer: either a non-static field member or a base class.
432
class NestedNameSpecifierValidatorCCC final
433
    : public CorrectionCandidateCallback {
434
public:
435
  explicit NestedNameSpecifierValidatorCCC(Sema &SRef)
436
156
      : SRef(SRef) {}
437
438
74
  bool ValidateCandidate(const TypoCorrection &candidate) override {
439
74
    return SRef.isAcceptableNestedNameSpecifier(candidate.getCorrectionDecl());
440
74
  }
441
442
144
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
443
144
    return llvm::make_unique<NestedNameSpecifierValidatorCCC>(*this);
444
144
  }
445
446
 private:
447
  Sema &SRef;
448
};
449
450
}
451
452
/// Build a new nested-name-specifier for "identifier::", as described
453
/// by ActOnCXXNestedNameSpecifier.
454
///
455
/// \param S Scope in which the nested-name-specifier occurs.
456
/// \param IdInfo Parser information about an identifier in the
457
///        nested-name-spec.
458
/// \param EnteringContext If true, enter the context specified by the
459
///        nested-name-specifier.
460
/// \param SS Optional nested name specifier preceding the identifier.
461
/// \param ScopeLookupResult Provides the result of name lookup within the
462
///        scope of the nested-name-specifier that was computed at template
463
///        definition time.
464
/// \param ErrorRecoveryLookup Specifies if the method is called to improve
465
///        error recovery and what kind of recovery is performed.
466
/// \param IsCorrectedToColon If not null, suggestion of replace '::' -> ':'
467
///        are allowed.  The bool value pointed by this parameter is set to
468
///       'true' if the identifier is treated as if it was followed by ':',
469
///        not '::'.
470
/// \param OnlyNamespace If true, only considers namespaces in lookup.
471
///
472
/// This routine differs only slightly from ActOnCXXNestedNameSpecifier, in
473
/// that it contains an extra parameter \p ScopeLookupResult, which provides
474
/// the result of name lookup within the scope of the nested-name-specifier
475
/// that was computed at template definition time.
476
///
477
/// If ErrorRecoveryLookup is true, then this call is used to improve error
478
/// recovery.  This means that it should not emit diagnostics, it should
479
/// just return true on failure.  It also means it should only return a valid
480
/// scope if it *knows* that the result is correct.  It should not return in a
481
/// dependent context, for example. Nor will it extend \p SS with the scope
482
/// specifier.
483
bool Sema::BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
484
                                       bool EnteringContext, CXXScopeSpec &SS,
485
                                       NamedDecl *ScopeLookupResult,
486
                                       bool ErrorRecoveryLookup,
487
                                       bool *IsCorrectedToColon,
488
2.39M
                                       bool OnlyNamespace) {
489
2.39M
  if (IdInfo.Identifier->isEditorPlaceholder())
490
4
    return true;
491
2.39M
  LookupResult Found(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
492
2.39M
                     OnlyNamespace ? 
LookupNamespaceName225
493
2.39M
                                   : 
LookupNestedNameSpecifierName2.39M
);
494
2.39M
  QualType ObjectType = GetTypeFromParser(IdInfo.ObjectType);
495
2.39M
496
2.39M
  // Determine where to perform name lookup
497
2.39M
  DeclContext *LookupCtx = nullptr;
498
2.39M
  bool isDependent = false;
499
2.39M
  if (IsCorrectedToColon)
500
138k
    *IsCorrectedToColon = false;
501
2.39M
  if (!ObjectType.isNull()) {
502
570
    // This nested-name-specifier occurs in a member access expression, e.g.,
503
570
    // x->B::f, and we are looking into the type of the object.
504
570
    assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
505
570
    LookupCtx = computeDeclContext(ObjectType);
506
570
    isDependent = ObjectType->isDependentType();
507
2.39M
  } else if (SS.isSet()) {
508
395k
    // This nested-name-specifier occurs after another nested-name-specifier,
509
395k
    // so look into the context associated with the prior nested-name-specifier.
510
395k
    LookupCtx = computeDeclContext(SS, EnteringContext);
511
395k
    isDependent = isDependentScopeSpecifier(SS);
512
395k
    Found.setContextRange(SS.getRange());
513
395k
  }
514
2.39M
515
2.39M
  bool ObjectTypeSearchedInScope = false;
516
2.39M
  if (LookupCtx) {
517
383k
    // Perform "qualified" name lookup into the declaration context we
518
383k
    // computed, which is either the type of the base of a member access
519
383k
    // expression or the declaration context associated with a prior
520
383k
    // nested-name-specifier.
521
383k
522
383k
    // The declaration context must be complete.
523
383k
    if (!LookupCtx->isDependentContext() &&
524
383k
        
RequireCompleteDeclContext(SS, LookupCtx)381k
)
525
0
      return true;
526
383k
527
383k
    LookupQualifiedName(Found, LookupCtx);
528
383k
529
383k
    if (!ObjectType.isNull() && 
Found.empty()494
) {
530
232
      // C++ [basic.lookup.classref]p4:
531
232
      //   If the id-expression in a class member access is a qualified-id of
532
232
      //   the form
533
232
      //
534
232
      //        class-name-or-namespace-name::...
535
232
      //
536
232
      //   the class-name-or-namespace-name following the . or -> operator is
537
232
      //   looked up both in the context of the entire postfix-expression and in
538
232
      //   the scope of the class of the object expression. If the name is found
539
232
      //   only in the scope of the class of the object expression, the name
540
232
      //   shall refer to a class-name. If the name is found only in the
541
232
      //   context of the entire postfix-expression, the name shall refer to a
542
232
      //   class-name or namespace-name. [...]
543
232
      //
544
232
      // Qualified name lookup into a class will not find a namespace-name,
545
232
      // so we do not need to diagnose that case specifically. However,
546
232
      // this qualified name lookup may find nothing. In that case, perform
547
232
      // unqualified name lookup in the given scope (if available) or
548
232
      // reconstruct the result from when name lookup was performed at template
549
232
      // definition time.
550
232
      if (S)
551
206
        LookupName(Found, S);
552
26
      else if (ScopeLookupResult)
553
22
        Found.addDecl(ScopeLookupResult);
554
232
555
232
      ObjectTypeSearchedInScope = true;
556
232
    }
557
2.00M
  } else if (!isDependent) {
558
1.99M
    // Perform unqualified name lookup in the current scope.
559
1.99M
    LookupName(Found, S);
560
1.99M
  }
561
2.39M
562
2.39M
  if (Found.isAmbiguous())
563
4
    return true;
564
2.39M
565
2.39M
  // If we performed lookup into a dependent context and did not find anything,
566
2.39M
  // that's fine: just build a dependent nested-name-specifier.
567
2.39M
  if (Found.empty() && 
isDependent13.4k
&&
568
2.39M
      
!(12.8k
LookupCtx12.8k
&&
LookupCtx->isRecord()6
&&
569
12.8k
        
(6
!cast<CXXRecordDecl>(LookupCtx)->hasDefinition()6
||
570
12.8k
         
!cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()3
))) {
571
12.8k
    // Don't speculate if we're just trying to improve error recovery.
572
12.8k
    if (ErrorRecoveryLookup)
573
0
      return true;
574
12.8k
575
12.8k
    // We were not able to compute the declaration context for a dependent
576
12.8k
    // base object type or prior nested-name-specifier, so this
577
12.8k
    // nested-name-specifier refers to an unknown specialization. Just build
578
12.8k
    // a dependent nested-name-specifier.
579
12.8k
    SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc, IdInfo.CCLoc);
580
12.8k
    return false;
581
12.8k
  }
582
2.37M
583
2.37M
  if (Found.empty() && 
!ErrorRecoveryLookup627
) {
584
189
    // If identifier is not found as class-name-or-namespace-name, but is found
585
189
    // as other entity, don't look for typos.
586
189
    LookupResult R(*this, Found.getLookupNameInfo(), LookupOrdinaryName);
587
189
    if (LookupCtx)
588
42
      LookupQualifiedName(R, LookupCtx);
589
147
    else if (S && 
!isDependent146
)
590
146
      LookupName(R, S);
591
189
    if (!R.empty()) {
592
24
      // Don't diagnose problems with this speculative lookup.
593
24
      R.suppressDiagnostics();
594
24
      // The identifier is found in ordinary lookup. If correction to colon is
595
24
      // allowed, suggest replacement to ':'.
596
24
      if (IsCorrectedToColon) {
597
9
        *IsCorrectedToColon = true;
598
9
        Diag(IdInfo.CCLoc, diag::err_nested_name_spec_is_not_class)
599
9
            << IdInfo.Identifier << getLangOpts().CPlusPlus
600
9
            << FixItHint::CreateReplacement(IdInfo.CCLoc, ":");
601
9
        if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
602
9
          Diag(ND->getLocation(), diag::note_declared_at);
603
9
        return true;
604
9
      }
605
15
      // Replacement '::' -> ':' is not allowed, just issue respective error.
606
15
      Diag(R.getNameLoc(), OnlyNamespace
607
15
                               ? 
unsigned(diag::err_expected_namespace_name)9
608
15
                               : 
unsigned(diag::err_expected_class_or_namespace)6
)
609
15
          << IdInfo.Identifier << getLangOpts().CPlusPlus;
610
15
      if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
611
15
        Diag(ND->getLocation(), diag::note_entity_declared_at)
612
15
            << IdInfo.Identifier;
613
15
      return true;
614
15
    }
615
189
  }
616
2.37M
617
2.37M
  if (Found.empty() && 
!ErrorRecoveryLookup603
&&
!getLangOpts().MSVCCompat165
) {
618
156
    // We haven't found anything, and we're not recovering from a
619
156
    // different kind of error, so look for typos.
620
156
    DeclarationName Name = Found.getLookupName();
621
156
    Found.clear();
622
156
    NestedNameSpecifierValidatorCCC CCC(*this);
623
156
    if (TypoCorrection Corrected = CorrectTypo(
624
64
            Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, CCC,
625
64
            CTK_ErrorRecovery, LookupCtx, EnteringContext)) {
626
64
      if (LookupCtx) {
627
9
        bool DroppedSpecifier =
628
9
            Corrected.WillReplaceSpecifier() &&
629
9
            
Name.getAsString() == Corrected.getAsString(getLangOpts())5
;
630
9
        if (DroppedSpecifier)
631
1
          SS.clear();
632
9
        diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
633
9
                                  << Name << LookupCtx << DroppedSpecifier
634
9
                                  << SS.getRange());
635
9
      } else
636
55
        diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
637
55
                                  << Name);
638
64
639
64
      if (Corrected.getCorrectionSpecifier())
640
12
        SS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
641
12
                       SourceRange(Found.getNameLoc()));
642
64
643
64
      if (NamedDecl *ND = Corrected.getFoundDecl())
644
64
        Found.addDecl(ND);
645
64
      Found.setLookupName(Corrected.getCorrection());
646
92
    } else {
647
92
      Found.setLookupName(IdInfo.Identifier);
648
92
    }
649
156
  }
650
2.37M
651
2.37M
  NamedDecl *SD =
652
2.37M
      Found.isSingleResult() ? 
Found.getRepresentativeDecl()2.37M
:
nullptr539
;
653
2.37M
  bool IsExtension = false;
654
2.37M
  bool AcceptSpec = isAcceptableNestedNameSpecifier(SD, &IsExtension);
655
2.37M
  if (!AcceptSpec && 
IsExtension607
) {
656
13
    AcceptSpec = true;
657
13
    Diag(IdInfo.IdentifierLoc, diag::ext_nested_name_spec_is_enum);
658
13
  }
659
2.37M
  if (AcceptSpec) {
660
2.37M
    if (!ObjectType.isNull() && 
!ObjectTypeSearchedInScope483
&&
661
2.37M
        
!getLangOpts().CPlusPlus11264
) {
662
38
      // C++03 [basic.lookup.classref]p4:
663
38
      //   [...] If the name is found in both contexts, the
664
38
      //   class-name-or-namespace-name shall refer to the same entity.
665
38
      //
666
38
      // We already found the name in the scope of the object. Now, look
667
38
      // into the current scope (the scope of the postfix-expression) to
668
38
      // see if we can find the same name there. As above, if there is no
669
38
      // scope, reconstruct the result from the template instantiation itself.
670
38
      //
671
38
      // Note that C++11 does *not* perform this redundant lookup.
672
38
      NamedDecl *OuterDecl;
673
38
      if (S) {
674
29
        LookupResult FoundOuter(*this, IdInfo.Identifier, IdInfo.IdentifierLoc,
675
29
                                LookupNestedNameSpecifierName);
676
29
        LookupName(FoundOuter, S);
677
29
        OuterDecl = FoundOuter.getAsSingle<NamedDecl>();
678
29
      } else
679
9
        OuterDecl = ScopeLookupResult;
680
38
681
38
      if (isAcceptableNestedNameSpecifier(OuterDecl) &&
682
38
          
OuterDecl->getCanonicalDecl() != SD->getCanonicalDecl()27
&&
683
38
          
(23
!isa<TypeDecl>(OuterDecl)23
||
!isa<TypeDecl>(SD)23
||
684
23
           !Context.hasSameType(
685
23
                            Context.getTypeDeclType(cast<TypeDecl>(OuterDecl)),
686
23
                               Context.getTypeDeclType(cast<TypeDecl>(SD))))) {
687
2
        if (ErrorRecoveryLookup)
688
0
          return true;
689
2
690
2
         Diag(IdInfo.IdentifierLoc,
691
2
              diag::err_nested_name_member_ref_lookup_ambiguous)
692
2
           << IdInfo.Identifier;
693
2
         Diag(SD->getLocation(), diag::note_ambig_member_ref_object_type)
694
2
           << ObjectType;
695
2
         Diag(OuterDecl->getLocation(), diag::note_ambig_member_ref_scope);
696
2
697
2
         // Fall through so that we'll pick the name we found in the object
698
2
         // type, since that's probably what the user wanted anyway.
699
2
       }
700
38
    }
701
2.37M
702
2.37M
    if (auto *TD = dyn_cast_or_null<TypedefNameDecl>(SD))
703
337k
      MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
704
2.37M
705
2.37M
    // If we're just performing this lookup for error-recovery purposes,
706
2.37M
    // don't extend the nested-name-specifier. Just return now.
707
2.37M
    if (ErrorRecoveryLookup)
708
139
      return false;
709
2.37M
710
2.37M
    // The use of a nested name specifier may trigger deprecation warnings.
711
2.37M
    DiagnoseUseOfDecl(SD, IdInfo.CCLoc);
712
2.37M
713
2.37M
    if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(SD)) {
714
1.61M
      SS.Extend(Context, Namespace, IdInfo.IdentifierLoc, IdInfo.CCLoc);
715
1.61M
      return false;
716
1.61M
    }
717
768k
718
768k
    if (NamespaceAliasDecl *Alias = dyn_cast<NamespaceAliasDecl>(SD)) {
719
320
      SS.Extend(Context, Alias, IdInfo.IdentifierLoc, IdInfo.CCLoc);
720
320
      return false;
721
320
    }
722
767k
723
767k
    QualType T =
724
767k
        Context.getTypeDeclType(cast<TypeDecl>(SD->getUnderlyingDecl()));
725
767k
    TypeLocBuilder TLB;
726
767k
    if (isa<InjectedClassNameType>(T)) {
727
202
      InjectedClassNameTypeLoc InjectedTL
728
202
        = TLB.push<InjectedClassNameTypeLoc>(T);
729
202
      InjectedTL.setNameLoc(IdInfo.IdentifierLoc);
730
767k
    } else if (isa<RecordType>(T)) {
731
250k
      RecordTypeLoc RecordTL = TLB.push<RecordTypeLoc>(T);
732
250k
      RecordTL.setNameLoc(IdInfo.IdentifierLoc);
733
517k
    } else if (isa<TypedefType>(T)) {
734
337k
      TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T);
735
337k
      TypedefTL.setNameLoc(IdInfo.IdentifierLoc);
736
337k
    } else 
if (179k
isa<EnumType>(T)179k
) {
737
7.14k
      EnumTypeLoc EnumTL = TLB.push<EnumTypeLoc>(T);
738
7.14k
      EnumTL.setNameLoc(IdInfo.IdentifierLoc);
739
172k
    } else if (isa<TemplateTypeParmType>(T)) {
740
172k
      TemplateTypeParmTypeLoc TemplateTypeTL
741
172k
        = TLB.push<TemplateTypeParmTypeLoc>(T);
742
172k
      TemplateTypeTL.setNameLoc(IdInfo.IdentifierLoc);
743
172k
    } else 
if (1
isa<UnresolvedUsingType>(T)1
) {
744
1
      UnresolvedUsingTypeLoc UnresolvedTL
745
1
        = TLB.push<UnresolvedUsingTypeLoc>(T);
746
1
      UnresolvedTL.setNameLoc(IdInfo.IdentifierLoc);
747
1
    } else 
if (0
isa<SubstTemplateTypeParmType>(T)0
) {
748
0
      SubstTemplateTypeParmTypeLoc TL
749
0
        = TLB.push<SubstTemplateTypeParmTypeLoc>(T);
750
0
      TL.setNameLoc(IdInfo.IdentifierLoc);
751
0
    } else if (isa<SubstTemplateTypeParmPackType>(T)) {
752
0
      SubstTemplateTypeParmPackTypeLoc TL
753
0
        = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T);
754
0
      TL.setNameLoc(IdInfo.IdentifierLoc);
755
0
    } else {
756
0
      llvm_unreachable("Unhandled TypeDecl node in nested-name-specifier");
757
0
    }
758
767k
759
767k
    if (T->isEnumeralType())
760
7.15k
      Diag(IdInfo.IdentifierLoc, diag::warn_cxx98_compat_enum_nested_name_spec);
761
767k
762
767k
    SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
763
767k
              IdInfo.CCLoc);
764
767k
    return false;
765
767k
  }
766
594
767
594
  // Otherwise, we have an error case.  If we don't want diagnostics, just
768
594
  // return an error now.
769
594
  if (ErrorRecoveryLookup)
770
438
    return true;
771
156
772
156
  // If we didn't find anything during our lookup, try again with
773
156
  // ordinary name lookup, which can help us produce better error
774
156
  // messages.
775
156
  if (Found.empty()) {
776
101
    Found.clear(LookupOrdinaryName);
777
101
    LookupName(Found, S);
778
101
  }
779
156
780
156
  // In Microsoft mode, if we are within a templated function and we can't
781
156
  // resolve Identifier, then extend the SS with Identifier. This will have
782
156
  // the effect of resolving Identifier during template instantiation.
783
156
  // The goal is to be able to resolve a function call whose
784
156
  // nested-name-specifier is located inside a dependent base class.
785
156
  // Example:
786
156
  //
787
156
  // class C {
788
156
  // public:
789
156
  //    static void foo2() {  }
790
156
  // };
791
156
  // template <class T> class A { public: typedef C D; };
792
156
  //
793
156
  // template <class T> class B : public A<T> {
794
156
  // public:
795
156
  //   void foo() { D::foo2(); }
796
156
  // };
797
156
  if (getLangOpts().MSVCCompat) {
798
10
    DeclContext *DC = LookupCtx ? 
LookupCtx2
:
CurContext8
;
799
10
    if (DC->isDependentContext() && 
DC->isFunctionOrMethod()6
) {
800
6
      CXXRecordDecl *ContainingClass = dyn_cast<CXXRecordDecl>(DC->getParent());
801
6
      if (ContainingClass && 
ContainingClass->hasAnyDependentBases()5
) {
802
4
        Diag(IdInfo.IdentifierLoc,
803
4
             diag::ext_undeclared_unqual_id_with_dependent_base)
804
4
            << IdInfo.Identifier << ContainingClass;
805
4
        SS.Extend(Context, IdInfo.Identifier, IdInfo.IdentifierLoc,
806
4
                  IdInfo.CCLoc);
807
4
        return false;
808
4
      }
809
152
    }
810
10
  }
811
152
812
152
  if (!Found.empty()) {
813
55
    if (TypeDecl *TD = Found.getAsSingle<TypeDecl>())
814
53
      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
815
53
          << Context.getTypeDeclType(TD) << getLangOpts().CPlusPlus;
816
2
    else {
817
2
      Diag(IdInfo.IdentifierLoc, diag::err_expected_class_or_namespace)
818
2
          << IdInfo.Identifier << getLangOpts().CPlusPlus;
819
2
      if (NamedDecl *ND = Found.getAsSingle<NamedDecl>())
820
2
        Diag(ND->getLocation(), diag::note_entity_declared_at)
821
2
            << IdInfo.Identifier;
822
2
    }
823
97
  } else if (SS.isSet())
824
13
    Diag(IdInfo.IdentifierLoc, diag::err_no_member) << IdInfo.Identifier
825
13
        << LookupCtx << SS.getRange();
826
84
  else
827
84
    Diag(IdInfo.IdentifierLoc, diag::err_undeclared_var_use)
828
84
        << IdInfo.Identifier;
829
152
830
152
  return true;
831
152
}
832
833
bool Sema::ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo,
834
                                       bool EnteringContext, CXXScopeSpec &SS,
835
                                       bool ErrorRecoveryLookup,
836
                                       bool *IsCorrectedToColon,
837
2.38M
                                       bool OnlyNamespace) {
838
2.38M
  if (SS.isInvalid())
839
17
    return true;
840
2.38M
841
2.38M
  return BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
842
2.38M
                                     /*ScopeLookupResult=*/nullptr, false,
843
2.38M
                                     IsCorrectedToColon, OnlyNamespace);
844
2.38M
}
845
846
bool Sema::ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
847
                                               const DeclSpec &DS,
848
1.38k
                                               SourceLocation ColonColonLoc) {
849
1.38k
  if (SS.isInvalid() || DS.getTypeSpecType() == DeclSpec::TST_error)
850
3
    return true;
851
1.38k
852
1.38k
  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
853
1.38k
854
1.38k
  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
855
1.38k
  if (T.isNull())
856
0
    return true;
857
1.38k
858
1.38k
  if (!T->isDependentType() && 
!T->getAs<TagType>()59
) {
859
4
    Diag(DS.getTypeSpecTypeLoc(), diag::err_expected_class_or_namespace)
860
4
      << T << getLangOpts().CPlusPlus;
861
4
    return true;
862
4
  }
863
1.37k
864
1.37k
  TypeLocBuilder TLB;
865
1.37k
  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
866
1.37k
  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
867
1.37k
  SS.Extend(Context, SourceLocation(), TLB.getTypeLocInContext(Context, T),
868
1.37k
            ColonColonLoc);
869
1.37k
  return false;
870
1.37k
}
871
872
/// IsInvalidUnlessNestedName - This method is used for error recovery
873
/// purposes to determine whether the specified identifier is only valid as
874
/// a nested name specifier, for example a namespace name.  It is
875
/// conservatively correct to always return false from this method.
876
///
877
/// The arguments are the same as those passed to ActOnCXXNestedNameSpecifier.
878
bool Sema::IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
879
                                     NestedNameSpecInfo &IdInfo,
880
577
                                     bool EnteringContext) {
881
577
  if (SS.isInvalid())
882
0
    return false;
883
577
884
577
  return !BuildCXXNestedNameSpecifier(S, IdInfo, EnteringContext, SS,
885
577
                                      /*ScopeLookupResult=*/nullptr, true);
886
577
}
887
888
bool Sema::ActOnCXXNestedNameSpecifier(Scope *S,
889
                                       CXXScopeSpec &SS,
890
                                       SourceLocation TemplateKWLoc,
891
                                       TemplateTy OpaqueTemplate,
892
                                       SourceLocation TemplateNameLoc,
893
                                       SourceLocation LAngleLoc,
894
                                       ASTTemplateArgsPtr TemplateArgsIn,
895
                                       SourceLocation RAngleLoc,
896
                                       SourceLocation CCLoc,
897
1.29M
                                       bool EnteringContext) {
898
1.29M
  if (SS.isInvalid())
899
0
    return true;
900
1.29M
901
1.29M
  TemplateName Template = OpaqueTemplate.get();
902
1.29M
903
1.29M
  // Translate the parser's template argument list in our AST format.
904
1.29M
  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
905
1.29M
  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
906
1.29M
907
1.29M
  DependentTemplateName *DTN = Template.getAsDependentTemplateName();
908
1.29M
  if (DTN && 
DTN->isIdentifier()1.00k
) {
909
996
    // Handle a dependent template specialization for which we cannot resolve
910
996
    // the template name.
911
996
    assert(DTN->getQualifier() == SS.getScopeRep());
912
996
    QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
913
996
                                                          DTN->getQualifier(),
914
996
                                                          DTN->getIdentifier(),
915
996
                                                                TemplateArgs);
916
996
917
996
    // Create source-location information for this type.
918
996
    TypeLocBuilder Builder;
919
996
    DependentTemplateSpecializationTypeLoc SpecTL
920
996
      = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
921
996
    SpecTL.setElaboratedKeywordLoc(SourceLocation());
922
996
    SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
923
996
    SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
924
996
    SpecTL.setTemplateNameLoc(TemplateNameLoc);
925
996
    SpecTL.setLAngleLoc(LAngleLoc);
926
996
    SpecTL.setRAngleLoc(RAngleLoc);
927
2.00k
    for (unsigned I = 0, N = TemplateArgs.size(); I != N; 
++I1.00k
)
928
1.00k
      SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
929
996
930
996
    SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
931
996
              CCLoc);
932
996
    return false;
933
996
  }
934
1.29M
935
1.29M
  // If we assumed an undeclared identifier was a template name, try to
936
1.29M
  // typo-correct it now.
937
1.29M
  if (Template.getAsAssumedTemplateName() &&
938
1.29M
      
resolveAssumedTemplateNameAsType(S, Template, TemplateNameLoc)38
)
939
34
    return true;
940
1.29M
941
1.29M
  TemplateDecl *TD = Template.getAsTemplateDecl();
942
1.29M
  if (Template.getAsOverloadedTemplate() || 
DTN1.29M
||
943
1.29M
      
isa<FunctionTemplateDecl>(TD)1.29M
||
isa<VarTemplateDecl>(TD)1.29M
) {
944
17
    SourceRange R(TemplateNameLoc, RAngleLoc);
945
17
    if (SS.getRange().isValid())
946
8
      R.setBegin(SS.getRange().getBegin());
947
17
948
17
    Diag(CCLoc, diag::err_non_type_template_in_nested_name_specifier)
949
17
      << (TD && 
isa<VarTemplateDecl>(TD)6
) << Template << R;
950
17
    NoteAllFoundTemplates(Template);
951
17
    return true;
952
17
  }
953
1.29M
954
1.29M
  // We were able to resolve the template name to an actual template.
955
1.29M
  // Build an appropriate nested-name-specifier.
956
1.29M
  QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
957
1.29M
  if (T.isNull())
958
180
    return true;
959
1.28M
960
1.28M
  // Alias template specializations can produce types which are not valid
961
1.28M
  // nested name specifiers.
962
1.28M
  if (!T->isDependentType() && 
!T->getAs<TagType>()35.8k
) {
963
2
    Diag(TemplateNameLoc, diag::err_nested_name_spec_non_tag) << T;
964
2
    NoteAllFoundTemplates(Template);
965
2
    return true;
966
2
  }
967
1.28M
968
1.28M
  // Provide source-location information for the template specialization type.
969
1.28M
  TypeLocBuilder Builder;
970
1.28M
  TemplateSpecializationTypeLoc SpecTL
971
1.28M
    = Builder.push<TemplateSpecializationTypeLoc>(T);
972
1.28M
  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
973
1.28M
  SpecTL.setTemplateNameLoc(TemplateNameLoc);
974
1.28M
  SpecTL.setLAngleLoc(LAngleLoc);
975
1.28M
  SpecTL.setRAngleLoc(RAngleLoc);
976
3.30M
  for (unsigned I = 0, N = TemplateArgs.size(); I != N; 
++I2.01M
)
977
2.01M
    SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
978
1.28M
979
1.28M
980
1.28M
  SS.Extend(Context, TemplateKWLoc, Builder.getTypeLocInContext(Context, T),
981
1.28M
            CCLoc);
982
1.28M
  return false;
983
1.28M
}
984
985
namespace {
986
  /// A structure that stores a nested-name-specifier annotation,
987
  /// including both the nested-name-specifier
988
  struct NestedNameSpecifierAnnotation {
989
    NestedNameSpecifier *NNS;
990
  };
991
}
992
993
3.68M
void *Sema::SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS) {
994
3.68M
  if (SS.isEmpty() || SS.isInvalid())
995
547
    return nullptr;
996
3.68M
997
3.68M
  void *Mem = Context.Allocate(
998
3.68M
      (sizeof(NestedNameSpecifierAnnotation) + SS.location_size()),
999
3.68M
      alignof(NestedNameSpecifierAnnotation));
1000
3.68M
  NestedNameSpecifierAnnotation *Annotation
1001
3.68M
    = new (Mem) NestedNameSpecifierAnnotation;
1002
3.68M
  Annotation->NNS = SS.getScopeRep();
1003
3.68M
  memcpy(Annotation + 1, SS.location_data(), SS.location_size());
1004
3.68M
  return Annotation;
1005
3.68M
}
1006
1007
void Sema::RestoreNestedNameSpecifierAnnotation(void *AnnotationPtr,
1008
                                                SourceRange AnnotationRange,
1009
4.45M
                                                CXXScopeSpec &SS) {
1010
4.45M
  if (!AnnotationPtr) {
1011
647
    SS.SetInvalid(AnnotationRange);
1012
647
    return;
1013
647
  }
1014
4.45M
1015
4.45M
  NestedNameSpecifierAnnotation *Annotation
1016
4.45M
    = static_cast<NestedNameSpecifierAnnotation *>(AnnotationPtr);
1017
4.45M
  SS.Adopt(NestedNameSpecifierLoc(Annotation->NNS, Annotation + 1));
1018
4.45M
}
1019
1020
338k
bool Sema::ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1021
338k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1022
338k
1023
338k
  // Don't enter a declarator context when the current context is an Objective-C
1024
338k
  // declaration.
1025
338k
  if (isa<ObjCContainerDecl>(CurContext) || 
isa<ObjCMethodDecl>(CurContext)338k
)
1026
12
    return false;
1027
338k
1028
338k
  NestedNameSpecifier *Qualifier = SS.getScopeRep();
1029
338k
1030
338k
  // There are only two places a well-formed program may qualify a
1031
338k
  // declarator: first, when defining a namespace or class member
1032
338k
  // out-of-line, and second, when naming an explicitly-qualified
1033
338k
  // friend function.  The latter case is governed by
1034
338k
  // C++03 [basic.lookup.unqual]p10:
1035
338k
  //   In a friend declaration naming a member function, a name used
1036
338k
  //   in the function declarator and not part of a template-argument
1037
338k
  //   in a template-id is first looked up in the scope of the member
1038
338k
  //   function's class. If it is not found, or if the name is part of
1039
338k
  //   a template-argument in a template-id, the look up is as
1040
338k
  //   described for unqualified names in the definition of the class
1041
338k
  //   granting friendship.
1042
338k
  // i.e. we don't push a scope unless it's a class member.
1043
338k
1044
338k
  switch (Qualifier->getKind()) {
1045
338k
  case NestedNameSpecifier::Global:
1046
996
  case NestedNameSpecifier::Namespace:
1047
996
  case NestedNameSpecifier::NamespaceAlias:
1048
996
    // These are always namespace scopes.  We never want to enter a
1049
996
    // namespace scope from anything but a file context.
1050
996
    return CurContext->getRedeclContext()->isFileContext();
1051
996
1052
337k
  case NestedNameSpecifier::Identifier:
1053
337k
  case NestedNameSpecifier::TypeSpec:
1054
337k
  case NestedNameSpecifier::TypeSpecWithTemplate:
1055
337k
  case NestedNameSpecifier::Super:
1056
337k
    // These are never namespace scopes.
1057
337k
    return true;
1058
0
  }
1059
0
1060
0
  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
1061
0
}
1062
1063
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
1064
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
1065
/// After this method is called, according to [C++ 3.4.3p3], names should be
1066
/// looked up in the declarator-id's scope, until the declarator is parsed and
1067
/// ActOnCXXExitDeclaratorScope is called.
1068
/// The 'SS' should be a non-empty valid CXXScopeSpec.
1069
338k
bool Sema::ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS) {
1070
338k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1071
338k
1072
338k
  if (SS.isInvalid()) 
return true0
;
1073
338k
1074
338k
  DeclContext *DC = computeDeclContext(SS, true);
1075
338k
  if (!DC) 
return true42
;
1076
338k
1077
338k
  // Before we enter a declarator's context, we need to make sure that
1078
338k
  // it is a complete declaration context.
1079
338k
  if (!DC->isDependentContext() && 
RequireCompleteDeclContext(SS, DC)50.9k
)
1080
8
    return true;
1081
338k
1082
338k
  EnterDeclaratorContext(S, DC);
1083
338k
1084
338k
  // Rebuild the nested name specifier for the new scope.
1085
338k
  if (DC->isDependentContext())
1086
287k
    RebuildNestedNameSpecifierInCurrentInstantiation(SS);
1087
338k
1088
338k
  return false;
1089
338k
}
1090
1091
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
1092
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
1093
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
1094
/// Used to indicate that names should revert to being looked up in the
1095
/// defining scope.
1096
338k
void Sema::ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS) {
1097
338k
  assert(SS.isSet() && "Parser passed invalid CXXScopeSpec.");
1098
338k
  if (SS.isInvalid())
1099
0
    return;
1100
338k
  assert(!SS.isInvalid() && computeDeclContext(SS, true) &&
1101
338k
         "exiting declarator scope we never really entered");
1102
338k
  ExitDeclaratorContext(S);
1103
338k
}