SemaExprCXX.cpp 296 KB
Newer Older
1
2
3
4
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
//
//                     The LLVM Compiler Infrastructure
//
5
6
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
7
8
//
//===----------------------------------------------------------------------===//
9
10
11
12
13
///
/// \file
/// \brief Implements semantic analysis for C++ expressions.
///
//===----------------------------------------------------------------------===//
14

15
#include "clang/Sema/SemaInternal.h"
16
#include "TreeTransform.h"
17
#include "TypeLocBuilder.h"
18
#include "clang/AST/ASTContext.h"
19
#include "clang/AST/ASTLambda.h"
20
#include "clang/AST/CXXInheritance.h"
21
#include "clang/AST/CharUnits.h"
22
#include "clang/AST/DeclObjC.h"
23
#include "clang/AST/ExprCXX.h"
24
#include "clang/AST/ExprObjC.h"
25
#include "clang/AST/RecursiveASTVisitor.h"
26
#include "clang/AST/TypeLoc.h"
27
#include "clang/Basic/PartialDiagnostic.h"
28
#include "clang/Basic/TargetInfo.h"
29
#include "clang/Lex/Preprocessor.h"
30
31
32
33
34
35
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
36
#include "clang/Sema/SemaLambda.h"
37
#include "clang/Sema/TemplateDeduction.h"
38
#include "llvm/ADT/APInt.h"
39
#include "llvm/ADT/STLExtras.h"
40
#include "llvm/Support/ErrorHandling.h"
41
using namespace clang;
John McCall's avatar
John McCall committed
42
using namespace sema;
43

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/// \brief Handle the result of the special case name lookup for inheriting
/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
/// constructor names in member using declarations, even if 'X' is not the
/// name of the corresponding type.
ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
                                              SourceLocation NameLoc,
                                              IdentifierInfo &Name) {
  NestedNameSpecifier *NNS = SS.getScopeRep();

  // Convert the nested-name-specifier into a type.
  QualType Type;
  switch (NNS->getKind()) {
  case NestedNameSpecifier::TypeSpec:
  case NestedNameSpecifier::TypeSpecWithTemplate:
    Type = QualType(NNS->getAsType(), 0);
    break;

  case NestedNameSpecifier::Identifier:
    // Strip off the last layer of the nested-name-specifier and build a
    // typename type for it.
    assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
    Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
                                        NNS->getAsIdentifier());
    break;

  case NestedNameSpecifier::Global:
70
  case NestedNameSpecifier::Super:
71
72
73
74
75
76
77
78
79
80
81
  case NestedNameSpecifier::Namespace:
  case NestedNameSpecifier::NamespaceAlias:
    llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
  }

  // This reference to the type is located entirely at the location of the
  // final identifier in the qualified-id.
  return CreateParsedType(Type,
                          Context.getTrivialTypeSourceInfo(Type, NameLoc));
}

82
ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
83
                                   IdentifierInfo &II,
84
85
86
87
                                   SourceLocation NameLoc,
                                   Scope *S, CXXScopeSpec &SS,
                                   ParsedType ObjectTypePtr,
                                   bool EnteringContext) {
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
  // Determine where to perform name lookup.

  // FIXME: This area of the standard is very messy, and the current
  // wording is rather unclear about which scopes we search for the
  // destructor name; see core issues 399 and 555. Issue 399 in
  // particular shows where the current description of destructor name
  // lookup is completely out of line with existing practice, e.g.,
  // this appears to be ill-formed:
  //
  //   namespace N {
  //     template <typename T> struct S {
  //       ~S();
  //     };
  //   }
  //
  //   void f(N::S<int>* s) {
  //     s->N::S<int>::~S();
  //   }
  //
107
  // See also PR6358 and PR6359.
108
109
  // For this reason, we're currently only doing the C++03 version of this
  // code; the C++0x version has to wait until we get a proper spec.
110
  QualType SearchType;
111
  DeclContext *LookupCtx = nullptr;
112
113
114
  bool isDependent = false;
  bool LookInScope = false;

115
  if (SS.isInvalid())
116
    return nullptr;
117

118
119
120
121
122
123
124
  // If we have an object type, it's because we are in a
  // pseudo-destructor-expression or a member access expression, and
  // we know what type we're looking for.
  if (ObjectTypePtr)
    SearchType = GetTypeFromParser(ObjectTypePtr);

  if (SS.isSet()) {
125
    NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
126

127
128
    bool AlreadySearched = false;
    bool LookAtPrefix = true;
David Majnemer's avatar
David Majnemer committed
129
    // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
130
    //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
131
    //   the type-names are looked up as types in the scope designated by the
David Majnemer's avatar
David Majnemer committed
132
    //   nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
133
    //
David Majnemer's avatar
David Majnemer committed
134
    //     nested-name-specifier[opt] class-name :: ~ class-name
135
    //
David Majnemer's avatar
David Majnemer committed
136
    //   the second class-name is looked up in the same scope as the first.
137
    //
David Majnemer's avatar
David Majnemer committed
138
139
    // Here, we determine whether the code below is permitted to look at the
    // prefix of the nested-name-specifier.
140
141
142
143
144
    DeclContext *DC = computeDeclContext(SS, EnteringContext);
    if (DC && DC->isFileContext()) {
      AlreadySearched = true;
      LookupCtx = DC;
      isDependent = false;
David Majnemer's avatar
David Majnemer committed
145
    } else if (DC && isa<CXXRecordDecl>(DC)) {
146
      LookAtPrefix = false;
David Majnemer's avatar
David Majnemer committed
147
148
      LookInScope = true;
    }
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
149

150
    // The second case from the C++03 rules quoted further above.
151
    NestedNameSpecifier *Prefix = nullptr;
152
153
154
155
    if (AlreadySearched) {
      // Nothing left to do.
    } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
      CXXScopeSpec PrefixSS;
156
      PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157
158
159
      LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
      isDependent = isDependentScopeSpecifier(PrefixSS);
    } else if (ObjectTypePtr) {
160
161
162
163
      LookupCtx = computeDeclContext(SearchType);
      isDependent = SearchType->isDependentType();
    } else {
      LookupCtx = computeDeclContext(SS, EnteringContext);
164
      isDependent = LookupCtx && LookupCtx->isDependentContext();
165
166
167
168
169
170
171
172
173
174
175
    }
  } else if (ObjectTypePtr) {
    // C++ [basic.lookup.classref]p3:
    //   If the unqualified-id is ~type-name, the type-name is looked up
    //   in the context of the entire postfix-expression. If the type T
    //   of the object expression is of a class type C, the type-name is
    //   also looked up in the scope of class C. At least one of the
    //   lookups shall find a name that refers to (possibly
    //   cv-qualified) T.
    LookupCtx = computeDeclContext(SearchType);
    isDependent = SearchType->isDependentType();
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
176
    assert((isDependent || !SearchType->isIncompleteType()) &&
177
178
179
180
181
182
183
184
           "Caller should have completed object type");

    LookInScope = true;
  } else {
    // Perform lookup into the current scope (only).
    LookInScope = true;
  }

185
  TypeDecl *NonMatchingTypeDecl = nullptr;
186
187
188
  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
  for (unsigned Step = 0; Step != 2; ++Step) {
    // Look for the name first in the computed lookup context (if we
189
    // have one) and, if that fails to find a match, in the scope (if
190
191
192
193
    // we're allowed to look there).
    Found.clear();
    if (Step == 0 && LookupCtx)
      LookupQualifiedName(Found, LookupCtx);
194
    else if (Step == 1 && LookInScope && S)
195
196
197
198
199
200
      LookupName(Found, S);
    else
      continue;

    // FIXME: Should we be suppressing ambiguities here?
    if (Found.isAmbiguous())
201
      return nullptr;
202
203
204

    if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
      QualType T = Context.getTypeDeclType(Type);
205
      MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
206
207
208
209
210

      if (SearchType.isNull() || SearchType->isDependentType() ||
          Context.hasSameUnqualifiedType(T, SearchType)) {
        // We found our type!

211
212
        return CreateParsedType(T,
                                Context.getTrivialTypeSourceInfo(T, NameLoc));
213
      }
214

215
216
      if (!SearchType.isNull())
        NonMatchingTypeDecl = Type;
217
218
219
220
221
222
223
    }

    // If the name that we found is a class template name, and it is
    // the same name as the template name in the last part of the
    // nested-name-specifier (if present) or the object type, then
    // this is the destructor for that class.
    // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
224
    // issue 399, for which there isn't even an obvious direction.
225
226
227
228
229
    if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
      QualType MemberOfType;
      if (SS.isSet()) {
        if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
          // Figure out the type of the context, if it has one.
230
231
          if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
            MemberOfType = Context.getTypeDeclType(Record);
232
233
234
235
        }
      }
      if (MemberOfType.isNull())
        MemberOfType = SearchType;
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
236

237
238
239
240
241
242
243
244
245
246
247
      if (MemberOfType.isNull())
        continue;

      // We're referring into a class template specialization. If the
      // class template we found is the same as the template being
      // specialized, we found what we are looking for.
      if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
        if (ClassTemplateSpecializationDecl *Spec
              = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
          if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
                Template->getCanonicalDecl())
248
249
250
            return CreateParsedType(
                MemberOfType,
                Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
251
252
253
254
        }

        continue;
      }
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
255

256
257
258
259
260
261
262
263
264
265
266
267
268
      // We're referring to an unresolved class template
      // specialization. Determine whether we class template we found
      // is the same as the template being specialized or, if we don't
      // know which template is being specialized, that it at least
      // has the same name.
      if (const TemplateSpecializationType *SpecType
            = MemberOfType->getAs<TemplateSpecializationType>()) {
        TemplateName SpecName = SpecType->getTemplateName();

        // The class template we found is the same template being
        // specialized.
        if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
          if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
269
270
271
            return CreateParsedType(
                MemberOfType,
                Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
272
273
274
275
276
277

          continue;
        }

        // The class template we found has the same name as the
        // (dependent) template name being specialized.
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
278
        if (DependentTemplateName *DepTemplate
279
280
281
                                    = SpecName.getAsDependentTemplateName()) {
          if (DepTemplate->isIdentifier() &&
              DepTemplate->getIdentifier() == Template->getIdentifier())
282
283
284
            return CreateParsedType(
                MemberOfType,
                Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
285
286
287
288
289
290
291
292
293
294

          continue;
        }
      }
    }
  }

  if (isDependent) {
    // We didn't find our type, but that's okay: it's dependent
    // anyway.
295

296
297
298
299
    // FIXME: What if we have no nested-name-specifier?
    QualType T = CheckTypenameType(ETK_None, SourceLocation(),
                                   SS.getWithLocInContext(Context),
                                   II, NameLoc);
300
    return ParsedType::make(T);
301
302
  }

303
304
305
306
307
308
309
310
  if (NonMatchingTypeDecl) {
    QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
    Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
      << T << SearchType;
    Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
      << T;
  } else if (ObjectTypePtr)
    Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
311
      << &II;
312
313
314
315
  else {
    SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
                                          diag::err_destructor_class_name);
    if (S) {
316
      const DeclContext *Ctx = S->getEntity();
317
318
319
320
321
      if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
        DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
                                                 Class->getNameAsString());
    }
  }
322

323
  return nullptr;
324
325
}

326
ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
327
    if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
328
      return nullptr;
329
    assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
330
331
332
333
334
335
           && "only get destructor types from declspecs");
    QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
    QualType SearchType = GetTypeFromParser(ObjectType);
    if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
      return ParsedType::make(T);
    }
336

337
338
    Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
      << T << SearchType;
339
    return nullptr;
340
341
}

342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
                                  const UnqualifiedId &Name) {
  assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);

  if (!SS.isValid())
    return false;

  switch (SS.getScopeRep()->getKind()) {
  case NestedNameSpecifier::Identifier:
  case NestedNameSpecifier::TypeSpec:
  case NestedNameSpecifier::TypeSpecWithTemplate:
    // Per C++11 [over.literal]p2, literal operators can only be declared at
    // namespace scope. Therefore, this unqualified-id cannot name anything.
    // Reject it early, because we have no AST representation for this in the
    // case where the scope is dependent.
    Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
      << SS.getScopeRep();
    return true;

  case NestedNameSpecifier::Global:
362
  case NestedNameSpecifier::Super:
363
364
365
366
367
368
369
370
  case NestedNameSpecifier::Namespace:
  case NestedNameSpecifier::NamespaceAlias:
    return false;
  }

  llvm_unreachable("unknown nested name specifier kind");
}

371
/// \brief Build a C++ typeid expression with a type operand.
372
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
373
374
375
                                SourceLocation TypeidLoc,
                                TypeSourceInfo *Operand,
                                SourceLocation RParenLoc) {
376
  // C++ [expr.typeid]p4:
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
377
  //   The top-level cv-qualifiers of the lvalue expression or the type-id
378
  //   that is the operand of typeid are always ignored.
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
379
  //   If the type of the type-id is a class type or a reference to a class
380
  //   type, the class shall be completely-defined.
381
382
383
384
  Qualifiers Quals;
  QualType T
    = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
                                      Quals);
385
386
387
  if (T->getAs<RecordType>() &&
      RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
    return ExprError();
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
388

389
390
391
  if (T->isVariablyModifiedType())
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);

392
393
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
                                     SourceRange(TypeidLoc, RParenLoc));
394
395
396
}

/// \brief Build a C++ typeid expression with an expression operand.
397
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
398
399
400
                                SourceLocation TypeidLoc,
                                Expr *E,
                                SourceLocation RParenLoc) {
401
  bool WasEvaluated = false;
402
  if (E && !E->isTypeDependent()) {
403
404
405
    if (E->getType()->isPlaceholderType()) {
      ExprResult result = CheckPlaceholderExpr(E);
      if (result.isInvalid()) return ExprError();
406
      E = result.get();
407
408
    }

409
410
411
412
413
414
415
416
    QualType T = E->getType();
    if (const RecordType *RecordT = T->getAs<RecordType>()) {
      CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
      // C++ [expr.typeid]p3:
      //   [...] If the type of the expression is a class type, the class
      //   shall be completely-defined.
      if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
        return ExprError();
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
417

418
      // C++ [expr.typeid]p3:
419
      //   When typeid is applied to an expression other than an glvalue of a
420
421
      //   polymorphic class type [...] [the] expression is an unevaluated
      //   operand. [...]
422
      if (RecordD->isPolymorphic() && E->isGLValue()) {
423
424
        // The subexpression is potentially evaluated; switch the context
        // and recheck the subexpression.
Benjamin Kramer's avatar
Benjamin Kramer committed
425
        ExprResult Result = TransformToPotentiallyEvaluated(E);
426
        if (Result.isInvalid()) return ExprError();
427
        E = Result.get();
428
429
430

        // We require a vtable to query the type at run time.
        MarkVTableUsed(TypeidLoc, RecordD);
431
        WasEvaluated = true;
432
      }
433
    }
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
434

435
436
    // C++ [expr.typeid]p4:
    //   [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
437
438
    //   cv-qualified type, the result of the typeid expression refers to a
    //   std::type_info object representing the cv-unqualified referenced
439
    //   type.
440
441
442
443
    Qualifiers Quals;
    QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
    if (!Context.hasSameType(T, UnqualT)) {
      T = UnqualT;
444
      E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
445
446
    }
  }
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
447

448
449
450
  if (E->getType()->isVariablyModifiedType())
    return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
                     << E->getType());
451
452
453
454
455
456
457
458
  else if (ActiveTemplateInstantiations.empty() &&
           E->HasSideEffects(Context, WasEvaluated)) {
    // The expression operand for typeid is in an unevaluated expression
    // context, so side effects could result in unintended consequences.
    Diag(E->getExprLoc(), WasEvaluated
                              ? diag::warn_side_effects_typeid
                              : diag::warn_side_effects_unevaluated_context);
  }
459

460
461
  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
                                     SourceRange(TypeidLoc, RParenLoc));
462
463
464
}

/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
465
ExprResult
466
467
Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
468
  // Find the std::type_info type.
469
  if (!getStdNamespace())
470
    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
471

472
473
474
475
476
  if (!CXXTypeInfoDecl) {
    IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
    LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
    LookupQualifiedName(R, getStdNamespace());
    CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
477
478
    // Microsoft's typeinfo doesn't have type_info in std but in the global
    // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
479
    if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
480
481
482
      LookupQualifiedName(R, Context.getTranslationUnitDecl());
      CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
    }
483
484
485
    if (!CXXTypeInfoDecl)
      return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
  }
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
486

487
488
489
490
  if (!getLangOpts().RTTI) {
    return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
  }

491
  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
492

493
494
  if (isType) {
    // The operand is a type; handle it as such.
495
    TypeSourceInfo *TInfo = nullptr;
496
497
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
                                   &TInfo);
498
499
    if (T.isNull())
      return ExprError();
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
500

501
502
    if (!TInfo)
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
503

504
    return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
505
  }
506

NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
507
  // The operand is an expression.
508
  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
509
510
}

511
512
513
514
515
516
517
518
519
520
521
522
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
/// a single GUID.
static void
getUuidAttrOfType(Sema &SemaRef, QualType QT,
                  llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
  // Optionally remove one level of pointer, reference or array indirection.
  const Type *Ty = QT.getTypePtr();
  if (QT->isPointerType() || QT->isReferenceType())
    Ty = QT->getPointeeType().getTypePtr();
  else if (QT->isArrayType())
    Ty = Ty->getBaseElementTypeUnsafe();

523
524
  const auto *TD = Ty->getAsTagDecl();
  if (!TD)
525
526
    return;

527
  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
528
529
530
531
532
    UuidAttrs.insert(Uuid);
    return;
  }

  // __uuidof can grab UUIDs from template arguments.
533
  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
534
535
536
537
538
539
540
541
542
543
544
545
546
547
    const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
    for (const TemplateArgument &TA : TAL.asArray()) {
      const UuidAttr *UuidForTA = nullptr;
      if (TA.getKind() == TemplateArgument::Type)
        getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
      else if (TA.getKind() == TemplateArgument::Declaration)
        getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);

      if (UuidForTA)
        UuidAttrs.insert(UuidForTA);
    }
  }
}

548
549
550
551
552
/// \brief Build a Microsoft __uuidof expression with a type operand.
ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
                                SourceLocation TypeidLoc,
                                TypeSourceInfo *Operand,
                                SourceLocation RParenLoc) {
553
  StringRef UuidStr;
Francois Pichet's avatar
Francois Pichet committed
554
  if (!Operand->getType()->isDependentType()) {
555
556
557
558
559
560
    llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
    getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
    if (UuidAttrs.empty())
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
    if (UuidAttrs.size() > 1)
      return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
561
    UuidStr = UuidAttrs.back()->getGuid();
Francois Pichet's avatar
Francois Pichet committed
562
  }
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
563

564
  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
565
                                     SourceRange(TypeidLoc, RParenLoc));
566
567
568
569
570
571
572
}

/// \brief Build a Microsoft __uuidof expression with an expression operand.
ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
                                SourceLocation TypeidLoc,
                                Expr *E,
                                SourceLocation RParenLoc) {
573
  StringRef UuidStr;
Francois Pichet's avatar
Francois Pichet committed
574
  if (!E->getType()->isDependentType()) {
575
576
577
    if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
      UuidStr = "00000000-0000-0000-0000-000000000000";
    } else {
578
579
580
      llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
      getUuidAttrOfType(*this, E->getType(), UuidAttrs);
      if (UuidAttrs.empty())
581
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
582
583
      if (UuidAttrs.size() > 1)
        return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
584
      UuidStr = UuidAttrs.back()->getGuid();
585
    }
Francois Pichet's avatar
Francois Pichet committed
586
  }
587

588
  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
589
                                     SourceRange(TypeidLoc, RParenLoc));
590
591
592
593
594
595
}

/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
ExprResult
Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
596
  // If MSVCGuidDecl has not been cached, do the lookup.
597
598
599
600
601
602
603
  if (!MSVCGuidDecl) {
    IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
    LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
    LookupQualifiedName(R, Context.getTranslationUnitDecl());
    MSVCGuidDecl = R.getAsSingle<RecordDecl>();
    if (!MSVCGuidDecl)
      return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
604
605
  }

606
  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
607

608
609
  if (isType) {
    // The operand is a type; handle it as such.
610
    TypeSourceInfo *TInfo = nullptr;
611
612
613
614
    QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
                                   &TInfo);
    if (T.isNull())
      return ExprError();
NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
615

616
617
618
619
620
621
    if (!TInfo)
      TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);

    return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
  }

NAKAMURA Takumi's avatar
NAKAMURA Takumi committed
622
  // The operand is an expression.
623
  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
624
625
}

626
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
627
ExprResult
628
Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
629
  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
630
         "Unknown C++ Boolean value!");
631
632
  return new (Context)
      CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
633
}
634

Sebastian Redl's avatar
Sebastian Redl committed
635
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
636
ExprResult
Sebastian Redl's avatar
Sebastian Redl committed
637
Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
638
  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl's avatar
Sebastian Redl committed
639
640
}

641
/// ActOnCXXThrow - Parse throw expressions.
642
ExprResult
643
644
645
646
Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
  bool IsThrownVarInScope = false;
  if (Ex) {
    // C++0x [class.copymove]p31:
647
    //   When certain criteria are met, an implementation is allowed to omit the
648
649
    //   copy/move construction of a class object [...]
    //
650
    //     - in a throw-expression, when the operand is the name of a
651
    //       non-volatile automatic object (other than a function or catch-
652
    //       clause parameter) whose scope does not extend beyond the end of the
653
654
655
    //       innermost enclosing try-block (if there is one), the copy/move
    //       operation from the operand to the exception object (15.1) can be
    //       omitted by constructing the automatic object directly into the
656
657
658
659
660
661
662
663
664
    //       exception object
    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
      if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
        if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
          for( ; S; S = S->getParent()) {
            if (S->isDeclScope(Var)) {
              IsThrownVarInScope = true;
              break;
            }
665

666
667
668
669
670
671
672
673
674
            if (S->getFlags() &
                (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
                 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
                 Scope::TryScope))
              break;
          }
        }
      }
  }
675

676
677
678
  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
}

679
ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
680
                               bool IsThrownVarInScope) {
681
  // Don't report an error if 'throw' is used in system headers.
682
  if (!getLangOpts().CXXExceptions &&
683
      !getSourceManager().isInSystemHeader(OpLoc))
684
    Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
685

686
687
  // Exceptions aren't allowed in CUDA device code.
  if (getLangOpts().CUDA)
688
689
    CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
        << "throw" << CurrentCUDATarget();
690

691
692
693
  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
    Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";

694
  if (Ex && !Ex->isTypeDependent()) {
695
696
    QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
    if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
697
      return ExprError();
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725

    // Initialize the exception result.  This implicitly weeds out
    // abstract types or types with inaccessible copy constructors.

    // C++0x [class.copymove]p31:
    //   When certain criteria are met, an implementation is allowed to omit the
    //   copy/move construction of a class object [...]
    //
    //     - in a throw-expression, when the operand is the name of a
    //       non-volatile automatic object (other than a function or
    //       catch-clause
    //       parameter) whose scope does not extend beyond the end of the
    //       innermost enclosing try-block (if there is one), the copy/move
    //       operation from the operand to the exception object (15.1) can be
    //       omitted by constructing the automatic object directly into the
    //       exception object
    const VarDecl *NRVOVariable = nullptr;
    if (IsThrownVarInScope)
      NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);

    InitializedEntity Entity = InitializedEntity::InitializeException(
        OpLoc, ExceptionObjectTy,
        /*NRVO=*/NRVOVariable != nullptr);
    ExprResult Res = PerformMoveOrCopyInitialization(
        Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
    if (Res.isInvalid())
      return ExprError();
    Ex = Res.get();
726
  }
727

728
729
  return new (Context)
      CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
730
731
}

732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
static void
collectPublicBases(CXXRecordDecl *RD,
                   llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
                   llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
                   llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
                   bool ParentIsPublic) {
  for (const CXXBaseSpecifier &BS : RD->bases()) {
    CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
    bool NewSubobject;
    // Virtual bases constitute the same subobject.  Non-virtual bases are
    // always distinct subobjects.
    if (BS.isVirtual())
      NewSubobject = VBases.insert(BaseDecl).second;
    else
      NewSubobject = true;

    if (NewSubobject)
      ++SubobjectsSeen[BaseDecl];

    // Only add subobjects which have public access throughout the entire chain.
    bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
    if (PublicPath)
      PublicSubobjectsSeen.insert(BaseDecl);

    // Recurse on to each base subobject.
    collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
                       PublicPath);
  }
}

static void getUnambiguousPublicSubobjects(
    CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
  SubobjectsSeen[RD] = 1;
  PublicSubobjectsSeen.insert(RD);
  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
                     /*ParentIsPublic=*/true);

  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
    // Skip ambiguous objects.
    if (SubobjectsSeen[PublicSubobject] > 1)
      continue;

    Objects.push_back(PublicSubobject);
  }
}

781
/// CheckCXXThrowOperand - Validate the operand of a throw.
782
783
bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
                                QualType ExceptionObjectTy, Expr *E) {
784
785
  //   If the type of the exception would be an incomplete type or a pointer
  //   to an incomplete type other than (cv) void the program is ill-formed.
786
  QualType Ty = ExceptionObjectTy;
787
  bool isPointer = false;
Ted Kremenek's avatar
Ted Kremenek committed
788
  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
789
    Ty = Ptr->getPointeeType();
790
    isPointer = true;
791
792
793
  }
  if (!isPointer || !Ty->isVoidType()) {
    if (RequireCompleteType(ThrowLoc, Ty,
794
795
                            isPointer ? diag::err_throw_incomplete_ptr
                                      : diag::err_throw_incomplete,
796
                            E->getSourceRange()))
797
      return true;
798

799
    if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
800
                               diag::err_throw_abstract_type, E))
801
      return true;
802
803
  }

804
  // If the exception has class type, we need additional handling.
805
806
807
  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  if (!RD)
    return false;
808

809
810
  // If we are throwing a polymorphic class type or pointer thereof,
  // exception handling will make use of the vtable.
811
812
  MarkVTableUsed(ThrowLoc, RD);

813
814
  // If a pointer is thrown, the referenced object will not be destroyed.
  if (isPointer)
815
    return false;
816

817
  // If the class has a destructor, we must be able to call it.
818
819
820
821
822
823
  if (!RD->hasIrrelevantDestructor()) {
    if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
      MarkFunctionReferenced(E->getExprLoc(), Destructor);
      CheckDestructorAccess(E->getExprLoc(), Destructor,
                            PDiag(diag::err_access_dtor_exception) << Ty);
      if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
824
        return true;
825
826
    }
  }
827

828
829
830
  // The MSVC ABI creates a list of all types which can catch the exception
  // object.  This list also references the appropriate copy constructor to call
  // if the object is caught by value and has a non-trivial copy constructor.
831
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
832
833
834
    // We are only interested in the public, unambiguous bases contained within
    // the exception object.  Bases which are ambiguous or otherwise
    // inaccessible are not catchable types.
835
836
    llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
    getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
837

838
    for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
      // Attempt to lookup the copy constructor.  Various pieces of machinery
      // will spring into action, like template instantiation, which means this
      // cannot be a simple walk of the class's decls.  Instead, we must perform
      // lookup and overload resolution.
      CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
      if (!CD)
        continue;

      // Mark the constructor referenced as it is used by this throw expression.
      MarkFunctionReferenced(E->getExprLoc(), CD);

      // Skip this copy constructor if it is trivial, we don't need to record it
      // in the catchable type data.
      if (CD->isTrivial())
        continue;

      // The copy constructor is non-trivial, create a mapping from this class
      // type to this constructor.
      // N.B.  The selection of copy constructor is not sensitive to this
      // particular throw-site.  Lookup will be performed at the catch-site to
      // ensure that the copy constructor is, in fact, accessible (via
      // friendship or any other means).
      Context.addCopyConstructorForExceptionObject(Subobject, CD);

      // We don't keep the instantiated default argument expressions around so
      // we must rebuild them here.
      for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
866
867
        if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
          return true;
868
869
870
      }
    }
  }
871

872
  return false;
873
}
874

875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
static QualType adjustCVQualifiersForCXXThisWithinLambda(
    ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
    DeclContext *CurSemaContext, ASTContext &ASTCtx) {

  QualType ClassType = ThisTy->getPointeeType();
  LambdaScopeInfo *CurLSI = nullptr;
  DeclContext *CurDC = CurSemaContext;

  // Iterate through the stack of lambdas starting from the innermost lambda to
  // the outermost lambda, checking if '*this' is ever captured by copy - since
  // that could change the cv-qualifiers of the '*this' object.
  // The object referred to by '*this' starts out with the cv-qualifiers of its
  // member function.  We then start with the innermost lambda and iterate
  // outward checking to see if any lambda performs a by-copy capture of '*this'
  // - and if so, any nested lambda must respect the 'constness' of that
  // capturing lamdbda's call operator.
  //

  // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
  // since ScopeInfos are pushed on during parsing and treetransforming. But
  // since a generic lambda's call operator can be instantiated anywhere (even
  // end of the TU) we need to be able to examine its enclosing lambdas and so
  // we use the DeclContext to get a hold of the closure-class and query it for
  // capture information.  The reason we don't just resort to always using the
  // DeclContext chain is that it is only mature for lambda expressions
  // enclosing generic lambda's call operators that are being instantiated.

  for (int I = FunctionScopes.size();
       I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
       CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
    CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
906
907

    if (!CurLSI->isCXXThisCaptured())
908
        continue;
909

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
    auto C = CurLSI->getCXXThisCapture();

    if (C.isCopyCapture()) {
      ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
      if (CurLSI->CallOperator->isConst())
        ClassType.addConst();
      return ASTCtx.getPointerType(ClassType);
    }
  }
  // We've run out of ScopeInfos but check if CurDC is a lambda (which can
  // happen during instantiation of generic lambdas)
  if (isLambdaCallOperator(CurDC)) {
    assert(CurLSI);
    assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
    assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
925

926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
    auto IsThisCaptured =
        [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
      IsConst = false;
      IsByCopy = false;
      for (auto &&C : Closure->captures()) {
        if (C.capturesThis()) {
          if (C.getCaptureKind() == LCK_StarThis)
            IsByCopy = true;
          if (Closure->getLambdaCallOperator()->isConst())
            IsConst = true;
          return true;
        }
      }
      return false;
    };

    bool IsByCopyCapture = false;
    bool IsConstCapture = false;
    CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
    while (Closure &&
           IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
      if (IsByCopyCapture) {
        ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
        if (IsConstCapture)
          ClassType.addConst();
        return ASTCtx.getPointerType(ClassType);
      }
      Closure = isLambdaCallOperator(Closure->getParent())
                    ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
                    : nullptr;
    }
  }
  return ASTCtx.getPointerType(ClassType);
}

961
962
QualType Sema::getCurrentThisType() {
  DeclContext *DC = getFunctionLevelDeclContext();
963
  QualType ThisTy = CXXThisTypeOverride;
964

965
966
967
968
  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
    if (method && method->isInstance())
      ThisTy = method->getThisType(Context);
  }
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983

  if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
      !ActiveTemplateInstantiations.empty()) {

    assert(isa<CXXRecordDecl>(DC) &&
           "Trying to get 'this' type from static method?");

    // This is a lambda call operator that is being instantiated as a default
    // initializer. DC must point to the enclosing class type, so we can recover
    // the 'this' type from it.

    QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
    // There are no cv-qualifiers for 'this' within default initializers,
    // per [expr.prim.general]p4.
    ThisTy = Context.getPointerType(ClassTy);
984
  }
985
986
987
988
989
990
991

  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
  // might need to be adjusted if the lambda or any of its enclosing lambda's
  // captures '*this' by copy.
  if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
    return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
                                                    CurContext, Context);
992
  return ThisTy;
993
994
}

995
Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
996
997
                                         Decl *ContextDecl,
                                         unsigned CXXThisTypeQuals,
998
                                         bool Enabled)
999
1000
  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
{
For faster browsing, not all history is shown. View entire blame